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