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