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