]> git.sesse.net Git - vlc/blob - modules/video_output/x11/xcommon.c
* modules/video_output/x11/xcommon.c: support on-the-fly ar/cropping in the x11 vout.
[vlc] / modules / video_output / x11 / xcommon.c
1 /*****************************************************************************
2  * xcommon.c: Functions common to the X11 and XVideo plugins
3  *****************************************************************************
4  * Copyright (C) 1998-2001 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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <errno.h>                                                 /* ENOMEM */
31 #include <stdlib.h>                                                /* free() */
32 #include <string.h>                                            /* strerror() */
33
34 #include <vlc/vlc.h>
35 #include <vlc/intf.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_SYS_SHM_H
51 #   include <sys/shm.h>                                /* shmget(), shmctl() */
52 #endif
53
54 #include <X11/Xlib.h>
55 #include <X11/Xproto.h>
56 #include <X11/Xmd.h>
57 #include <X11/Xutil.h>
58 #include <X11/keysym.h>
59 #ifdef HAVE_SYS_SHM_H
60 #   include <X11/extensions/XShm.h>
61 #endif
62 #ifdef DPMSINFO_IN_DPMS_H
63 #   include <X11/extensions/dpms.h>
64 #endif
65
66 #ifdef MODULE_NAME_IS_xvideo
67 #   include <X11/extensions/Xv.h>
68 #   include <X11/extensions/Xvlib.h>
69 #endif
70
71 #ifdef MODULE_NAME_IS_glx
72 #   include <GL/glx.h>
73 #endif
74
75 #ifdef HAVE_XINERAMA
76 #   include <X11/extensions/Xinerama.h>
77 #endif
78
79 #include "xcommon.h"
80
81 /*****************************************************************************
82  * Local prototypes
83  *****************************************************************************/
84 int  E_(Activate)   ( vlc_object_t * );
85 void E_(Deactivate) ( vlc_object_t * );
86
87 static int  InitVideo      ( vout_thread_t * );
88 static void EndVideo       ( vout_thread_t * );
89 static void DisplayVideo   ( vout_thread_t *, picture_t * );
90 static int  ManageVideo    ( vout_thread_t * );
91 static int  Control        ( vout_thread_t *, int, va_list );
92
93 static int  InitDisplay    ( vout_thread_t * );
94
95 static int  CreateWindow   ( vout_thread_t *, x11_window_t * );
96 static void DestroyWindow  ( vout_thread_t *, x11_window_t * );
97
98 static int  NewPicture     ( vout_thread_t *, picture_t * );
99 static void FreePicture    ( vout_thread_t *, picture_t * );
100
101 static IMAGE_TYPE *CreateImage    ( vout_thread_t *,
102                                     Display *, EXTRA_ARGS, int, int );
103 #ifdef HAVE_SYS_SHM_H
104 static IMAGE_TYPE *CreateShmImage ( vout_thread_t *,
105                                     Display *, EXTRA_ARGS_SHM, int, int );
106 static vlc_bool_t b_shm = VLC_TRUE;
107 #endif
108
109 static void ToggleFullScreen      ( vout_thread_t * );
110
111 static void EnableXScreenSaver    ( vout_thread_t * );
112 static void DisableXScreenSaver   ( vout_thread_t * );
113
114 static void CreateCursor   ( vout_thread_t * );
115 static void DestroyCursor  ( vout_thread_t * );
116 static void ToggleCursor   ( vout_thread_t * );
117
118 #ifdef MODULE_NAME_IS_xvideo
119 static int  XVideoGetPort    ( vout_thread_t *, vlc_fourcc_t, vlc_fourcc_t * );
120 static void XVideoReleasePort( vout_thread_t *, int );
121 #endif
122
123 #ifdef MODULE_NAME_IS_x11
124 static void SetPalette     ( vout_thread_t *,
125                              uint16_t *, uint16_t *, uint16_t * );
126 #endif
127
128 static void TestNetWMSupport( vout_thread_t * );
129 static int ConvertKey( int );
130
131 static int WindowOnTop( vout_thread_t *, vlc_bool_t );
132
133 static int X11ErrorHandler( Display *, XErrorEvent * );
134
135 /*****************************************************************************
136  * Activate: allocate X11 video thread output method
137  *****************************************************************************
138  * This function allocate and initialize a X11 vout method. It uses some of the
139  * vout properties to choose the window size, and change them according to the
140  * actual properties of the display.
141  *****************************************************************************/
142 int E_(Activate) ( vlc_object_t *p_this )
143 {
144     vout_thread_t *p_vout = (vout_thread_t *)p_this;
145     char *        psz_display;
146     vlc_value_t   val;
147
148 #ifdef MODULE_NAME_IS_xvideo
149     char *       psz_chroma;
150     vlc_fourcc_t i_chroma = 0;
151     vlc_bool_t   b_chroma = 0;
152 #endif
153
154     p_vout->pf_init = InitVideo;
155     p_vout->pf_end = EndVideo;
156     p_vout->pf_manage = ManageVideo;
157     p_vout->pf_render = NULL;
158     p_vout->pf_display = DisplayVideo;
159     p_vout->pf_control = Control;
160
161     /* Allocate structure */
162     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
163     if( p_vout->p_sys == NULL )
164     {
165         msg_Err( p_vout, "out of memory" );
166         return VLC_ENOMEM;
167     }
168
169     vlc_mutex_init( p_vout, &p_vout->p_sys->lock );
170
171     /* Open display, using the "display" config variable or the DISPLAY
172      * environment variable */
173     psz_display = config_GetPsz( p_vout, MODULE_STRING "-display" );
174
175     p_vout->p_sys->p_display = XOpenDisplay( psz_display );
176
177     if( p_vout->p_sys->p_display == NULL )                          /* error */
178     {
179         msg_Err( p_vout, "cannot open display %s",
180                          XDisplayName( psz_display ) );
181         free( p_vout->p_sys );
182         if( psz_display ) free( psz_display );
183         return VLC_EGENERIC;
184     }
185     if( psz_display ) free( psz_display );
186
187     /* Replace error handler so we can intercept some non-fatal errors */
188     XSetErrorHandler( X11ErrorHandler );
189
190     /* Get a screen ID matching the XOpenDisplay return value */
191     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
192
193 #ifdef MODULE_NAME_IS_xvideo
194     psz_chroma = config_GetPsz( p_vout, "xvideo-chroma" );
195     if( psz_chroma )
196     {
197         if( strlen( psz_chroma ) >= 4 )
198         {
199             /* Do not use direct assignment because we are not sure of the
200              * alignment. */
201             memcpy(&i_chroma, psz_chroma, 4);
202             b_chroma = 1;
203         }
204
205         free( psz_chroma );
206     }
207
208     if( b_chroma )
209     {
210         msg_Dbg( p_vout, "forcing chroma 0x%.8x (%4.4s)",
211                  i_chroma, (char*)&i_chroma );
212     }
213     else
214     {
215         i_chroma = p_vout->render.i_chroma;
216     }
217
218     /* Check that we have access to an XVideo port providing this chroma */
219     p_vout->p_sys->i_xvport = XVideoGetPort( p_vout, VLC2X11_FOURCC(i_chroma),
220                                              &p_vout->output.i_chroma );
221     if( p_vout->p_sys->i_xvport < 0 )
222     {
223         /* If a specific chroma format was requested, then we don't try to
224          * be cleverer than the user. He knew pretty well what he wanted. */
225         if( b_chroma )
226         {
227             XCloseDisplay( p_vout->p_sys->p_display );
228             free( p_vout->p_sys );
229             return VLC_EGENERIC;
230         }
231
232         /* It failed, but it's not completely lost ! We try to open an
233          * XVideo port for an YUY2 picture. We'll need to do an YUV
234          * conversion, but at least it has got scaling. */
235         p_vout->p_sys->i_xvport =
236                         XVideoGetPort( p_vout, X11_FOURCC('Y','U','Y','2'),
237                                                &p_vout->output.i_chroma );
238         if( p_vout->p_sys->i_xvport < 0 )
239         {
240             /* It failed, but it's not completely lost ! We try to open an
241              * XVideo port for a simple 16bpp RGB picture. We'll need to do
242              * an YUV conversion, but at least it has got scaling. */
243             p_vout->p_sys->i_xvport =
244                             XVideoGetPort( p_vout, X11_FOURCC('R','V','1','6'),
245                                                    &p_vout->output.i_chroma );
246             if( p_vout->p_sys->i_xvport < 0 )
247             {
248                 XCloseDisplay( p_vout->p_sys->p_display );
249                 free( p_vout->p_sys );
250                 return VLC_EGENERIC;
251             }
252         }
253     }
254     p_vout->output.i_chroma = X112VLC_FOURCC(p_vout->output.i_chroma);
255 #endif
256
257     /* Create blank cursor (for mouse cursor autohiding) */
258     p_vout->p_sys->i_time_mouse_last_moved = mdate();
259     p_vout->p_sys->b_mouse_pointer_visible = 1;
260     CreateCursor( p_vout );
261
262     /* Set main window's size */
263     p_vout->p_sys->original_window.i_width = p_vout->i_window_width;
264     p_vout->p_sys->original_window.i_height = p_vout->i_window_height;
265     var_Create( p_vout, "video-title", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
266     /* Spawn base window - this window will include the video output window,
267      * but also command buttons, subtitles and other indicators */
268     if( CreateWindow( p_vout, &p_vout->p_sys->original_window ) )
269     {
270         msg_Err( p_vout, "cannot create X11 window" );
271         DestroyCursor( p_vout );
272         XCloseDisplay( p_vout->p_sys->p_display );
273         free( p_vout->p_sys );
274         return VLC_EGENERIC;
275     }
276
277     /* Open and initialize device. */
278     if( InitDisplay( p_vout ) )
279     {
280         msg_Err( p_vout, "cannot initialize X11 display" );
281         DestroyCursor( p_vout );
282         DestroyWindow( p_vout, &p_vout->p_sys->original_window );
283         XCloseDisplay( p_vout->p_sys->p_display );
284         free( p_vout->p_sys );
285         return VLC_EGENERIC;
286     }
287
288     /* Disable screen saver */
289     DisableXScreenSaver( p_vout );
290
291     /* Misc init */
292     p_vout->p_sys->b_altfullscreen = 0;
293     p_vout->p_sys->i_time_button_last_pressed = 0;
294
295     TestNetWMSupport( p_vout );
296
297     /* Variable to indicate if the window should be on top of others */
298     /* Trigger a callback right now */
299     var_Get( p_vout, "video-on-top", &val );
300     var_Set( p_vout, "video-on-top", val );
301
302     return VLC_SUCCESS;
303 }
304
305 /*****************************************************************************
306  * Deactivate: destroy X11 video thread output method
307  *****************************************************************************
308  * Terminate an output method created by Open
309  *****************************************************************************/
310 void E_(Deactivate) ( vlc_object_t *p_this )
311 {
312     vout_thread_t *p_vout = (vout_thread_t *)p_this;
313
314     /* If the fullscreen window is still open, close it */
315     if( p_vout->b_fullscreen )
316     {
317         ToggleFullScreen( p_vout );
318     }
319
320     /* Restore cursor if it was blanked */
321     if( !p_vout->p_sys->b_mouse_pointer_visible )
322     {
323         ToggleCursor( p_vout );
324     }
325
326 #ifdef MODULE_NAME_IS_x11
327     /* Destroy colormap */
328     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
329     {
330         XFreeColormap( p_vout->p_sys->p_display, p_vout->p_sys->colormap );
331     }
332 #elif defined(MODULE_NAME_IS_xvideo)
333     XVideoReleasePort( p_vout, p_vout->p_sys->i_xvport );
334 #endif
335
336     DestroyCursor( p_vout );
337     EnableXScreenSaver( p_vout );
338     DestroyWindow( p_vout, &p_vout->p_sys->original_window );
339
340     XCloseDisplay( p_vout->p_sys->p_display );
341
342     /* Destroy structure */
343     vlc_mutex_destroy( &p_vout->p_sys->lock );
344     free( p_vout->p_sys );
345 }
346
347 /*****************************************************************************
348  * InitVideo: initialize X11 video thread output method
349  *****************************************************************************
350  * This function create the XImages needed by the output thread. It is called
351  * at the beginning of the thread, but also each time the window is resized.
352  *****************************************************************************/
353 static int InitVideo( vout_thread_t *p_vout )
354 {
355     int i_index;
356     picture_t *p_pic;
357
358     I_OUTPUTPICTURES = 0;
359
360 #ifdef MODULE_NAME_IS_xvideo
361     /* Initialize the output structure; we already found an XVideo port,
362      * and the corresponding chroma we will be using. Since we can
363      * arbitrary scale, stick to the coordinates and aspect. */
364     p_vout->output.i_width  = p_vout->render.i_width;
365     p_vout->output.i_height = p_vout->render.i_height;
366     p_vout->output.i_aspect = p_vout->render.i_aspect;
367
368     p_vout->fmt_out = p_vout->fmt_in;
369     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
370
371     switch( p_vout->output.i_chroma )
372     {
373         case VLC_FOURCC('R','V','1','5'):
374             p_vout->output.i_rmask = 0x001f;
375             p_vout->output.i_gmask = 0x07e0;
376             p_vout->output.i_bmask = 0xf800;
377             break;
378         case VLC_FOURCC('R','V','1','6'):
379             p_vout->output.i_rmask = 0x001f;
380             p_vout->output.i_gmask = 0x03e0;
381             p_vout->output.i_bmask = 0x7c00;
382             break;
383     }
384
385 #elif defined(MODULE_NAME_IS_x11)
386     /* Initialize the output structure: RGB with square pixels, whatever
387      * the input format is, since it's the only format we know */
388     switch( p_vout->p_sys->i_screen_depth )
389     {
390         case 8: /* FIXME: set the palette */
391             p_vout->output.i_chroma = VLC_FOURCC('R','G','B','2'); break;
392         case 15:
393             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','5'); break;
394         case 16:
395             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','6'); break;
396         case 24:
397         case 32:
398             p_vout->output.i_chroma = VLC_FOURCC('R','V','3','2'); break;
399         default:
400             msg_Err( p_vout, "unknown screen depth %i",
401                      p_vout->p_sys->i_screen_depth );
402             return VLC_SUCCESS;
403     }
404
405     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
406                        p_vout->p_sys->p_win->i_height,
407                        &i_index, &i_index,
408                        &p_vout->fmt_out.i_visible_width,
409                        &p_vout->fmt_out.i_visible_height );
410
411     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
412
413     p_vout->output.i_width = p_vout->fmt_out.i_width =
414         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_width /
415         p_vout->fmt_in.i_visible_width;
416     p_vout->output.i_height = p_vout->fmt_out.i_height =
417         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_height /
418         p_vout->fmt_in.i_visible_height;
419     p_vout->fmt_out.i_x_offset =
420         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_x_offset /
421         p_vout->fmt_in.i_visible_width;
422     p_vout->fmt_out.i_y_offset =
423         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_y_offset /
424         p_vout->fmt_in.i_visible_height;
425
426     p_vout->fmt_out.i_sar_num = p_vout->fmt_out.i_sar_den = 1;
427     p_vout->output.i_aspect = p_vout->fmt_out.i_aspect =
428         p_vout->fmt_out.i_width * VOUT_ASPECT_FACTOR /p_vout->fmt_out.i_height;
429
430     msg_Dbg( p_vout, "x11 image size %ix%i (%i,%i,%ix%i)",
431              p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
432              p_vout->fmt_out.i_x_offset, p_vout->fmt_out.i_y_offset,
433              p_vout->fmt_out.i_visible_width,
434              p_vout->fmt_out.i_visible_height );
435 #endif
436
437     /* Try to initialize up to MAX_DIRECTBUFFERS direct buffers */
438     while( I_OUTPUTPICTURES < MAX_DIRECTBUFFERS )
439     {
440         p_pic = NULL;
441
442         /* Find an empty picture slot */
443         for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
444         {
445           if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
446             {
447                 p_pic = p_vout->p_picture + i_index;
448                 break;
449             }
450         }
451
452         /* Allocate the picture */
453         if( p_pic == NULL || NewPicture( p_vout, p_pic ) )
454         {
455             break;
456         }
457
458         p_pic->i_status = DESTROYED_PICTURE;
459         p_pic->i_type   = DIRECT_PICTURE;
460
461         PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
462
463         I_OUTPUTPICTURES++;
464     }
465
466     if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
467     {
468         /* U and V inverted compared to I420
469          * Fixme: this should be handled by the vout core */
470         p_vout->output.i_chroma = VLC_FOURCC('I','4','2','0');
471         p_vout->fmt_out.i_chroma = VLC_FOURCC('I','4','2','0');
472     }
473
474     return VLC_SUCCESS;
475 }
476
477 /*****************************************************************************
478  * DisplayVideo: displays previously rendered output
479  *****************************************************************************
480  * This function sends the currently rendered image to X11 server.
481  * (The Xv extension takes care of "double-buffering".)
482  *****************************************************************************/
483 static void DisplayVideo( vout_thread_t *p_vout, picture_t *p_pic )
484 {
485     int i_width, i_height, i_x, i_y;
486
487     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
488                        p_vout->p_sys->p_win->i_height,
489                        &i_x, &i_y, &i_width, &i_height );
490
491     vlc_mutex_lock( &p_vout->p_sys->lock );
492
493 #ifdef HAVE_SYS_SHM_H
494     if( p_vout->p_sys->b_shm )
495     {
496         /* Display rendered image using shared memory extension */
497 #   ifdef MODULE_NAME_IS_xvideo
498         XvShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
499                        p_vout->p_sys->p_win->video_window,
500                        p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
501                        p_vout->fmt_out.i_x_offset,
502                        p_vout->fmt_out.i_y_offset,
503                        p_vout->fmt_out.i_visible_width,
504                        p_vout->fmt_out.i_visible_height,
505                        0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height,
506                        False /* Don't put True here or you'll waste your CPU */ );
507 #   else
508         XShmPutImage( p_vout->p_sys->p_display,
509                       p_vout->p_sys->p_win->video_window,
510                       p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
511                       p_vout->fmt_out.i_x_offset,
512                       p_vout->fmt_out.i_y_offset,
513                       0 /*dest_x*/, 0 /*dest_y*/,
514                       p_vout->fmt_out.i_visible_width,
515                       p_vout->fmt_out.i_visible_height,
516                       False /* Don't put True here ! */ );
517 #   endif
518     }
519     else
520 #endif /* HAVE_SYS_SHM_H */
521     {
522         /* Use standard XPutImage -- this is gonna be slow ! */
523 #ifdef MODULE_NAME_IS_xvideo
524         XvPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
525                     p_vout->p_sys->p_win->video_window,
526                     p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
527                     p_vout->fmt_out.i_x_offset,
528                     p_vout->fmt_out.i_y_offset,
529                     p_vout->fmt_out.i_visible_width,
530                     p_vout->fmt_out.i_visible_height,
531                     0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height );
532 #else
533         XPutImage( p_vout->p_sys->p_display,
534                    p_vout->p_sys->p_win->video_window,
535                    p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
536                    p_vout->fmt_out.i_x_offset,
537                    p_vout->fmt_out.i_y_offset,
538                    0 /*dest_x*/, 0 /*dest_y*/,
539                    p_vout->fmt_out.i_visible_width,
540                    p_vout->fmt_out.i_visible_height );
541 #endif
542     }
543
544     /* Make sure the command is sent now - do NOT use XFlush !*/
545     XSync( p_vout->p_sys->p_display, False );
546
547     vlc_mutex_unlock( &p_vout->p_sys->lock );
548 }
549
550 /*****************************************************************************
551  * ManageVideo: handle X11 events
552  *****************************************************************************
553  * This function should be called regularly by video output thread. It manages
554  * X11 events and allows window resizing. It returns a non null value on
555  * error.
556  *****************************************************************************/
557 static int ManageVideo( vout_thread_t *p_vout )
558 {
559     XEvent      xevent;                                         /* X11 event */
560     vlc_value_t val;
561
562     vlc_mutex_lock( &p_vout->p_sys->lock );
563
564     /* Handle events from the owner window */
565     if( p_vout->p_sys->p_win->owner_window )
566     {
567         while( XCheckWindowEvent( p_vout->p_sys->p_display,
568                                   p_vout->p_sys->p_win->owner_window,
569                                   StructureNotifyMask, &xevent ) == True )
570         {
571             /* ConfigureNotify event: prepare  */
572             if( xevent.type == ConfigureNotify )
573             {
574                 /* Update dimensions */
575                 XResizeWindow( p_vout->p_sys->p_display,
576                                p_vout->p_sys->p_win->base_window,
577                                xevent.xconfigure.width,
578                                xevent.xconfigure.height );
579             }
580         }
581     }
582
583     /* Handle X11 events: ConfigureNotify events are parsed to know if the
584      * output window's size changed, MapNotify and UnmapNotify to know if the
585      * window is mapped (and if the display is useful), and ClientMessages
586      * to intercept window destruction requests */
587
588     while( XCheckWindowEvent( p_vout->p_sys->p_display,
589                               p_vout->p_sys->p_win->base_window,
590                               StructureNotifyMask | KeyPressMask |
591                               ButtonPressMask | ButtonReleaseMask |
592                               PointerMotionMask | Button1MotionMask , &xevent )
593            == True )
594     {
595         /* ConfigureNotify event: prepare  */
596         if( xevent.type == ConfigureNotify )
597         {
598             if( (unsigned int)xevent.xconfigure.width
599                    != p_vout->p_sys->p_win->i_width
600               || (unsigned int)xevent.xconfigure.height
601                     != p_vout->p_sys->p_win->i_height )
602             {
603                 /* Update dimensions */
604                 p_vout->i_changes |= VOUT_SIZE_CHANGE;
605                 p_vout->p_sys->p_win->i_width = xevent.xconfigure.width;
606                 p_vout->p_sys->p_win->i_height = xevent.xconfigure.height;
607             }
608         }
609         /* Keyboard event */
610         else if( xevent.type == KeyPress )
611         {
612             unsigned int state = xevent.xkey.state;
613             KeySym x_key_symbol;
614             char i_key;                                   /* ISO Latin-1 key */
615
616             /* We may have keys like F1 trough F12, ESC ... */
617             x_key_symbol = XKeycodeToKeysym( p_vout->p_sys->p_display,
618                                              xevent.xkey.keycode, 0 );
619             val.i_int = ConvertKey( (int)x_key_symbol );
620
621             xevent.xkey.state &= ~ShiftMask;
622             xevent.xkey.state &= ~ControlMask;
623             xevent.xkey.state &= ~Mod1Mask;
624
625             if( !val.i_int &&
626                 XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
627             {
628                 /* "Normal Keys"
629                  * The reason why I use this instead of XK_0 is that
630                  * with XLookupString, we don't have to care about
631                  * keymaps. */
632                 val.i_int = i_key;
633             }
634
635             if( val.i_int )
636             {
637                 if( state & ShiftMask )
638                 {
639                     val.i_int |= KEY_MODIFIER_SHIFT;
640                 }
641                 if( state & ControlMask )
642                 {
643                     val.i_int |= KEY_MODIFIER_CTRL;
644                 }
645                 if( state & Mod1Mask )
646                 {
647                     val.i_int |= KEY_MODIFIER_ALT;
648                 }
649                 var_Set( p_vout->p_vlc, "key-pressed", val );
650             }
651         }
652         /* Mouse click */
653         else if( xevent.type == ButtonPress )
654         {
655             switch( ((XButtonEvent *)&xevent)->button )
656             {
657                 case Button1:
658                     var_Get( p_vout, "mouse-button-down", &val );
659                     val.i_int |= 1;
660                     var_Set( p_vout, "mouse-button-down", val );
661
662                     /* detect double-clicks */
663                     if( ( ((XButtonEvent *)&xevent)->time -
664                           p_vout->p_sys->i_time_button_last_pressed ) < 300 )
665                     {
666                         p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
667                     }
668
669                     p_vout->p_sys->i_time_button_last_pressed =
670                         ((XButtonEvent *)&xevent)->time;
671                     break;
672                 case Button2:
673                     var_Get( p_vout, "mouse-button-down", &val );
674                     val.i_int |= 2;
675                     var_Set( p_vout, "mouse-button-down", val );
676                     break;
677
678                 case Button3:
679                     var_Get( p_vout, "mouse-button-down", &val );
680                     val.i_int |= 4;
681                     var_Set( p_vout, "mouse-button-down", val );
682                     break;
683
684                 case Button4:
685                     var_Get( p_vout, "mouse-button-down", &val );
686                     val.i_int |= 8;
687                     var_Set( p_vout, "mouse-button-down", val );
688                     break;
689
690                 case Button5:
691                     var_Get( p_vout, "mouse-button-down", &val );
692                     val.i_int |= 16;
693                     var_Set( p_vout, "mouse-button-down", val );
694                     break;
695             }
696         }
697         /* Mouse release */
698         else if( xevent.type == ButtonRelease )
699         {
700             switch( ((XButtonEvent *)&xevent)->button )
701             {
702                 case Button1:
703                     var_Get( p_vout, "mouse-button-down", &val );
704                     val.i_int &= ~1;
705                     var_Set( p_vout, "mouse-button-down", val );
706
707                     val.b_bool = VLC_TRUE;
708                     var_Set( p_vout, "mouse-clicked", val );
709                     break;
710
711                 case Button2:
712                     {
713                         playlist_t *p_playlist;
714
715                         var_Get( p_vout, "mouse-button-down", &val );
716                         val.i_int &= ~2;
717                         var_Set( p_vout, "mouse-button-down", val );
718
719                         p_playlist = vlc_object_find( p_vout,
720                                                       VLC_OBJECT_PLAYLIST,
721                                                       FIND_ANYWHERE );
722                         if( p_playlist != NULL )
723                         {
724                             vlc_value_t val;
725                             var_Get( p_playlist, "intf-show", &val );
726                             val.b_bool = !val.b_bool;
727                             var_Set( p_playlist, "intf-show", val );
728                             vlc_object_release( p_playlist );
729                         }
730                     }
731                     break;
732
733                 case Button3:
734                     {
735                         intf_thread_t *p_intf;
736                         playlist_t *p_playlist;
737
738                         var_Get( p_vout, "mouse-button-down", &val );
739                         val.i_int &= ~4;
740                         var_Set( p_vout, "mouse-button-down", val );
741                         p_intf = vlc_object_find( p_vout, VLC_OBJECT_INTF,
742                                                           FIND_ANYWHERE );
743                         if( p_intf )
744                         {
745                             p_intf->b_menu_change = 1;
746                             vlc_object_release( p_intf );
747                         }
748
749                         p_playlist = vlc_object_find( p_vout,
750                                                       VLC_OBJECT_PLAYLIST,
751                                                       FIND_ANYWHERE );
752                         if( p_playlist != NULL )
753                         {
754                             vlc_value_t val; val.b_bool = VLC_TRUE;
755                             var_Set( p_playlist, "intf-popupmenu", val );
756                             vlc_object_release( p_playlist );
757                         }
758                     }
759                     break;
760
761                 case Button4:
762                     var_Get( p_vout, "mouse-button-down", &val );
763                     val.i_int &= ~8;
764                     var_Set( p_vout, "mouse-button-down", val );
765                     break;
766
767                 case Button5:
768                     var_Get( p_vout, "mouse-button-down", &val );
769                     val.i_int &= ~16;
770                     var_Set( p_vout, "mouse-button-down", val );
771                     break;
772
773             }
774         }
775         /* Mouse move */
776         else if( xevent.type == MotionNotify )
777         {
778             int i_width, i_height, i_x, i_y;
779             vlc_value_t val;
780
781             /* somewhat different use for vout_PlacePicture:
782              * here the values are needed to give to mouse coordinates
783              * in the original picture space */
784             vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
785                                p_vout->p_sys->p_win->i_height,
786                                &i_x, &i_y, &i_width, &i_height );
787
788             val.i_int = ( xevent.xmotion.x - i_x )
789                          * p_vout->render.i_width / i_width;
790             var_Set( p_vout, "mouse-x", val );
791             val.i_int = ( xevent.xmotion.y - i_y )
792                          * p_vout->render.i_height / i_height;
793             var_Set( p_vout, "mouse-y", val );
794
795             val.b_bool = VLC_TRUE;
796             var_Set( p_vout, "mouse-moved", val );
797
798             p_vout->p_sys->i_time_mouse_last_moved = mdate();
799             if( ! p_vout->p_sys->b_mouse_pointer_visible )
800             {
801                 ToggleCursor( p_vout );
802             }
803         }
804         else if( xevent.type == ReparentNotify /* XXX: why do we get this? */
805                   || xevent.type == MapNotify
806                   || xevent.type == UnmapNotify )
807         {
808             /* Ignore these events */
809         }
810         else /* Other events */
811         {
812             msg_Warn( p_vout, "unhandled event %d received", xevent.type );
813         }
814     }
815
816     /* Handle events for video output sub-window */
817     while( XCheckWindowEvent( p_vout->p_sys->p_display,
818                               p_vout->p_sys->p_win->video_window,
819                               ExposureMask, &xevent ) == True )
820     {
821         /* Window exposed (only handled if stream playback is paused) */
822         if( xevent.type == Expose )
823         {
824             if( ((XExposeEvent *)&xevent)->count == 0 )
825             {
826                 /* (if this is the last a collection of expose events...) */
827 #if 0
828                 if( p_vout->p_vlc->p_input_bank->pp_input[0] != NULL )
829                 {
830                     if( PAUSE_S == p_vout->p_vlc->p_input_bank->pp_input[0]
831                                                    ->stream.control.i_status )
832                     {
833                         /* XVideoDisplay( p_vout )*/;
834                     }
835                 }
836 #endif
837             }
838         }
839     }
840
841     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
842      * are handled - according to the man pages, the format is always 32
843      * in this case */
844     while( XCheckTypedEvent( p_vout->p_sys->p_display,
845                              ClientMessage, &xevent ) )
846     {
847         if( (xevent.xclient.message_type == p_vout->p_sys->p_win->wm_protocols)
848                && ((Atom)xevent.xclient.data.l[0]
849                      == p_vout->p_sys->p_win->wm_delete_window ) )
850         {
851             /* the user wants to close the window */
852             playlist_t * p_playlist =
853                 (playlist_t *)vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
854                                                FIND_ANYWHERE );
855             if( p_playlist != NULL )
856             {
857                 playlist_Stop( p_playlist );
858                 vlc_object_release( p_playlist );
859             }
860         }
861     }
862
863     /*
864      * Fullscreen Change
865      */
866     if ( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
867     {
868         vlc_value_t val;
869
870         /* Update the object variable and trigger callback */
871         val.b_bool = !p_vout->b_fullscreen;
872         var_Set( p_vout, "fullscreen", val );
873
874         ToggleFullScreen( p_vout );
875         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
876     }
877
878     if( p_vout->i_changes & VOUT_CROP_CHANGE ||
879         p_vout->i_changes & VOUT_ASPECT_CHANGE )
880     {
881         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
882         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
883
884         p_vout->fmt_out.i_x_offset = p_vout->fmt_in.i_x_offset;
885         p_vout->fmt_out.i_y_offset = p_vout->fmt_in.i_y_offset;
886         p_vout->fmt_out.i_visible_width = p_vout->fmt_in.i_visible_width;
887         p_vout->fmt_out.i_visible_height = p_vout->fmt_in.i_visible_height;
888         p_vout->fmt_out.i_aspect = p_vout->fmt_in.i_aspect;
889         p_vout->fmt_out.i_sar_num = p_vout->fmt_in.i_sar_num;
890         p_vout->fmt_out.i_sar_den = p_vout->fmt_in.i_sar_den;
891         p_vout->output.i_aspect = p_vout->fmt_in.i_aspect;
892
893         p_vout->i_changes |= VOUT_SIZE_CHANGE;
894     }
895
896     /*
897      * Size change
898      *
899      * (Needs to be placed after VOUT_FULLSREEN_CHANGE because we can activate
900      *  the size flag inside the fullscreen routine)
901      */
902     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
903     {
904         int i_width, i_height, i_x, i_y;
905
906         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
907
908 #ifdef MODULE_NAME_IS_x11
909         /* We need to signal the vout thread about the size change because it
910          * is doing the rescaling */
911         p_vout->i_changes |= VOUT_SIZE_CHANGE;
912 #endif
913
914         vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
915                            p_vout->p_sys->p_win->i_height,
916                            &i_x, &i_y, &i_width, &i_height );
917
918         XMoveResizeWindow( p_vout->p_sys->p_display,
919                            p_vout->p_sys->p_win->video_window,
920                            i_x, i_y, i_width, i_height );
921     }
922
923     /* Autohide Cursour */
924     if( mdate() - p_vout->p_sys->i_time_mouse_last_moved > 2000000 )
925     {
926         /* Hide the mouse automatically */
927         if( p_vout->p_sys->b_mouse_pointer_visible )
928         {
929             ToggleCursor( p_vout );
930         }
931     }
932
933     vlc_mutex_unlock( &p_vout->p_sys->lock );
934
935     return 0;
936 }
937
938 /*****************************************************************************
939  * EndVideo: terminate X11 video thread output method
940  *****************************************************************************
941  * Destroy the X11 XImages created by Init. It is called at the end of
942  * the thread, but also each time the window is resized.
943  *****************************************************************************/
944 static void EndVideo( vout_thread_t *p_vout )
945 {
946     int i_index;
947
948     /* Free the direct buffers we allocated */
949     for( i_index = I_OUTPUTPICTURES ; i_index ; )
950     {
951         i_index--;
952         FreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
953     }
954 }
955
956 /* following functions are local */
957
958 /*****************************************************************************
959  * CreateWindow: open and set-up X11 main window
960  *****************************************************************************/
961 static int CreateWindow( vout_thread_t *p_vout, x11_window_t *p_win )
962 {
963     XSizeHints              xsize_hints;
964     XSetWindowAttributes    xwindow_attributes;
965     XGCValues               xgcvalues;
966     XEvent                  xevent;
967
968     vlc_bool_t              b_expose = VLC_FALSE;
969     vlc_bool_t              b_configure_notify = VLC_FALSE;
970     vlc_bool_t              b_map_notify = VLC_FALSE;
971     vlc_value_t             val;
972
973     /* Prepare window manager hints and properties */
974     p_win->wm_protocols =
975              XInternAtom( p_vout->p_sys->p_display, "WM_PROTOCOLS", True );
976     p_win->wm_delete_window =
977              XInternAtom( p_vout->p_sys->p_display, "WM_DELETE_WINDOW", True );
978
979     /* Never have a 0-pixel-wide window */
980     xsize_hints.min_width = 2;
981     xsize_hints.min_height = 1;
982
983     /* Prepare window attributes */
984     xwindow_attributes.backing_store = Always;       /* save the hidden part */
985     xwindow_attributes.background_pixel = BlackPixel(p_vout->p_sys->p_display,
986                                                      p_vout->p_sys->i_screen);
987     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
988
989     if( !p_vout->b_fullscreen )
990     {
991         p_win->owner_window =
992             (Window)vout_RequestWindow( p_vout, &p_win->i_x, &p_win->i_y,
993                                         &p_win->i_width, &p_win->i_height );
994
995         xsize_hints.base_width  = xsize_hints.width = p_win->i_width;
996         xsize_hints.base_height = xsize_hints.height = p_win->i_height;
997         xsize_hints.flags       = PSize | PMinSize;
998
999         if( p_win->i_x >=0 || p_win->i_y >= 0 )
1000         {
1001             xsize_hints.x = p_win->i_x;
1002             xsize_hints.y = p_win->i_y;
1003             xsize_hints.flags |= PPosition;
1004         }
1005     }
1006     else
1007     {
1008         /* Fullscreen window size and position */
1009         p_win->owner_window = 0;
1010         p_win->i_x = p_win->i_y = 0;
1011         p_win->i_width =
1012             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1013         p_win->i_height =
1014             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1015     }
1016
1017     if( !p_win->owner_window )
1018     {
1019         /* Create the window and set hints - the window must receive
1020          * ConfigureNotify events, and until it is displayed, Expose and
1021          * MapNotify events. */
1022
1023         p_win->base_window =
1024             XCreateWindow( p_vout->p_sys->p_display,
1025                            DefaultRootWindow( p_vout->p_sys->p_display ),
1026                            p_win->i_x, p_win->i_y,
1027                            p_win->i_width, p_win->i_height,
1028                            0,
1029                            0, InputOutput, 0,
1030                            CWBackingStore | CWBackPixel | CWEventMask,
1031                            &xwindow_attributes );
1032
1033         if( !p_vout->b_fullscreen )
1034         {
1035             /* Set window manager hints and properties: size hints, command,
1036              * window's name, and accepted protocols */
1037             XSetWMNormalHints( p_vout->p_sys->p_display,
1038                                p_win->base_window, &xsize_hints );
1039             XSetCommand( p_vout->p_sys->p_display, p_win->base_window,
1040                          p_vout->p_vlc->ppsz_argv, p_vout->p_vlc->i_argc );
1041
1042             if( !var_GetBool( p_vout, "video-deco") )
1043             {
1044                 Atom prop;
1045                 mwmhints_t mwmhints;
1046
1047                 mwmhints.flags = MWM_HINTS_DECORATIONS;
1048                 mwmhints.decorations = False;
1049
1050                 prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1051                                     False );
1052
1053                 XChangeProperty( p_vout->p_sys->p_display,
1054                                  p_win->base_window,
1055                                  prop, prop, 32, PropModeReplace,
1056                                  (unsigned char *)&mwmhints,
1057                                  PROP_MWM_HINTS_ELEMENTS );
1058             }
1059             else
1060             {
1061                  var_Get( p_vout, "video-title", &val );
1062                  if( !val.psz_string || !*val.psz_string )
1063                  {
1064                     XStoreName( p_vout->p_sys->p_display, p_win->base_window,
1065 #ifdef MODULE_NAME_IS_x11
1066                                 VOUT_TITLE " (X11 output)"
1067 #elif defined(MODULE_NAME_IS_glx)
1068                                 VOUT_TITLE " (GLX output)"
1069 #else
1070                                 VOUT_TITLE " (XVideo output)"
1071 #endif
1072                       );
1073                 }
1074                 else
1075                 {
1076                     XStoreName( p_vout->p_sys->p_display,
1077                                p_win->base_window, val.psz_string );
1078                 }
1079             }
1080         }
1081     }
1082     else
1083     {
1084         Window dummy1;
1085         unsigned int dummy2, dummy3;
1086
1087         /* Select events we are interested in. */
1088         XSelectInput( p_vout->p_sys->p_display, p_win->owner_window,
1089                       StructureNotifyMask );
1090
1091         /* Get the parent window's geometry information */
1092         XGetGeometry( p_vout->p_sys->p_display, p_win->owner_window,
1093                       &dummy1, &dummy2, &dummy3,
1094                       &p_win->i_width,
1095                       &p_win->i_height,
1096                       &dummy2, &dummy3 );
1097
1098         /* We are already configured */
1099         b_configure_notify = VLC_TRUE;
1100
1101         /* From man XSelectInput: only one client at a time can select a
1102          * ButtonPress event, so we need to open a new window anyway. */
1103         p_win->base_window =
1104             XCreateWindow( p_vout->p_sys->p_display,
1105                            p_win->owner_window,
1106                            0, 0,
1107                            p_win->i_width, p_win->i_height,
1108                            0,
1109                            0, CopyFromParent, 0,
1110                            CWBackingStore | CWBackPixel | CWEventMask,
1111                            &xwindow_attributes );
1112     }
1113
1114     if( (p_win->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1115         || (p_win->wm_delete_window == None)
1116         || !XSetWMProtocols( p_vout->p_sys->p_display, p_win->base_window,
1117                              &p_win->wm_delete_window, 1 ) )
1118     {
1119         /* WM_DELETE_WINDOW is not supported by window manager */
1120         msg_Warn( p_vout, "missing or bad window manager" );
1121     }
1122
1123     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1124      * event when using functions like XCopyArea */
1125     xgcvalues.graphics_exposures = False;
1126     p_win->gc = XCreateGC( p_vout->p_sys->p_display,
1127                            p_win->base_window,
1128                            GCGraphicsExposures, &xgcvalues );
1129
1130     /* Send orders to server, and wait until window is displayed - three
1131      * events must be received: a MapNotify event, an Expose event allowing
1132      * drawing in the window, and a ConfigureNotify to get the window
1133      * dimensions. Once those events have been received, only
1134      * ConfigureNotify events need to be received. */
1135     XMapWindow( p_vout->p_sys->p_display, p_win->base_window );
1136     do
1137     {
1138         XWindowEvent( p_vout->p_sys->p_display, p_win->base_window,
1139                       SubstructureNotifyMask | StructureNotifyMask |
1140                       ExposureMask, &xevent);
1141         if( (xevent.type == Expose)
1142             && (xevent.xexpose.window == p_win->base_window) )
1143         {
1144             b_expose = VLC_TRUE;
1145             /* ConfigureNotify isn't sent if there isn't a window manager.
1146              * Expose should be the last event to be received so it should
1147              * be fine to assume we won't receive it anymore. */
1148             b_configure_notify = VLC_TRUE;
1149         }
1150         else if( (xevent.type == MapNotify)
1151                  && (xevent.xmap.window == p_win->base_window) )
1152         {
1153             b_map_notify = VLC_TRUE;
1154         }
1155         else if( (xevent.type == ConfigureNotify)
1156                  && (xevent.xconfigure.window == p_win->base_window) )
1157         {
1158             b_configure_notify = VLC_TRUE;
1159             p_win->i_width = xevent.xconfigure.width;
1160             p_win->i_height = xevent.xconfigure.height;
1161         }
1162     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1163
1164     XSelectInput( p_vout->p_sys->p_display, p_win->base_window,
1165                   StructureNotifyMask | KeyPressMask |
1166                   ButtonPressMask | ButtonReleaseMask |
1167                   PointerMotionMask );
1168
1169 #ifdef MODULE_NAME_IS_x11
1170     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1171     {
1172         /* Allocate a new palette */
1173         p_vout->p_sys->colormap =
1174             XCreateColormap( p_vout->p_sys->p_display,
1175                              DefaultRootWindow( p_vout->p_sys->p_display ),
1176                              DefaultVisual( p_vout->p_sys->p_display,
1177                                             p_vout->p_sys->i_screen ),
1178                              AllocAll );
1179
1180         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1181         XChangeWindowAttributes( p_vout->p_sys->p_display, p_win->base_window,
1182                                  CWColormap, &xwindow_attributes );
1183     }
1184 #endif
1185
1186     /* Create video output sub-window. */
1187     p_win->video_window =  XCreateSimpleWindow(
1188                                       p_vout->p_sys->p_display,
1189                                       p_win->base_window, 0, 0,
1190                                       p_win->i_width, p_win->i_height,
1191                                       0,
1192                                       BlackPixel( p_vout->p_sys->p_display,
1193                                                   p_vout->p_sys->i_screen ),
1194                                       WhitePixel( p_vout->p_sys->p_display,
1195                                                   p_vout->p_sys->i_screen ) );
1196
1197     XSetWindowBackground( p_vout->p_sys->p_display, p_win->video_window,
1198                           BlackPixel( p_vout->p_sys->p_display,
1199                                       p_vout->p_sys->i_screen ) );
1200
1201     XMapWindow( p_vout->p_sys->p_display, p_win->video_window );
1202     XSelectInput( p_vout->p_sys->p_display, p_win->video_window,
1203                   ExposureMask );
1204
1205     /* make sure the video window will be centered in the next ManageVideo() */
1206     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1207
1208     /* If the cursor was formerly blank than blank it again */
1209     if( !p_vout->p_sys->b_mouse_pointer_visible )
1210     {
1211         ToggleCursor( p_vout );
1212         ToggleCursor( p_vout );
1213     }
1214
1215     /* Do NOT use XFlush here ! */
1216     XSync( p_vout->p_sys->p_display, False );
1217
1218     /* At this stage, the window is open, displayed, and ready to
1219      * receive data */
1220     p_vout->p_sys->p_win = p_win;
1221
1222     return VLC_SUCCESS;
1223 }
1224
1225 /*****************************************************************************
1226  * DestroyWindow: destroy the window
1227  *****************************************************************************
1228  *
1229  *****************************************************************************/
1230 static void DestroyWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1231 {
1232     /* Do NOT use XFlush here ! */
1233     XSync( p_vout->p_sys->p_display, False );
1234
1235     if( p_win->video_window != None )
1236         XDestroyWindow( p_vout->p_sys->p_display, p_win->video_window );
1237
1238     XFreeGC( p_vout->p_sys->p_display, p_win->gc );
1239
1240     XUnmapWindow( p_vout->p_sys->p_display, p_win->base_window );
1241     XDestroyWindow( p_vout->p_sys->p_display, p_win->base_window );
1242
1243     if( p_win->owner_window )
1244         vout_ReleaseWindow( p_vout, (void *)p_win->owner_window );
1245 }
1246
1247 /*****************************************************************************
1248  * NewPicture: allocate a picture
1249  *****************************************************************************
1250  * Returns 0 on success, -1 otherwise
1251  *****************************************************************************/
1252 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1253 {
1254 #ifndef MODULE_NAME_IS_glx
1255
1256 #ifdef MODULE_NAME_IS_xvideo
1257     int i_plane;
1258 #endif
1259
1260     /* We know the chroma, allocate a buffer which will be used
1261      * directly by the decoder */
1262     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1263
1264     if( p_pic->p_sys == NULL )
1265     {
1266         return -1;
1267     }
1268
1269     /* Fill in picture_t fields */
1270     vout_InitPicture( VLC_OBJECT(p_vout), p_pic, p_vout->output.i_chroma,
1271                       p_vout->output.i_width, p_vout->output.i_height,
1272                       p_vout->output.i_aspect );
1273
1274 #ifdef HAVE_SYS_SHM_H
1275     if( p_vout->p_sys->b_shm )
1276     {
1277         /* Create image using XShm extension */
1278         p_pic->p_sys->p_image =
1279             CreateShmImage( p_vout, p_vout->p_sys->p_display,
1280 #   ifdef MODULE_NAME_IS_xvideo
1281                             p_vout->p_sys->i_xvport, 
1282                             VLC2X11_FOURCC(p_vout->output.i_chroma),
1283 #   else
1284                             p_vout->p_sys->p_visual,
1285                             p_vout->p_sys->i_screen_depth,
1286 #   endif
1287                             &p_pic->p_sys->shminfo,
1288                             p_vout->output.i_width, p_vout->output.i_height );
1289     }
1290
1291     if( !p_vout->p_sys->b_shm || !p_pic->p_sys->p_image )
1292 #endif /* HAVE_SYS_SHM_H */
1293     {
1294         /* Create image without XShm extension */
1295         p_pic->p_sys->p_image =
1296             CreateImage( p_vout, p_vout->p_sys->p_display,
1297 #ifdef MODULE_NAME_IS_xvideo
1298                          p_vout->p_sys->i_xvport, 
1299                          VLC2X11_FOURCC(p_vout->output.i_chroma),
1300                          p_pic->format.i_bits_per_pixel,
1301 #else
1302                          p_vout->p_sys->p_visual,
1303                          p_vout->p_sys->i_screen_depth,
1304                          p_vout->p_sys->i_bytes_per_pixel,
1305 #endif
1306                          p_vout->output.i_width, p_vout->output.i_height );
1307
1308 #ifdef HAVE_SYS_SHM_H
1309         if( p_pic->p_sys->p_image && p_vout->p_sys->b_shm )
1310         {
1311             msg_Warn( p_vout, "couldn't create SHM image, disabling SHM." );
1312             p_vout->p_sys->b_shm = VLC_FALSE;
1313         }
1314 #endif /* HAVE_SYS_SHM_H */
1315     }
1316
1317     if( p_pic->p_sys->p_image == NULL )
1318     {
1319         free( p_pic->p_sys );
1320         return -1;
1321     }
1322
1323     switch( p_vout->output.i_chroma )
1324     {
1325 #ifdef MODULE_NAME_IS_xvideo
1326         case VLC_FOURCC('I','4','2','0'):
1327         case VLC_FOURCC('Y','V','1','2'):
1328         case VLC_FOURCC('Y','2','1','1'):
1329         case VLC_FOURCC('Y','U','Y','2'):
1330         case VLC_FOURCC('U','Y','V','Y'):
1331         case VLC_FOURCC('R','V','1','5'):
1332         case VLC_FOURCC('R','V','1','6'):
1333         case VLC_FOURCC('R','V','2','4'): /* Fixme: pixel pitch == 4 ? */
1334         case VLC_FOURCC('R','V','3','2'):
1335
1336             for( i_plane = 0; i_plane < p_pic->p_sys->p_image->num_planes;
1337                  i_plane++ )
1338             {
1339                 p_pic->p[i_plane].p_pixels = p_pic->p_sys->p_image->data
1340                     + p_pic->p_sys->p_image->offsets[i_plane];
1341                 p_pic->p[i_plane].i_pitch =
1342                     p_pic->p_sys->p_image->pitches[i_plane];
1343             }
1344             if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
1345             {
1346                 /* U and V inverted compared to I420
1347                  * Fixme: this should be handled by the vout core */
1348                 p_pic->U_PIXELS = p_pic->p_sys->p_image->data
1349                     + p_pic->p_sys->p_image->offsets[2];
1350                 p_pic->V_PIXELS = p_pic->p_sys->p_image->data
1351                     + p_pic->p_sys->p_image->offsets[1];
1352             }
1353             break;
1354
1355 #else
1356         case VLC_FOURCC('R','G','B','2'):
1357         case VLC_FOURCC('R','V','1','6'):
1358         case VLC_FOURCC('R','V','1','5'):
1359         case VLC_FOURCC('R','V','2','4'):
1360         case VLC_FOURCC('R','V','3','2'):
1361
1362             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
1363             p_pic->p->i_visible_lines = p_pic->p_sys->p_image->height;
1364             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1365                                   + p_pic->p_sys->p_image->xoffset;
1366             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
1367
1368             /* p_pic->p->i_pixel_pitch = 4 for RV24 but this should be set
1369              * properly by vout_InitPicture() */
1370             p_pic->p->i_visible_pitch = p_pic->p->i_pixel_pitch
1371                                          * p_pic->p_sys->p_image->width;
1372             break;
1373 #endif
1374
1375         default:
1376             /* Unknown chroma, tell the guy to get lost */
1377             IMAGE_FREE( p_pic->p_sys->p_image );
1378             free( p_pic->p_sys );
1379             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1380                      p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
1381             p_pic->i_planes = 0;
1382             return -1;
1383     }
1384
1385 #endif /* !MODULE_NAME_IS_glx */
1386
1387     return 0;
1388 }
1389
1390 /*****************************************************************************
1391  * FreePicture: destroy a picture allocated with NewPicture
1392  *****************************************************************************
1393  * Destroy XImage AND associated data. If using Shm, detach shared memory
1394  * segment from server and process, then free it. The XDestroyImage manpage
1395  * says that both the image structure _and_ the data pointed to by the
1396  * image structure are freed, so no need to free p_image->data.
1397  *****************************************************************************/
1398 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
1399 {
1400     /* The order of operations is correct */
1401 #ifdef HAVE_SYS_SHM_H
1402     if( p_vout->p_sys->b_shm )
1403     {
1404         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
1405         IMAGE_FREE( p_pic->p_sys->p_image );
1406
1407         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
1408         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
1409         {
1410             msg_Err( p_vout, "cannot detach shared memory (%s)",
1411                              strerror(errno) );
1412         }
1413     }
1414     else
1415 #endif
1416     {
1417         IMAGE_FREE( p_pic->p_sys->p_image );
1418     }
1419
1420     /* Do NOT use XFlush here ! */
1421     XSync( p_vout->p_sys->p_display, False );
1422
1423     free( p_pic->p_sys );
1424 }
1425
1426 /*****************************************************************************
1427  * ToggleFullScreen: Enable or disable full screen mode
1428  *****************************************************************************
1429  * This function will switch between fullscreen and window mode.
1430  *****************************************************************************/
1431 static void ToggleFullScreen ( vout_thread_t *p_vout )
1432 {
1433     Atom prop;
1434     XEvent xevent;
1435     mwmhints_t mwmhints;
1436     XSetWindowAttributes attributes;
1437
1438 #ifdef HAVE_XINERAMA
1439     int i_d1, i_d2;
1440 #endif
1441
1442     p_vout->b_fullscreen = !p_vout->b_fullscreen;
1443
1444     if( p_vout->b_fullscreen )
1445     {
1446         msg_Dbg( p_vout, "entering fullscreen mode" );
1447
1448         p_vout->p_sys->b_altfullscreen =
1449             config_GetInt( p_vout, MODULE_STRING "-altfullscreen" );
1450
1451         XUnmapWindow( p_vout->p_sys->p_display,
1452                       p_vout->p_sys->p_win->base_window );
1453
1454         p_vout->p_sys->p_win = &p_vout->p_sys->fullscreen_window;
1455
1456         CreateWindow( p_vout, p_vout->p_sys->p_win );
1457         XDestroyWindow( p_vout->p_sys->p_display,
1458                         p_vout->p_sys->fullscreen_window.video_window );
1459         XReparentWindow( p_vout->p_sys->p_display,
1460                          p_vout->p_sys->original_window.video_window,
1461                          p_vout->p_sys->fullscreen_window.base_window, 0, 0 );
1462         p_vout->p_sys->fullscreen_window.video_window =
1463             p_vout->p_sys->original_window.video_window;
1464
1465         /* To my knowledge there are two ways to create a borderless window.
1466          * There's the generic way which is to tell x to bypass the window
1467          * manager, but this creates problems with the focus of other
1468          * applications.
1469          * The other way is to use the motif property "_MOTIF_WM_HINTS" which
1470          * luckily seems to be supported by most window managers. */
1471         if( !p_vout->p_sys->b_altfullscreen )
1472         {
1473             mwmhints.flags = MWM_HINTS_DECORATIONS;
1474             mwmhints.decorations = False;
1475
1476             prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1477                                 False );
1478             XChangeProperty( p_vout->p_sys->p_display,
1479                              p_vout->p_sys->p_win->base_window,
1480                              prop, prop, 32, PropModeReplace,
1481                              (unsigned char *)&mwmhints,
1482                              PROP_MWM_HINTS_ELEMENTS );
1483         }
1484         else
1485         {
1486             /* brute force way to remove decorations */
1487             attributes.override_redirect = True;
1488             XChangeWindowAttributes( p_vout->p_sys->p_display,
1489                                      p_vout->p_sys->p_win->base_window,
1490                                      CWOverrideRedirect,
1491                                      &attributes);
1492
1493             /* Make sure the change is effective */
1494             XReparentWindow( p_vout->p_sys->p_display,
1495                              p_vout->p_sys->p_win->base_window,
1496                              DefaultRootWindow( p_vout->p_sys->p_display ),
1497                              0, 0 );
1498         }
1499
1500         if( p_vout->p_sys->b_net_wm_state_fullscreen )
1501         {
1502             XClientMessageEvent event;
1503
1504             memset( &event, 0, sizeof( XClientMessageEvent ) );
1505
1506             event.type = ClientMessage;
1507             event.message_type = p_vout->p_sys->net_wm_state;
1508             event.display = p_vout->p_sys->p_display;
1509             event.window = p_vout->p_sys->p_win->base_window;
1510             event.format = 32;
1511             event.data.l[ 0 ] = 1; /* set property */
1512             event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_fullscreen;
1513
1514             XSendEvent( p_vout->p_sys->p_display,
1515                         DefaultRootWindow( p_vout->p_sys->p_display ),
1516                         False, SubstructureRedirectMask,
1517                         (XEvent*)&event );
1518         }
1519
1520         /* Make sure the change is effective */
1521         XReparentWindow( p_vout->p_sys->p_display,
1522                          p_vout->p_sys->p_win->base_window,
1523                          DefaultRootWindow( p_vout->p_sys->p_display ),
1524                          0, 0 );
1525
1526 #ifdef HAVE_XINERAMA
1527         if( XineramaQueryExtension( p_vout->p_sys->p_display, &i_d1, &i_d2 ) &&
1528             XineramaIsActive( p_vout->p_sys->p_display ) )
1529         {
1530             XineramaScreenInfo *screens;   /* infos for xinerama */
1531             int i_num_screens;
1532
1533             msg_Dbg( p_vout, "using XFree Xinerama extension");
1534
1535 #define SCREEN p_vout->p_sys->p_win->i_screen
1536
1537             /* Get Information about Xinerama (num of screens) */
1538             screens = XineramaQueryScreens( p_vout->p_sys->p_display,
1539                                             &i_num_screens );
1540
1541             if( !SCREEN )
1542                 SCREEN = config_GetInt( p_vout,
1543                                         MODULE_STRING "-xineramascreen" );
1544
1545             /* just check that user has entered a good value */
1546             if( SCREEN >= i_num_screens || SCREEN < 0 )
1547             {
1548                 msg_Dbg( p_vout, "requested screen number invalid" );
1549                 SCREEN = 0;
1550             }
1551
1552             /* Get the X/Y upper left corner coordinate of the above screen */
1553             p_vout->p_sys->p_win->i_x = screens[SCREEN].x_org;
1554             p_vout->p_sys->p_win->i_y = screens[SCREEN].y_org;
1555
1556             /* Set the Height/width to the screen resolution */
1557             p_vout->p_sys->p_win->i_width = screens[SCREEN].width;
1558             p_vout->p_sys->p_win->i_height = screens[SCREEN].height;
1559
1560             XFree(screens);
1561
1562 #undef SCREEN
1563
1564         }
1565         else
1566 #endif
1567         {
1568             /* The window wasn't necessarily created at the requested size */
1569             p_vout->p_sys->p_win->i_x = p_vout->p_sys->p_win->i_y = 0;
1570             p_vout->p_sys->p_win->i_width =
1571                 DisplayWidth( p_vout->p_sys->p_display,
1572                               p_vout->p_sys->i_screen );
1573             p_vout->p_sys->p_win->i_height =
1574                 DisplayHeight( p_vout->p_sys->p_display,
1575                                p_vout->p_sys->i_screen );
1576         }
1577
1578         XMoveResizeWindow( p_vout->p_sys->p_display,
1579                            p_vout->p_sys->p_win->base_window,
1580                            p_vout->p_sys->p_win->i_x,
1581                            p_vout->p_sys->p_win->i_y,
1582                            p_vout->p_sys->p_win->i_width,
1583                            p_vout->p_sys->p_win->i_height );
1584     }
1585     else
1586     {
1587         msg_Dbg( p_vout, "leaving fullscreen mode" );
1588
1589         XReparentWindow( p_vout->p_sys->p_display,
1590                          p_vout->p_sys->original_window.video_window,
1591                          p_vout->p_sys->original_window.base_window, 0, 0 );
1592
1593         p_vout->p_sys->fullscreen_window.video_window = None;
1594         DestroyWindow( p_vout, &p_vout->p_sys->fullscreen_window );
1595         p_vout->p_sys->p_win = &p_vout->p_sys->original_window;
1596
1597         XMapWindow( p_vout->p_sys->p_display,
1598                     p_vout->p_sys->p_win->base_window );
1599     }
1600
1601     /* Unfortunately, using XSync() here is not enough to ensure the
1602      * window has already been mapped because the XMapWindow() request
1603      * has not necessarily been sent directly to our window (remember,
1604      * the call is first redirected to the window manager) */
1605     do
1606     {
1607         XWindowEvent( p_vout->p_sys->p_display,
1608                       p_vout->p_sys->p_win->base_window,
1609                       StructureNotifyMask, &xevent );
1610     } while( xevent.type != MapNotify );
1611
1612     /* Be careful, this can generate a BadMatch error if the window is not
1613      * already mapped by the server (see above) */
1614     XSetInputFocus(p_vout->p_sys->p_display,
1615                    p_vout->p_sys->p_win->base_window,
1616                    RevertToParent,
1617                    CurrentTime);
1618
1619     /* signal that the size needs to be updated */
1620     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1621 }
1622
1623 /*****************************************************************************
1624  * EnableXScreenSaver: enable screen saver
1625  *****************************************************************************
1626  * This function enables the screen saver on a display after it has been
1627  * disabled by XDisableScreenSaver.
1628  * FIXME: what happens if multiple vlc sessions are running at the same
1629  *        time ???
1630  *****************************************************************************/
1631 static void EnableXScreenSaver( vout_thread_t *p_vout )
1632 {
1633 #ifdef DPMSINFO_IN_DPMS_H
1634     int dummy;
1635 #endif
1636
1637     if( p_vout->p_sys->i_ss_timeout )
1638     {
1639         XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
1640                          p_vout->p_sys->i_ss_interval,
1641                          p_vout->p_sys->i_ss_blanking,
1642                          p_vout->p_sys->i_ss_exposure );
1643     }
1644
1645     /* Restore DPMS settings */
1646 #ifdef DPMSINFO_IN_DPMS_H
1647     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
1648     {
1649         if( p_vout->p_sys->b_ss_dpms )
1650         {
1651             DPMSEnable( p_vout->p_sys->p_display );
1652         }
1653     }
1654 #endif
1655 }
1656
1657 /*****************************************************************************
1658  * DisableXScreenSaver: disable screen saver
1659  *****************************************************************************
1660  * See XEnableXScreenSaver
1661  *****************************************************************************/
1662 static void DisableXScreenSaver( vout_thread_t *p_vout )
1663 {
1664 #ifdef DPMSINFO_IN_DPMS_H
1665     int dummy;
1666 #endif
1667
1668     /* Save screen saver information */
1669     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
1670                      &p_vout->p_sys->i_ss_interval,
1671                      &p_vout->p_sys->i_ss_blanking,
1672                      &p_vout->p_sys->i_ss_exposure );
1673
1674     /* Disable screen saver */
1675     if( p_vout->p_sys->i_ss_timeout )
1676     {
1677         XSetScreenSaver( p_vout->p_sys->p_display, 0,
1678                          p_vout->p_sys->i_ss_interval,
1679                          p_vout->p_sys->i_ss_blanking,
1680                          p_vout->p_sys->i_ss_exposure );
1681     }
1682
1683     /* Disable DPMS */
1684 #ifdef DPMSINFO_IN_DPMS_H
1685     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
1686     {
1687         CARD16 unused;
1688         /* Save DPMS current state */
1689         DPMSInfo( p_vout->p_sys->p_display, &unused,
1690                   &p_vout->p_sys->b_ss_dpms );
1691         DPMSDisable( p_vout->p_sys->p_display );
1692    }
1693 #endif
1694 }
1695
1696 /*****************************************************************************
1697  * CreateCursor: create a blank mouse pointer
1698  *****************************************************************************/
1699 static void CreateCursor( vout_thread_t *p_vout )
1700 {
1701     XColor cursor_color;
1702
1703     p_vout->p_sys->cursor_pixmap =
1704         XCreatePixmap( p_vout->p_sys->p_display,
1705                        DefaultRootWindow( p_vout->p_sys->p_display ),
1706                        1, 1, 1 );
1707
1708     XParseColor( p_vout->p_sys->p_display,
1709                  XCreateColormap( p_vout->p_sys->p_display,
1710                                   DefaultRootWindow(
1711                                                     p_vout->p_sys->p_display ),
1712                                   DefaultVisual(
1713                                                 p_vout->p_sys->p_display,
1714                                                 p_vout->p_sys->i_screen ),
1715                                   AllocNone ),
1716                  "black", &cursor_color );
1717
1718     p_vout->p_sys->blank_cursor =
1719         XCreatePixmapCursor( p_vout->p_sys->p_display,
1720                              p_vout->p_sys->cursor_pixmap,
1721                              p_vout->p_sys->cursor_pixmap,
1722                              &cursor_color, &cursor_color, 1, 1 );
1723 }
1724
1725 /*****************************************************************************
1726  * DestroyCursor: destroy the blank mouse pointer
1727  *****************************************************************************/
1728 static void DestroyCursor( vout_thread_t *p_vout )
1729 {
1730     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
1731 }
1732
1733 /*****************************************************************************
1734  * ToggleCursor: hide or show the mouse pointer
1735  *****************************************************************************
1736  * This function hides the X pointer if it is visible by setting the pointer
1737  * sprite to a blank one. To show it again, we disable the sprite.
1738  *****************************************************************************/
1739 static void ToggleCursor( vout_thread_t *p_vout )
1740 {
1741     if( p_vout->p_sys->b_mouse_pointer_visible )
1742     {
1743         XDefineCursor( p_vout->p_sys->p_display,
1744                        p_vout->p_sys->p_win->base_window,
1745                        p_vout->p_sys->blank_cursor );
1746         p_vout->p_sys->b_mouse_pointer_visible = 0;
1747     }
1748     else
1749     {
1750         XUndefineCursor( p_vout->p_sys->p_display,
1751                          p_vout->p_sys->p_win->base_window );
1752         p_vout->p_sys->b_mouse_pointer_visible = 1;
1753     }
1754 }
1755
1756 #ifdef MODULE_NAME_IS_xvideo
1757 /*****************************************************************************
1758  * XVideoGetPort: get YUV12 port
1759  *****************************************************************************/
1760 static int XVideoGetPort( vout_thread_t *p_vout,
1761                           vlc_fourcc_t i_chroma, vlc_fourcc_t *pi_newchroma )
1762 {
1763     XvAdaptorInfo *p_adaptor;
1764     unsigned int i;
1765     int i_adaptor, i_num_adaptors, i_requested_adaptor;
1766     int i_selected_port;
1767
1768     switch( XvQueryExtension( p_vout->p_sys->p_display, &i, &i, &i, &i, &i ) )
1769     {
1770         case Success:
1771             break;
1772
1773         case XvBadExtension:
1774             msg_Warn( p_vout, "XvBadExtension" );
1775             return -1;
1776
1777         case XvBadAlloc:
1778             msg_Warn( p_vout, "XvBadAlloc" );
1779             return -1;
1780
1781         default:
1782             msg_Warn( p_vout, "XvQueryExtension failed" );
1783             return -1;
1784     }
1785
1786     switch( XvQueryAdaptors( p_vout->p_sys->p_display,
1787                              DefaultRootWindow( p_vout->p_sys->p_display ),
1788                              &i_num_adaptors, &p_adaptor ) )
1789     {
1790         case Success:
1791             break;
1792
1793         case XvBadExtension:
1794             msg_Warn( p_vout, "XvBadExtension for XvQueryAdaptors" );
1795             return -1;
1796
1797         case XvBadAlloc:
1798             msg_Warn( p_vout, "XvBadAlloc for XvQueryAdaptors" );
1799             return -1;
1800
1801         default:
1802             msg_Warn( p_vout, "XvQueryAdaptors failed" );
1803             return -1;
1804     }
1805
1806     i_selected_port = -1;
1807     i_requested_adaptor = config_GetInt( p_vout, "xvideo-adaptor" );
1808
1809     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
1810     {
1811         XvImageFormatValues *p_formats;
1812         int i_format, i_num_formats;
1813         int i_port;
1814
1815         /* If we requested an adaptor and it's not this one, we aren't
1816          * interested */
1817         if( i_requested_adaptor != -1 && i_adaptor != i_requested_adaptor )
1818         {
1819             continue;
1820         }
1821
1822         /* If the adaptor doesn't have the required properties, skip it */
1823         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
1824             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
1825         {
1826             continue;
1827         }
1828
1829         /* Check that adaptor supports our requested format... */
1830         p_formats = XvListImageFormats( p_vout->p_sys->p_display,
1831                                         p_adaptor[i_adaptor].base_id,
1832                                         &i_num_formats );
1833
1834         for( i_format = 0;
1835              i_format < i_num_formats && ( i_selected_port == -1 );
1836              i_format++ )
1837         {
1838             XvAttribute     *p_attr;
1839             int             i_attr, i_num_attributes;
1840
1841             /* If this is not the format we want, or at least a
1842              * similar one, forget it */
1843             if( !vout_ChromaCmp( p_formats[ i_format ].id, i_chroma ) )
1844             {
1845                 continue;
1846             }
1847
1848             /* Look for the first available port supporting this format */
1849             for( i_port = p_adaptor[i_adaptor].base_id;
1850                  ( i_port < (int)(p_adaptor[i_adaptor].base_id
1851                                    + p_adaptor[i_adaptor].num_ports) )
1852                    && ( i_selected_port == -1 );
1853                  i_port++ )
1854             {
1855                 if( XvGrabPort( p_vout->p_sys->p_display, i_port, CurrentTime )
1856                      == Success )
1857                 {
1858                     i_selected_port = i_port;
1859                     *pi_newchroma = p_formats[ i_format ].id;
1860                 }
1861             }
1862
1863             /* If no free port was found, forget it */
1864             if( i_selected_port == -1 )
1865             {
1866                 continue;
1867             }
1868
1869             /* If we found a port, print information about it */
1870             msg_Dbg( p_vout, "adaptor %i, port %i, format 0x%x (%4.4s) %s",
1871                      i_adaptor, i_selected_port, p_formats[ i_format ].id,
1872                      (char *)&p_formats[ i_format ].id,
1873                      ( p_formats[ i_format ].format == XvPacked ) ?
1874                          "packed" : "planar" );
1875
1876             /* Make sure XV_AUTOPAINT_COLORKEY is set */
1877             p_attr = XvQueryPortAttributes( p_vout->p_sys->p_display,
1878                                             i_selected_port,
1879                                             &i_num_attributes );
1880
1881             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
1882             {
1883                 if( !strcmp( p_attr[i_attr].name, "XV_AUTOPAINT_COLORKEY" ) )
1884                 {
1885                     const Atom autopaint =
1886                         XInternAtom( p_vout->p_sys->p_display,
1887                                      "XV_AUTOPAINT_COLORKEY", False );
1888                     XvSetPortAttribute( p_vout->p_sys->p_display,
1889                                         i_selected_port, autopaint, 1 );
1890                     break;
1891                 }
1892             }
1893
1894             if( p_attr != NULL )
1895             {
1896                 XFree( p_attr );
1897             }
1898         }
1899
1900         if( p_formats != NULL )
1901         {
1902             XFree( p_formats );
1903         }
1904
1905     }
1906
1907     if( i_num_adaptors > 0 )
1908     {
1909         XvFreeAdaptorInfo( p_adaptor );
1910     }
1911
1912     if( i_selected_port == -1 )
1913     {
1914         int i_chroma_tmp = X112VLC_FOURCC( i_chroma );
1915         if( i_requested_adaptor == -1 )
1916         {
1917             msg_Warn( p_vout, "no free XVideo port found for format "
1918                       "0x%.8x (%4.4s)", i_chroma_tmp, (char*)&i_chroma_tmp );
1919         }
1920         else
1921         {
1922             msg_Warn( p_vout, "XVideo adaptor %i does not have a free "
1923                       "XVideo port for format 0x%.8x (%4.4s)",
1924                       i_requested_adaptor, i_chroma_tmp, (char*)&i_chroma_tmp );
1925         }
1926     }
1927
1928     return i_selected_port;
1929 }
1930
1931 /*****************************************************************************
1932  * XVideoReleasePort: release YUV12 port
1933  *****************************************************************************/
1934 static void XVideoReleasePort( vout_thread_t *p_vout, int i_port )
1935 {
1936     XvUngrabPort( p_vout->p_sys->p_display, i_port, CurrentTime );
1937 }
1938 #endif
1939
1940 /*****************************************************************************
1941  * InitDisplay: open and initialize X11 device
1942  *****************************************************************************
1943  * Create a window according to video output given size, and set other
1944  * properties according to the display properties.
1945  *****************************************************************************/
1946 static int InitDisplay( vout_thread_t *p_vout )
1947 {
1948 #ifdef MODULE_NAME_IS_x11
1949     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
1950     XVisualInfo *               p_xvisual;            /* visuals information */
1951     XVisualInfo                 xvisual_template;         /* visual template */
1952     int                         i_count;                       /* array size */
1953 #endif
1954
1955 #ifdef HAVE_SYS_SHM_H
1956     p_vout->p_sys->b_shm = 0;
1957
1958     if( config_GetInt( p_vout, MODULE_STRING "-shm" ) )
1959     {
1960 #   ifdef SYS_DARWIN
1961         /* FIXME: As of 2001-03-16, XFree4 for MacOS X does not support Xshm */
1962 #   else
1963         p_vout->p_sys->b_shm =
1964                   ( XShmQueryExtension( p_vout->p_sys->p_display ) == True );
1965 #   endif
1966
1967         if( !p_vout->p_sys->b_shm )
1968         {
1969             msg_Warn( p_vout, "XShm video extension is unavailable" );
1970         }
1971     }
1972     else
1973     {
1974         msg_Dbg( p_vout, "disabling XShm video extension" );
1975     }
1976
1977 #else
1978     msg_Warn( p_vout, "XShm video extension is unavailable" );
1979
1980 #endif
1981
1982 #ifdef MODULE_NAME_IS_xvideo
1983     /* XXX The brightness and contrast values should be read from environment
1984      * XXX variables... */
1985 #if 0
1986     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
1987     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
1988 #endif
1989 #endif
1990
1991 #ifdef MODULE_NAME_IS_x11
1992     /* Initialize structure */
1993     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
1994
1995     /* Get screen depth */
1996     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
1997                                                    p_vout->p_sys->i_screen );
1998     switch( p_vout->p_sys->i_screen_depth )
1999     {
2000     case 8:
2001         /*
2002          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
2003          */
2004         xvisual_template.screen =   p_vout->p_sys->i_screen;
2005         xvisual_template.class =    DirectColor;
2006         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2007                                     VisualScreenMask | VisualClassMask,
2008                                     &xvisual_template, &i_count );
2009         if( p_xvisual == NULL )
2010         {
2011             msg_Err( p_vout, "no PseudoColor visual available" );
2012             return VLC_EGENERIC;
2013         }
2014         p_vout->p_sys->i_bytes_per_pixel = 1;
2015         p_vout->output.pf_setpalette = SetPalette;
2016         break;
2017     case 15:
2018     case 16:
2019     case 24:
2020     default:
2021         /*
2022          * Screen depth is higher than 8bpp. TrueColor visual is used.
2023          */
2024         xvisual_template.screen =   p_vout->p_sys->i_screen;
2025         xvisual_template.class =    TrueColor;
2026         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2027                                     VisualScreenMask | VisualClassMask,
2028                                     &xvisual_template, &i_count );
2029         if( p_xvisual == NULL )
2030         {
2031             msg_Err( p_vout, "no TrueColor visual available" );
2032             return VLC_EGENERIC;
2033         }
2034
2035         p_vout->output.i_rmask = p_xvisual->red_mask;
2036         p_vout->output.i_gmask = p_xvisual->green_mask;
2037         p_vout->output.i_bmask = p_xvisual->blue_mask;
2038
2039         /* There is no difference yet between 3 and 4 Bpp. The only way
2040          * to find the actual number of bytes per pixel is to list supported
2041          * pixmap formats. */
2042         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
2043         p_vout->p_sys->i_bytes_per_pixel = 0;
2044
2045         for( ; i_count-- ; p_formats++ )
2046         {
2047             /* Under XFree4.0, the list contains pixmap formats available
2048              * through all video depths ; so we have to check against current
2049              * depth. */
2050             if( p_formats->depth == (int)p_vout->p_sys->i_screen_depth )
2051             {
2052                 if( p_formats->bits_per_pixel / 8
2053                         > (int)p_vout->p_sys->i_bytes_per_pixel )
2054                 {
2055                     p_vout->p_sys->i_bytes_per_pixel =
2056                                                p_formats->bits_per_pixel / 8;
2057                 }
2058             }
2059         }
2060         break;
2061     }
2062     p_vout->p_sys->p_visual = p_xvisual->visual;
2063     XFree( p_xvisual );
2064 #endif
2065
2066     return VLC_SUCCESS;
2067 }
2068
2069 #ifdef HAVE_SYS_SHM_H
2070 /*****************************************************************************
2071  * CreateShmImage: create an XImage or XvImage using shared memory extension
2072  *****************************************************************************
2073  * Prepare an XImage or XvImage for display function.
2074  * The order of the operations respects the recommandations of the mit-shm
2075  * document by J.Corbet and K.Packard. Most of the parameters were copied from
2076  * there. See http://ftp.xfree86.org/pub/XFree86/4.0/doc/mit-shm.TXT
2077  *****************************************************************************/
2078 static IMAGE_TYPE * CreateShmImage( vout_thread_t *p_vout,
2079                                     Display* p_display, EXTRA_ARGS_SHM,
2080                                     int i_width, int i_height )
2081 {
2082     IMAGE_TYPE *p_image;
2083     Status result;
2084
2085     /* Create XImage / XvImage */
2086 #ifdef MODULE_NAME_IS_xvideo
2087
2088     /* Make sure the buffer is aligned to multiple of 16 */
2089     i_height = ( i_height + 15 ) >> 4 << 4;
2090     i_width = ( i_width + 15 ) >> 4 << 4;
2091
2092     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2093                                 i_width, i_height, p_shm );
2094 #else
2095     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2096                                p_shm, i_width, i_height );
2097 #endif
2098     if( p_image == NULL )
2099     {
2100         msg_Err( p_vout, "image creation failed" );
2101         return NULL;
2102     }
2103
2104     /* Allocate shared memory segment - 0776 set the access permission
2105      * rights (like umask), they are not yet supported by all X servers */
2106     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE(p_image), IPC_CREAT | 0776 );
2107     if( p_shm->shmid < 0 )
2108     {
2109         msg_Err( p_vout, "cannot allocate shared image data (%s)",
2110                          strerror( errno ) );
2111         IMAGE_FREE( p_image );
2112         return NULL;
2113     }
2114
2115     /* Attach shared memory segment to process (read/write) */
2116     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
2117     if(! p_shm->shmaddr )
2118     {
2119         msg_Err( p_vout, "cannot attach shared memory (%s)",
2120                          strerror(errno));
2121         IMAGE_FREE( p_image );
2122         shmctl( p_shm->shmid, IPC_RMID, 0 );
2123         return NULL;
2124     }
2125
2126     /* Read-only data. We won't be using XShmGetImage */
2127     p_shm->readOnly = True;
2128
2129     /* Attach shared memory segment to X server */
2130     XSynchronize( p_display, True );
2131     b_shm = VLC_TRUE;
2132     result = XShmAttach( p_display, p_shm );
2133     if( result == False || !b_shm )
2134     {
2135         msg_Err( p_vout, "cannot attach shared memory to X server" );
2136         IMAGE_FREE( p_image );
2137         shmctl( p_shm->shmid, IPC_RMID, 0 );
2138         shmdt( p_shm->shmaddr );
2139         return NULL;
2140     }
2141     XSynchronize( p_display, False );
2142
2143     /* Send image to X server. This instruction is required, since having
2144      * built a Shm XImage and not using it causes an error on XCloseDisplay,
2145      * and remember NOT to use XFlush ! */
2146     XSync( p_display, False );
2147
2148 #if 0
2149     /* Mark the shm segment to be removed when there are no more
2150      * attachements, so it is automatic on process exit or after shmdt */
2151     shmctl( p_shm->shmid, IPC_RMID, 0 );
2152 #endif
2153
2154     return p_image;
2155 }
2156 #endif
2157
2158 /*****************************************************************************
2159  * CreateImage: create an XImage or XvImage
2160  *****************************************************************************
2161  * Create a simple image used as a buffer.
2162  *****************************************************************************/
2163 static IMAGE_TYPE * CreateImage( vout_thread_t *p_vout,
2164                                  Display *p_display, EXTRA_ARGS,
2165                                  int i_width, int i_height )
2166 {
2167     byte_t *    p_data;                           /* image data storage zone */
2168     IMAGE_TYPE *p_image;
2169 #ifdef MODULE_NAME_IS_x11
2170     int         i_quantum;                     /* XImage quantum (see below) */
2171     int         i_bytes_per_line;
2172 #endif
2173
2174     /* Allocate memory for image */
2175 #ifdef MODULE_NAME_IS_xvideo
2176
2177     /* Make sure the buffer is aligned to multiple of 16 */
2178     i_height = ( i_height + 15 ) >> 4 << 4;
2179     i_width = ( i_width + 15 ) >> 4 << 4;
2180
2181     p_data = (byte_t *) malloc( i_width * i_height * i_bits_per_pixel / 8 );
2182 #elif defined(MODULE_NAME_IS_x11)
2183     i_bytes_per_line = i_width * i_bytes_per_pixel;
2184     p_data = (byte_t *) malloc( i_bytes_per_line * i_height );
2185 #endif
2186     if( !p_data )
2187     {
2188         msg_Err( p_vout, "out of memory" );
2189         return NULL;
2190     }
2191
2192 #ifdef MODULE_NAME_IS_x11
2193     /* Optimize the quantum of a scanline regarding its size - the quantum is
2194        a diviser of the number of bits between the start of two scanlines. */
2195     if( i_bytes_per_line & 0xf )
2196     {
2197         i_quantum = 0x8;
2198     }
2199     else if( i_bytes_per_line & 0x10 )
2200     {
2201         i_quantum = 0x10;
2202     }
2203     else
2204     {
2205         i_quantum = 0x20;
2206     }
2207 #endif
2208
2209     /* Create XImage. p_data will be automatically freed */
2210 #ifdef MODULE_NAME_IS_xvideo
2211     p_image = XvCreateImage( p_display, i_xvport, i_chroma,
2212                              p_data, i_width, i_height );
2213 #elif defined(MODULE_NAME_IS_x11)
2214     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2215                             p_data, i_width, i_height, i_quantum, 0 );
2216 #endif
2217     if( p_image == NULL )
2218     {
2219         msg_Err( p_vout, "XCreateImage() failed" );
2220         free( p_data );
2221         return NULL;
2222     }
2223
2224     return p_image;
2225 }
2226
2227 /*****************************************************************************
2228  * X11ErrorHandler: replace error handler so we can intercept some of them
2229  *****************************************************************************/
2230 static int X11ErrorHandler( Display * display, XErrorEvent * event )
2231 {
2232     /* Ingnore errors on XSetInputFocus()
2233      * (they happen when a window is not yet mapped) */
2234     if( event->request_code == X_SetInputFocus )
2235     {
2236         fprintf(stderr, "XSetInputFocus failed\n");
2237         return 0;
2238     }
2239
2240     if( event->request_code == 150 /* MIT-SHM */ &&
2241         event->minor_code == X_ShmAttach )
2242     {
2243         fprintf(stderr, "XShmAttach failed\n");
2244         b_shm = VLC_FALSE;
2245         return 0;
2246     }
2247
2248     XSetErrorHandler(NULL);
2249     return (XSetErrorHandler(X11ErrorHandler))( display, event );
2250 }
2251
2252 #ifdef MODULE_NAME_IS_x11
2253 /*****************************************************************************
2254  * SetPalette: sets an 8 bpp palette
2255  *****************************************************************************
2256  * This function sets the palette given as an argument. It does not return
2257  * anything, but could later send information on which colors it was unable
2258  * to set.
2259  *****************************************************************************/
2260 static void SetPalette( vout_thread_t *p_vout,
2261                         uint16_t *red, uint16_t *green, uint16_t *blue )
2262 {
2263     int i;
2264     XColor p_colors[255];
2265
2266     /* allocate palette */
2267     for( i = 0; i < 255; i++ )
2268     {
2269         /* kludge: colors are indexed reversely because color 255 seems
2270          * to be reserved for black even if we try to set it to white */
2271         p_colors[ i ].pixel = 255 - i;
2272         p_colors[ i ].pad   = 0;
2273         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
2274         p_colors[ i ].red   = red[ 255 - i ];
2275         p_colors[ i ].blue  = blue[ 255 - i ];
2276         p_colors[ i ].green = green[ 255 - i ];
2277     }
2278
2279     XStoreColors( p_vout->p_sys->p_display,
2280                   p_vout->p_sys->colormap, p_colors, 255 );
2281 }
2282 #endif
2283
2284 /*****************************************************************************
2285  * Control: control facility for the vout
2286  *****************************************************************************/
2287 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
2288 {
2289     double f_arg;
2290     vlc_bool_t b_arg;
2291
2292     switch( i_query )
2293     {
2294         case VOUT_SET_ZOOM:
2295             if( p_vout->p_sys->p_win->owner_window )
2296                 return vout_ControlWindow( p_vout,
2297                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2298
2299             f_arg = va_arg( args, double );
2300
2301             vlc_mutex_lock( &p_vout->p_sys->lock );
2302
2303             /* Update dimensions */
2304             /* FIXME: export InitWindowSize() from vout core */
2305             XResizeWindow( p_vout->p_sys->p_display,
2306                            p_vout->p_sys->p_win->base_window,
2307                            p_vout->i_window_width * f_arg,
2308                            p_vout->i_window_height * f_arg );
2309
2310             vlc_mutex_unlock( &p_vout->p_sys->lock );
2311             return VLC_SUCCESS;
2312
2313        case VOUT_CLOSE:
2314             vlc_mutex_lock( &p_vout->p_sys->lock );
2315             XUnmapWindow( p_vout->p_sys->p_display,
2316                           p_vout->p_sys->original_window.base_window );
2317             vlc_mutex_unlock( &p_vout->p_sys->lock );
2318             /* Fall through */
2319
2320        case VOUT_REPARENT:
2321             vlc_mutex_lock( &p_vout->p_sys->lock );
2322             XReparentWindow( p_vout->p_sys->p_display,
2323                              p_vout->p_sys->original_window.base_window,
2324                              DefaultRootWindow( p_vout->p_sys->p_display ),
2325                              0, 0 );
2326             XSync( p_vout->p_sys->p_display, False );
2327             p_vout->p_sys->original_window.owner_window = 0;
2328             vlc_mutex_unlock( &p_vout->p_sys->lock );
2329             return vout_vaControlDefault( p_vout, i_query, args );
2330
2331         case VOUT_SET_STAY_ON_TOP:
2332             if( p_vout->p_sys->p_win->owner_window )
2333                 return vout_ControlWindow( p_vout,
2334                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2335
2336             b_arg = va_arg( args, vlc_bool_t );
2337             vlc_mutex_lock( &p_vout->p_sys->lock );
2338             WindowOnTop( p_vout, b_arg );
2339             vlc_mutex_unlock( &p_vout->p_sys->lock );
2340             return VLC_SUCCESS;
2341
2342        default:
2343             return vout_vaControlDefault( p_vout, i_query, args );
2344     }
2345 }
2346
2347 /*****************************************************************************
2348  * TestNetWMSupport: tests for Extended Window Manager Hints support
2349  *****************************************************************************/
2350 static void TestNetWMSupport( vout_thread_t *p_vout )
2351 {
2352     int i_ret, i_format;
2353     unsigned long i, i_items, i_bytesafter;
2354     Atom net_wm_supported;
2355     union { Atom *p_atom; unsigned char *p_char; } p_args;
2356
2357     p_args.p_atom = NULL;
2358
2359     p_vout->p_sys->b_net_wm_state_fullscreen = VLC_FALSE;
2360     p_vout->p_sys->b_net_wm_state_above = VLC_FALSE;
2361     p_vout->p_sys->b_net_wm_state_below = VLC_FALSE;
2362     p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_FALSE;
2363
2364     net_wm_supported =
2365         XInternAtom( p_vout->p_sys->p_display, "_NET_SUPPORTED", False );
2366
2367     i_ret = XGetWindowProperty( p_vout->p_sys->p_display,
2368                                 DefaultRootWindow( p_vout->p_sys->p_display ),
2369                                 net_wm_supported,
2370                                 0, 16384, False, AnyPropertyType,
2371                                 &net_wm_supported,
2372                                 &i_format, &i_items, &i_bytesafter,
2373                                 (unsigned char **)&p_args );
2374
2375     if( i_ret != Success || i_items == 0 ) return;
2376
2377     msg_Dbg( p_vout, "Window manager supports NetWM" );
2378
2379     p_vout->p_sys->net_wm_state =
2380         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE", False );
2381     p_vout->p_sys->net_wm_state_fullscreen =
2382         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_FULLSCREEN",
2383                      False );
2384     p_vout->p_sys->net_wm_state_above =
2385         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_ABOVE", False );
2386     p_vout->p_sys->net_wm_state_below =
2387         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_BELOW", False );
2388     p_vout->p_sys->net_wm_state_stays_on_top =
2389         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_STAYS_ON_TOP",
2390                      False );
2391
2392     for( i = 0; i < i_items; i++ )
2393     {
2394         if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_fullscreen )
2395         {
2396             msg_Dbg( p_vout,
2397                      "Window manager supports _NET_WM_STATE_FULLSCREEN" );
2398             p_vout->p_sys->b_net_wm_state_fullscreen = VLC_TRUE;
2399         }
2400         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_above )
2401         {
2402             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_ABOVE" );
2403             p_vout->p_sys->b_net_wm_state_above = VLC_TRUE;
2404         }
2405         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_below )
2406         {
2407             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_BELOW" );
2408             p_vout->p_sys->b_net_wm_state_below = VLC_TRUE;
2409         }
2410         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_stays_on_top )
2411         {
2412             msg_Dbg( p_vout,
2413                      "Window manager supports _NET_WM_STATE_STAYS_ON_TOP" );
2414             p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_TRUE;
2415         }
2416     }
2417
2418     XFree( p_args.p_atom );
2419 }
2420
2421 /*****************************************************************************
2422  * Key events handling
2423  *****************************************************************************/
2424 static struct
2425 {
2426     int i_x11key;
2427     int i_vlckey;
2428
2429 } x11keys_to_vlckeys[] =
2430 {
2431     { XK_F1, KEY_F1 }, { XK_F2, KEY_F2 }, { XK_F3, KEY_F3 }, { XK_F4, KEY_F4 },
2432     { XK_F5, KEY_F5 }, { XK_F6, KEY_F6 }, { XK_F7, KEY_F7 }, { XK_F8, KEY_F8 },
2433     { XK_F9, KEY_F9 }, { XK_F10, KEY_F10 }, { XK_F11, KEY_F11 },
2434     { XK_F12, KEY_F12 },
2435
2436     { XK_Return, KEY_ENTER },
2437     { XK_KP_Enter, KEY_ENTER },
2438     { XK_space, KEY_SPACE },
2439     { XK_Escape, KEY_ESC },
2440
2441     { XK_Menu, KEY_MENU },
2442     { XK_Left, KEY_LEFT },
2443     { XK_Right, KEY_RIGHT },
2444     { XK_Up, KEY_UP },
2445     { XK_Down, KEY_DOWN },
2446
2447     { XK_Home, KEY_HOME },
2448     { XK_End, KEY_END },
2449     { XK_Page_Up, KEY_PAGEUP },
2450     { XK_Page_Down, KEY_PAGEDOWN },
2451
2452     { XK_Insert, KEY_INSERT },
2453     { XK_Delete, KEY_DELETE },
2454
2455     { 0, 0 }
2456 };
2457
2458 static int ConvertKey( int i_key )
2459 {
2460     int i;
2461
2462     for( i = 0; x11keys_to_vlckeys[i].i_x11key != 0; i++ )
2463     {
2464         if( x11keys_to_vlckeys[i].i_x11key == i_key )
2465         {
2466             return x11keys_to_vlckeys[i].i_vlckey;
2467         }
2468     }
2469
2470     return 0;
2471 }
2472
2473 /*****************************************************************************
2474  * WindowOnTop: Switches the "always on top" state of the video window.
2475  *****************************************************************************/
2476 static int WindowOnTop( vout_thread_t *p_vout, vlc_bool_t b_on_top )
2477 {
2478     if( p_vout->p_sys->b_net_wm_state_stays_on_top )
2479     {
2480         XClientMessageEvent event;
2481
2482         memset( &event, 0, sizeof( XClientMessageEvent ) );
2483
2484         event.type = ClientMessage;
2485         event.message_type = p_vout->p_sys->net_wm_state;
2486         event.display = p_vout->p_sys->p_display;
2487         event.window = p_vout->p_sys->p_win->base_window;
2488         event.format = 32;
2489         event.data.l[ 0 ] = b_on_top; /* set property */
2490         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_stays_on_top;
2491
2492         XSendEvent( p_vout->p_sys->p_display,
2493                     DefaultRootWindow( p_vout->p_sys->p_display ),
2494                     False, SubstructureRedirectMask,
2495                     (XEvent*)&event );
2496     }
2497
2498     return VLC_SUCCESS;
2499 }