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