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