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