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