]> git.sesse.net Git - vlc/blob - modules/video_output/x11/xcommon.c
* modules/gui/wxwindows/*: implemented VOUT_SET_STAY_ON_TOP in ControlWindow()
[vlc] / modules / video_output / x11 / xcommon.c
1 /*****************************************************************************
2  * xcommon.c: Functions common to the X11 and XVideo plugins
3  *****************************************************************************
4  * Copyright (C) 1998-2001 VideoLAN
5  * $Id$
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Sam Hocevar <sam@zoy.org>
9  *          David Kennedy <dkennedy@tinytoad.com>
10  *          Gildas Bazin <gbazin@netcourrier.com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <errno.h>                                                 /* ENOMEM */
31 #include <stdlib.h>                                                /* free() */
32 #include <string.h>                                            /* strerror() */
33
34 #include <vlc/vlc.h>
35 #include <vlc/intf.h>
36 #include <vlc/vout.h>
37 #include <vlc_keys.h>
38
39 #ifdef HAVE_MACHINE_PARAM_H
40     /* BSD */
41 #   include <machine/param.h>
42 #   include <sys/types.h>                                  /* typedef ushort */
43 #   include <sys/ipc.h>
44 #endif
45
46 #ifndef WIN32
47 #   include <netinet/in.h>                            /* BSD: struct in_addr */
48 #endif
49
50 #ifdef HAVE_SYS_SHM_H
51 #   include <sys/shm.h>                                /* shmget(), shmctl() */
52 #endif
53
54 #include <X11/Xlib.h>
55 #include <X11/Xmd.h>
56 #include <X11/Xutil.h>
57 #include <X11/keysym.h>
58 #ifdef HAVE_SYS_SHM_H
59 #   include <X11/extensions/XShm.h>
60 #endif
61 #ifdef DPMSINFO_IN_DPMS_H
62 #   include <X11/extensions/dpms.h>
63 #endif
64
65 #ifdef MODULE_NAME_IS_xvideo
66 #   include <X11/extensions/Xv.h>
67 #   include <X11/extensions/Xvlib.h>
68 #endif
69
70 #ifdef 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     /* Prepare window attributes */
905     xwindow_attributes.backing_store = Always;       /* save the hidden part */
906     xwindow_attributes.background_pixel = BlackPixel(p_vout->p_sys->p_display,
907                                                      p_vout->p_sys->i_screen);
908     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
909
910     if( !p_vout->b_fullscreen )
911     {
912         p_win->owner_window =
913             (Window)vout_RequestWindow( p_vout, &p_win->i_x, &p_win->i_y,
914                                         &p_win->i_width, &p_win->i_height );
915
916         xsize_hints.base_width  = xsize_hints.width = p_win->i_width;
917         xsize_hints.base_height = xsize_hints.height = p_win->i_height;
918         xsize_hints.flags       = PSize;
919
920         if( p_win->i_x >=0 || p_win->i_y >= 0 )
921         {
922             xsize_hints.x = p_win->i_x;
923             xsize_hints.y = p_win->i_y;
924             xsize_hints.flags |= PPosition;
925         }
926     }
927     else
928     {
929         /* Fullscreen window size and position */
930         p_win->owner_window = 0;
931         p_win->i_x = p_win->i_y = 0;
932         p_win->i_width =
933             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
934         p_win->i_height =
935             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
936     }
937
938     if( !p_win->owner_window )
939     {
940         /* Create the window and set hints - the window must receive
941          * ConfigureNotify events, and until it is displayed, Expose and
942          * MapNotify events. */
943
944         p_win->base_window =
945             XCreateWindow( p_vout->p_sys->p_display,
946                            DefaultRootWindow( p_vout->p_sys->p_display ),
947                            p_win->i_x, p_win->i_y,
948                            p_win->i_width, p_win->i_height,
949                            0,
950                            0, InputOutput, 0,
951                            CWBackingStore | CWBackPixel | CWEventMask,
952                            &xwindow_attributes );
953
954         if( !p_vout->b_fullscreen )
955         {
956             /* Set window manager hints and properties: size hints, command,
957              * window's name, and accepted protocols */
958             XSetWMNormalHints( p_vout->p_sys->p_display,
959                                p_win->base_window, &xsize_hints );
960             XSetCommand( p_vout->p_sys->p_display, p_win->base_window,
961                          p_vout->p_vlc->ppsz_argv, p_vout->p_vlc->i_argc );
962
963             XStoreName( p_vout->p_sys->p_display, p_win->base_window,
964 #ifdef MODULE_NAME_IS_x11
965                         VOUT_TITLE " (X11 output)"
966 #else
967                         VOUT_TITLE " (XVideo output)"
968 #endif
969                       );
970         }
971     }
972     else
973     {
974         Window dummy1;
975         unsigned int dummy2, dummy3;
976
977         /* Select events we are interested in. */
978         XSelectInput( p_vout->p_sys->p_display, p_win->owner_window,
979                       StructureNotifyMask );
980
981         /* Get the parent window's geometry information */
982         XGetGeometry( p_vout->p_sys->p_display, p_win->owner_window,
983                       &dummy1, &dummy2, &dummy3,
984                       &p_win->i_width,
985                       &p_win->i_height,
986                       &dummy2, &dummy3 );
987
988         /* We are already configured */
989         b_configure_notify = VLC_TRUE;
990
991         /* From man XSelectInput: only one client at a time can select a
992          * ButtonPress event, so we need to open a new window anyway. */
993         p_win->base_window =
994             XCreateWindow( p_vout->p_sys->p_display,
995                            p_win->owner_window,
996                            0, 0,
997                            p_win->i_width, p_win->i_height,
998                            0,
999                            0, CopyFromParent, 0,
1000                            CWBackingStore | CWBackPixel | CWEventMask,
1001                            &xwindow_attributes );
1002     }
1003
1004     if( (p_win->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1005         || (p_win->wm_delete_window == None)
1006         || !XSetWMProtocols( p_vout->p_sys->p_display, p_win->base_window,
1007                              &p_win->wm_delete_window, 1 ) )
1008     {
1009         /* WM_DELETE_WINDOW is not supported by window manager */
1010         msg_Warn( p_vout, "missing or bad window manager" );
1011     }
1012
1013     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1014      * event when using functions like XCopyArea */
1015     xgcvalues.graphics_exposures = False;
1016     p_win->gc = XCreateGC( p_vout->p_sys->p_display,
1017                            p_win->base_window,
1018                            GCGraphicsExposures, &xgcvalues );
1019
1020     /* Send orders to server, and wait until window is displayed - three
1021      * events must be received: a MapNotify event, an Expose event allowing
1022      * drawing in the window, and a ConfigureNotify to get the window
1023      * dimensions. Once those events have been received, only
1024      * ConfigureNotify events need to be received. */
1025     XMapWindow( p_vout->p_sys->p_display, p_win->base_window );
1026     do
1027     {
1028         XNextEvent( p_vout->p_sys->p_display, &xevent);
1029         if( (xevent.type == Expose)
1030             && (xevent.xexpose.window == p_win->base_window) )
1031         {
1032             b_expose = VLC_TRUE;
1033         }
1034         else if( (xevent.type == MapNotify)
1035                  && (xevent.xmap.window == p_win->base_window) )
1036         {
1037             b_map_notify = VLC_TRUE;
1038         }
1039         else if( (xevent.type == ConfigureNotify)
1040                  && (xevent.xconfigure.window == p_win->base_window) )
1041         {
1042             b_configure_notify = VLC_TRUE;
1043             p_win->i_width = xevent.xconfigure.width;
1044             p_win->i_height = xevent.xconfigure.height;
1045         }
1046     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1047
1048     XSelectInput( p_vout->p_sys->p_display, p_win->base_window,
1049                   StructureNotifyMask | KeyPressMask |
1050                   ButtonPressMask | ButtonReleaseMask |
1051                   PointerMotionMask );
1052
1053 #ifdef MODULE_NAME_IS_x11
1054     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1055     {
1056         /* Allocate a new palette */
1057         p_vout->p_sys->colormap =
1058             XCreateColormap( p_vout->p_sys->p_display,
1059                              DefaultRootWindow( p_vout->p_sys->p_display ),
1060                              DefaultVisual( p_vout->p_sys->p_display,
1061                                             p_vout->p_sys->i_screen ),
1062                              AllocAll );
1063
1064         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1065         XChangeWindowAttributes( p_vout->p_sys->p_display, p_win->base_window,
1066                                  CWColormap, &xwindow_attributes );
1067     }
1068 #endif
1069
1070     /* Create video output sub-window. */
1071     p_win->video_window =  XCreateSimpleWindow(
1072                                       p_vout->p_sys->p_display,
1073                                       p_win->base_window, 0, 0,
1074                                       p_win->i_width, p_win->i_height,
1075                                       0,
1076                                       BlackPixel( p_vout->p_sys->p_display,
1077                                                   p_vout->p_sys->i_screen ),
1078                                       WhitePixel( p_vout->p_sys->p_display,
1079                                                   p_vout->p_sys->i_screen ) );
1080
1081     XSetWindowBackground( p_vout->p_sys->p_display, p_win->video_window,
1082                           BlackPixel( p_vout->p_sys->p_display,
1083                                       p_vout->p_sys->i_screen ) );
1084
1085     XMapWindow( p_vout->p_sys->p_display, p_win->video_window );
1086     XSelectInput( p_vout->p_sys->p_display, p_win->video_window,
1087                   ExposureMask );
1088
1089     /* make sure the video window will be centered in the next ManageVideo() */
1090     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1091
1092     /* If the cursor was formerly blank than blank it again */
1093     if( !p_vout->p_sys->b_mouse_pointer_visible )
1094     {
1095         ToggleCursor( p_vout );
1096         ToggleCursor( p_vout );
1097     }
1098
1099     /* Do NOT use XFlush here ! */
1100     XSync( p_vout->p_sys->p_display, False );
1101
1102     /* At this stage, the window is open, displayed, and ready to
1103      * receive data */
1104     p_vout->p_sys->p_win = p_win;
1105
1106     return VLC_SUCCESS;
1107 }
1108
1109 /*****************************************************************************
1110  * DestroyWindow: destroy the window
1111  *****************************************************************************
1112  *
1113  *****************************************************************************/
1114 static void DestroyWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1115 {
1116     /* Do NOT use XFlush here ! */
1117     XSync( p_vout->p_sys->p_display, False );
1118
1119     XDestroyWindow( p_vout->p_sys->p_display, p_win->video_window );
1120     XFreeGC( p_vout->p_sys->p_display, p_win->gc );
1121
1122     XUnmapWindow( p_vout->p_sys->p_display, p_win->base_window );
1123     XDestroyWindow( p_vout->p_sys->p_display, p_win->base_window );
1124
1125     if( p_win->owner_window )
1126         vout_ReleaseWindow( p_vout, (void *)p_win->owner_window );
1127 }
1128
1129 /*****************************************************************************
1130  * NewPicture: allocate a picture
1131  *****************************************************************************
1132  * Returns 0 on success, -1 otherwise
1133  *****************************************************************************/
1134 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1135 {
1136 #ifdef MODULE_NAME_IS_xvideo
1137     int i_plane;
1138 #endif
1139
1140     /* We know the chroma, allocate a buffer which will be used
1141      * directly by the decoder */
1142     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1143
1144     if( p_pic->p_sys == NULL )
1145     {
1146         return -1;
1147     }
1148
1149     /* Fill in picture_t fields */
1150     vout_InitPicture( VLC_OBJECT(p_vout), p_pic, p_vout->output.i_chroma,
1151                       p_vout->output.i_width, p_vout->output.i_height,
1152                       p_vout->output.i_aspect );
1153
1154 #ifdef HAVE_SYS_SHM_H
1155     if( p_vout->p_sys->b_shm )
1156     {
1157         /* Create image using XShm extension */
1158         p_pic->p_sys->p_image =
1159             CreateShmImage( p_vout, p_vout->p_sys->p_display,
1160 #   ifdef MODULE_NAME_IS_xvideo
1161                             p_vout->p_sys->i_xvport, p_vout->output.i_chroma,
1162 #   else
1163                             p_vout->p_sys->p_visual,
1164                             p_vout->p_sys->i_screen_depth,
1165 #   endif
1166                             &p_pic->p_sys->shminfo,
1167                             p_vout->output.i_width, p_vout->output.i_height );
1168     }
1169     else
1170 #endif /* HAVE_SYS_SHM_H */
1171     {
1172         /* Create image without XShm extension */
1173         p_pic->p_sys->p_image =
1174             CreateImage( p_vout, p_vout->p_sys->p_display,
1175 #ifdef MODULE_NAME_IS_xvideo
1176                          p_vout->p_sys->i_xvport, p_vout->output.i_chroma,
1177                          p_pic->format.i_bits_per_pixel,
1178 #else
1179                          p_vout->p_sys->p_visual,
1180                          p_vout->p_sys->i_screen_depth,
1181                          p_vout->p_sys->i_bytes_per_pixel,
1182 #endif
1183                          p_vout->output.i_width, p_vout->output.i_height );
1184     }
1185
1186     if( p_pic->p_sys->p_image == NULL )
1187     {
1188         free( p_pic->p_sys );
1189         return -1;
1190     }
1191
1192     switch( p_vout->output.i_chroma )
1193     {
1194 #ifdef MODULE_NAME_IS_xvideo
1195         case VLC_FOURCC('I','4','2','0'):
1196         case VLC_FOURCC('Y','V','1','2'):
1197         case VLC_FOURCC('Y','2','1','1'):
1198         case VLC_FOURCC('Y','U','Y','2'):
1199         case VLC_FOURCC('U','Y','V','Y'):
1200         case VLC_FOURCC('R','V','1','5'):
1201         case VLC_FOURCC('R','V','1','6'):
1202         case VLC_FOURCC('R','V','2','4'): /* Fixme: pixel pitch == 4 ? */
1203         case VLC_FOURCC('R','V','3','2'):
1204
1205             for( i_plane = 0; i_plane < p_pic->p_sys->p_image->num_planes;
1206                  i_plane++ )
1207             {
1208                 p_pic->p[i_plane].p_pixels = p_pic->p_sys->p_image->data
1209                     + p_pic->p_sys->p_image->offsets[i_plane];
1210                 p_pic->p[i_plane].i_pitch =
1211                     p_pic->p_sys->p_image->pitches[i_plane];
1212             }
1213             if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
1214             {
1215                 /* U and V inverted compared to I420
1216                  * Fixme: this should be handled by the vout core */
1217                 p_pic->U_PIXELS = p_pic->p_sys->p_image->data
1218                     + p_pic->p_sys->p_image->offsets[2];
1219                 p_pic->V_PIXELS = p_pic->p_sys->p_image->data
1220                     + p_pic->p_sys->p_image->offsets[1];
1221             }
1222             break;
1223
1224 #else
1225         case VLC_FOURCC('R','G','B','2'):
1226         case VLC_FOURCC('R','V','1','6'):
1227         case VLC_FOURCC('R','V','1','5'):
1228         case VLC_FOURCC('R','V','2','4'):
1229         case VLC_FOURCC('R','V','3','2'):
1230
1231             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
1232             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1233                                   + p_pic->p_sys->p_image->xoffset;
1234             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
1235
1236             /* p_pic->p->i_pixel_pitch = 4 for RV24 but this should be set
1237              * properly by vout_InitPicture() */
1238             p_pic->p->i_visible_pitch = p_pic->p->i_pixel_pitch
1239                                          * p_pic->p_sys->p_image->width;
1240             break;
1241 #endif
1242
1243         default:
1244             /* Unknown chroma, tell the guy to get lost */
1245             IMAGE_FREE( p_pic->p_sys->p_image );
1246             free( p_pic->p_sys );
1247             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1248                      p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
1249             p_pic->i_planes = 0;
1250             return -1;
1251     }
1252
1253     return 0;
1254 }
1255
1256 /*****************************************************************************
1257  * FreePicture: destroy a picture allocated with NewPicture
1258  *****************************************************************************
1259  * Destroy XImage AND associated data. If using Shm, detach shared memory
1260  * segment from server and process, then free it. The XDestroyImage manpage
1261  * says that both the image structure _and_ the data pointed to by the
1262  * image structure are freed, so no need to free p_image->data.
1263  *****************************************************************************/
1264 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
1265 {
1266     /* The order of operations is correct */
1267 #ifdef HAVE_SYS_SHM_H
1268     if( p_vout->p_sys->b_shm )
1269     {
1270         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
1271         IMAGE_FREE( p_pic->p_sys->p_image );
1272
1273         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
1274         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
1275         {
1276             msg_Err( p_vout, "cannot detach shared memory (%s)",
1277                              strerror(errno) );
1278         }
1279     }
1280     else
1281 #endif
1282     {
1283         IMAGE_FREE( p_pic->p_sys->p_image );
1284     }
1285
1286     /* Do NOT use XFlush here ! */
1287     XSync( p_vout->p_sys->p_display, False );
1288
1289     free( p_pic->p_sys );
1290 }
1291
1292 /*****************************************************************************
1293  * ToggleFullScreen: Enable or disable full screen mode
1294  *****************************************************************************
1295  * This function will switch between fullscreen and window mode.
1296  *****************************************************************************/
1297 static void ToggleFullScreen ( vout_thread_t *p_vout )
1298 {
1299     Atom prop;
1300     XEvent xevent;
1301     mwmhints_t mwmhints;
1302     XSetWindowAttributes attributes;
1303
1304 #ifdef HAVE_XINERAMA
1305     int i_d1, i_d2;
1306 #endif
1307
1308     p_vout->b_fullscreen = !p_vout->b_fullscreen;
1309
1310     if( p_vout->b_fullscreen )
1311     {
1312         msg_Dbg( p_vout, "entering fullscreen mode" );
1313
1314         p_vout->p_sys->b_altfullscreen =
1315             config_GetInt( p_vout, MODULE_STRING "-altfullscreen" );
1316
1317         XUnmapWindow( p_vout->p_sys->p_display,
1318                       p_vout->p_sys->p_win->base_window);
1319
1320         p_vout->p_sys->p_win = &p_vout->p_sys->fullscreen_window;
1321
1322         CreateWindow( p_vout, p_vout->p_sys->p_win );
1323
1324         /* To my knowledge there are two ways to create a borderless window.
1325          * There's the generic way which is to tell x to bypass the window
1326          * manager, but this creates problems with the focus of other
1327          * applications.
1328          * The other way is to use the motif property "_MOTIF_WM_HINTS" which
1329          * luckily seems to be supported by most window managers. */
1330         if( !p_vout->p_sys->b_altfullscreen )
1331         {
1332             mwmhints.flags = MWM_HINTS_DECORATIONS;
1333             mwmhints.decorations = False;
1334
1335             prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1336                                 False );
1337             XChangeProperty( p_vout->p_sys->p_display,
1338                              p_vout->p_sys->p_win->base_window,
1339                              prop, prop, 32, PropModeReplace,
1340                              (unsigned char *)&mwmhints,
1341                              PROP_MWM_HINTS_ELEMENTS );
1342         }
1343         else
1344         {
1345             /* brute force way to remove decorations */
1346             attributes.override_redirect = True;
1347             XChangeWindowAttributes( p_vout->p_sys->p_display,
1348                                      p_vout->p_sys->p_win->base_window,
1349                                      CWOverrideRedirect,
1350                                      &attributes);
1351
1352             /* Make sure the change is effective */
1353             XReparentWindow( p_vout->p_sys->p_display,
1354                              p_vout->p_sys->p_win->base_window,
1355                              DefaultRootWindow( p_vout->p_sys->p_display ),
1356                              0, 0 );
1357         }
1358
1359         if( p_vout->p_sys->b_net_wm_state_fullscreen )
1360         {
1361             XClientMessageEvent event;
1362
1363             memset( &event, 0, sizeof( XClientMessageEvent ) );
1364
1365             event.type = ClientMessage;
1366             event.message_type = p_vout->p_sys->net_wm_state;
1367             event.display = p_vout->p_sys->p_display;
1368             event.window = p_vout->p_sys->p_win->base_window;
1369             event.format = 32;
1370             event.data.l[ 0 ] = 1; /* set property */
1371             event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_fullscreen;
1372
1373             XSendEvent( p_vout->p_sys->p_display,
1374                         DefaultRootWindow( p_vout->p_sys->p_display ),
1375                         False, SubstructureRedirectMask,
1376                         (XEvent*)&event );
1377         }
1378
1379         /* Make sure the change is effective */
1380         XReparentWindow( p_vout->p_sys->p_display,
1381                          p_vout->p_sys->p_win->base_window,
1382                          DefaultRootWindow( p_vout->p_sys->p_display ),
1383                          0, 0 );
1384
1385 #ifdef HAVE_XINERAMA
1386         if( XineramaQueryExtension( p_vout->p_sys->p_display, &i_d1, &i_d2 ) &&
1387             XineramaIsActive( p_vout->p_sys->p_display ) )
1388         {
1389             XineramaScreenInfo *screens;   /* infos for xinerama */
1390             int i_num_screens;
1391
1392             msg_Dbg( p_vout, "using XFree Xinerama extension");
1393
1394 #define SCREEN p_vout->p_sys->p_win->i_screen
1395
1396             /* Get Informations about Xinerama (num of screens) */
1397             screens = XineramaQueryScreens( p_vout->p_sys->p_display,
1398                                             &i_num_screens );
1399
1400             if( !SCREEN )
1401                 SCREEN = config_GetInt( p_vout,
1402                                         MODULE_STRING "-xineramascreen" );
1403
1404             /* just check that user has entered a good value */
1405             if( SCREEN >= i_num_screens || SCREEN < 0 )
1406             {
1407                 msg_Dbg( p_vout, "requested screen number invalid" );
1408                 SCREEN = 0;
1409             }
1410
1411             /* Get the X/Y upper left corner coordinate of the above screen */
1412             p_vout->p_sys->p_win->i_x = screens[SCREEN].x_org;
1413             p_vout->p_sys->p_win->i_y = screens[SCREEN].y_org;
1414
1415             /* Set the Height/width to the screen resolution */
1416             p_vout->p_sys->p_win->i_width = screens[SCREEN].width;
1417             p_vout->p_sys->p_win->i_height = screens[SCREEN].height;
1418
1419             XFree(screens);
1420
1421 #undef SCREEN
1422
1423         }
1424 #endif
1425
1426         XMoveResizeWindow( p_vout->p_sys->p_display,
1427                            p_vout->p_sys->p_win->base_window,
1428                            p_vout->p_sys->p_win->i_x,
1429                            p_vout->p_sys->p_win->i_y,
1430                            p_vout->p_sys->p_win->i_width,
1431                            p_vout->p_sys->p_win->i_height );
1432     }
1433     else
1434     {
1435         msg_Dbg( p_vout, "leaving fullscreen mode" );
1436         DestroyWindow( p_vout, &p_vout->p_sys->fullscreen_window );
1437         p_vout->p_sys->p_win = &p_vout->p_sys->original_window;
1438
1439         XMapWindow( p_vout->p_sys->p_display,
1440                     p_vout->p_sys->p_win->base_window);
1441     }
1442
1443     /* Unfortunately, using XSync() here is not enough to ensure the
1444      * window has already been mapped because the XMapWindow() request
1445      * has not necessarily been sent directly to our window (remember,
1446      * the call is first redirected to the window manager) */
1447     do
1448     {
1449         XWindowEvent( p_vout->p_sys->p_display,
1450                       p_vout->p_sys->p_win->base_window,
1451                       StructureNotifyMask, &xevent );
1452     } while( xevent.type != MapNotify );
1453
1454     /* Be careful, this can generate a BadMatch error if the window is not
1455      * already mapped by the server (see above) */
1456     XSetInputFocus(p_vout->p_sys->p_display,
1457                    p_vout->p_sys->p_win->base_window,
1458                    RevertToParent,
1459                    CurrentTime);
1460
1461     /* signal that the size needs to be updated */
1462     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1463 }
1464
1465 /*****************************************************************************
1466  * EnableXScreenSaver: enable screen saver
1467  *****************************************************************************
1468  * This function enables the screen saver on a display after it has been
1469  * disabled by XDisableScreenSaver.
1470  * FIXME: what happens if multiple vlc sessions are running at the same
1471  *        time ???
1472  *****************************************************************************/
1473 static void EnableXScreenSaver( vout_thread_t *p_vout )
1474 {
1475 #ifdef DPMSINFO_IN_DPMS_H
1476     int dummy;
1477 #endif
1478
1479     if( p_vout->p_sys->i_ss_timeout )
1480     {
1481         XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
1482                          p_vout->p_sys->i_ss_interval,
1483                          p_vout->p_sys->i_ss_blanking,
1484                          p_vout->p_sys->i_ss_exposure );
1485     }
1486
1487     /* Restore DPMS settings */
1488 #ifdef DPMSINFO_IN_DPMS_H
1489     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
1490     {
1491         if( p_vout->p_sys->b_ss_dpms )
1492         {
1493             DPMSEnable( p_vout->p_sys->p_display );
1494         }
1495     }
1496 #endif
1497 }
1498
1499 /*****************************************************************************
1500  * DisableXScreenSaver: disable screen saver
1501  *****************************************************************************
1502  * See XEnableXScreenSaver
1503  *****************************************************************************/
1504 static void DisableXScreenSaver( vout_thread_t *p_vout )
1505 {
1506 #ifdef DPMSINFO_IN_DPMS_H
1507     int dummy;
1508 #endif
1509
1510     /* Save screen saver informations */
1511     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
1512                      &p_vout->p_sys->i_ss_interval,
1513                      &p_vout->p_sys->i_ss_blanking,
1514                      &p_vout->p_sys->i_ss_exposure );
1515
1516     /* Disable screen saver */
1517     if( p_vout->p_sys->i_ss_timeout )
1518     {
1519         XSetScreenSaver( p_vout->p_sys->p_display, 0,
1520                          p_vout->p_sys->i_ss_interval,
1521                          p_vout->p_sys->i_ss_blanking,
1522                          p_vout->p_sys->i_ss_exposure );
1523     }
1524
1525     /* Disable DPMS */
1526 #ifdef DPMSINFO_IN_DPMS_H
1527     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
1528     {
1529         CARD16 unused;
1530         /* Save DPMS current state */
1531         DPMSInfo( p_vout->p_sys->p_display, &unused,
1532                   &p_vout->p_sys->b_ss_dpms );
1533         DPMSDisable( p_vout->p_sys->p_display );
1534    }
1535 #endif
1536 }
1537
1538 /*****************************************************************************
1539  * CreateCursor: create a blank mouse pointer
1540  *****************************************************************************/
1541 static void CreateCursor( vout_thread_t *p_vout )
1542 {
1543     XColor cursor_color;
1544
1545     p_vout->p_sys->cursor_pixmap =
1546         XCreatePixmap( p_vout->p_sys->p_display,
1547                        DefaultRootWindow( p_vout->p_sys->p_display ),
1548                        1, 1, 1 );
1549
1550     XParseColor( p_vout->p_sys->p_display,
1551                  XCreateColormap( p_vout->p_sys->p_display,
1552                                   DefaultRootWindow(
1553                                                     p_vout->p_sys->p_display ),
1554                                   DefaultVisual(
1555                                                 p_vout->p_sys->p_display,
1556                                                 p_vout->p_sys->i_screen ),
1557                                   AllocNone ),
1558                  "black", &cursor_color );
1559
1560     p_vout->p_sys->blank_cursor =
1561         XCreatePixmapCursor( p_vout->p_sys->p_display,
1562                              p_vout->p_sys->cursor_pixmap,
1563                              p_vout->p_sys->cursor_pixmap,
1564                              &cursor_color, &cursor_color, 1, 1 );
1565 }
1566
1567 /*****************************************************************************
1568  * DestroyCursor: destroy the blank mouse pointer
1569  *****************************************************************************/
1570 static void DestroyCursor( vout_thread_t *p_vout )
1571 {
1572     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
1573 }
1574
1575 /*****************************************************************************
1576  * ToggleCursor: hide or show the mouse pointer
1577  *****************************************************************************
1578  * This function hides the X pointer if it is visible by setting the pointer
1579  * sprite to a blank one. To show it again, we disable the sprite.
1580  *****************************************************************************/
1581 static void ToggleCursor( vout_thread_t *p_vout )
1582 {
1583     if( p_vout->p_sys->b_mouse_pointer_visible )
1584     {
1585         XDefineCursor( p_vout->p_sys->p_display,
1586                        p_vout->p_sys->p_win->base_window,
1587                        p_vout->p_sys->blank_cursor );
1588         p_vout->p_sys->b_mouse_pointer_visible = 0;
1589     }
1590     else
1591     {
1592         XUndefineCursor( p_vout->p_sys->p_display,
1593                          p_vout->p_sys->p_win->base_window );
1594         p_vout->p_sys->b_mouse_pointer_visible = 1;
1595     }
1596 }
1597
1598 #ifdef MODULE_NAME_IS_xvideo
1599 /*****************************************************************************
1600  * XVideoGetPort: get YUV12 port
1601  *****************************************************************************/
1602 static int XVideoGetPort( vout_thread_t *p_vout,
1603                           vlc_fourcc_t i_chroma, vlc_fourcc_t *pi_newchroma )
1604 {
1605     XvAdaptorInfo *p_adaptor;
1606     unsigned int i;
1607     int i_adaptor, i_num_adaptors, i_requested_adaptor;
1608     int i_selected_port;
1609
1610     switch( XvQueryExtension( p_vout->p_sys->p_display, &i, &i, &i, &i, &i ) )
1611     {
1612         case Success:
1613             break;
1614
1615         case XvBadExtension:
1616             msg_Warn( p_vout, "XvBadExtension" );
1617             return -1;
1618
1619         case XvBadAlloc:
1620             msg_Warn( p_vout, "XvBadAlloc" );
1621             return -1;
1622
1623         default:
1624             msg_Warn( p_vout, "XvQueryExtension failed" );
1625             return -1;
1626     }
1627
1628     switch( XvQueryAdaptors( p_vout->p_sys->p_display,
1629                              DefaultRootWindow( p_vout->p_sys->p_display ),
1630                              &i_num_adaptors, &p_adaptor ) )
1631     {
1632         case Success:
1633             break;
1634
1635         case XvBadExtension:
1636             msg_Warn( p_vout, "XvBadExtension for XvQueryAdaptors" );
1637             return -1;
1638
1639         case XvBadAlloc:
1640             msg_Warn( p_vout, "XvBadAlloc for XvQueryAdaptors" );
1641             return -1;
1642
1643         default:
1644             msg_Warn( p_vout, "XvQueryAdaptors failed" );
1645             return -1;
1646     }
1647
1648     i_selected_port = -1;
1649     i_requested_adaptor = config_GetInt( p_vout, "xvideo-adaptor" );
1650
1651     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
1652     {
1653         XvImageFormatValues *p_formats;
1654         int i_format, i_num_formats;
1655         int i_port;
1656
1657         /* If we requested an adaptor and it's not this one, we aren't
1658          * interested */
1659         if( i_requested_adaptor != -1 && i_adaptor != i_requested_adaptor )
1660         {
1661             continue;
1662         }
1663
1664         /* If the adaptor doesn't have the required properties, skip it */
1665         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
1666             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
1667         {
1668             continue;
1669         }
1670
1671         /* Check that adaptor supports our requested format... */
1672         p_formats = XvListImageFormats( p_vout->p_sys->p_display,
1673                                         p_adaptor[i_adaptor].base_id,
1674                                         &i_num_formats );
1675
1676         for( i_format = 0;
1677              i_format < i_num_formats && ( i_selected_port == -1 );
1678              i_format++ )
1679         {
1680             /* Code removed, we can get this through xvinfo anyway */
1681 #if 0
1682             XvEncodingInfo  *p_enc;
1683             int             i_enc, i_num_encodings;
1684             XvAttribute     *p_attr;
1685             int             i_attr, i_num_attributes;
1686 #endif
1687
1688             /* If this is not the format we want, or at least a
1689              * similar one, forget it */
1690             if( !vout_ChromaCmp( p_formats[ i_format ].id, i_chroma ) )
1691             {
1692                 continue;
1693             }
1694
1695             /* Look for the first available port supporting this format */
1696             for( i_port = p_adaptor[i_adaptor].base_id;
1697                  ( i_port < (int)(p_adaptor[i_adaptor].base_id
1698                                    + p_adaptor[i_adaptor].num_ports) )
1699                    && ( i_selected_port == -1 );
1700                  i_port++ )
1701             {
1702                 if( XvGrabPort( p_vout->p_sys->p_display, i_port, CurrentTime )
1703                      == Success )
1704                 {
1705                     i_selected_port = i_port;
1706                     *pi_newchroma = p_formats[ i_format ].id;
1707                 }
1708             }
1709
1710             /* If no free port was found, forget it */
1711             if( i_selected_port == -1 )
1712             {
1713                 continue;
1714             }
1715
1716             /* If we found a port, print information about it */
1717             msg_Dbg( p_vout, "adaptor %i, port %i, format 0x%x (%4.4s) %s",
1718                      i_adaptor, i_selected_port, p_formats[ i_format ].id,
1719                      (char *)&p_formats[ i_format ].id,
1720                      ( p_formats[ i_format ].format == XvPacked ) ?
1721                          "packed" : "planar" );
1722
1723 #if 0
1724             msg_Dbg( p_vout, " encoding list:" );
1725
1726             if( XvQueryEncodings( p_vout->p_sys->p_display, i_selected_port,
1727                                   &i_num_encodings, &p_enc )
1728                  != Success )
1729             {
1730                 msg_Dbg( p_vout, "  XvQueryEncodings failed" );
1731                 continue;
1732             }
1733
1734             for( i_enc = 0; i_enc < i_num_encodings; i_enc++ )
1735             {
1736                 msg_Dbg( p_vout, "  id=%ld, name=%s, size=%ldx%ld,"
1737                                       " numerator=%d, denominator=%d",
1738                              p_enc[i_enc].encoding_id, p_enc[i_enc].name,
1739                              p_enc[i_enc].width, p_enc[i_enc].height,
1740                              p_enc[i_enc].rate.numerator,
1741                              p_enc[i_enc].rate.denominator );
1742             }
1743
1744             if( p_enc != NULL )
1745             {
1746                 XvFreeEncodingInfo( p_enc );
1747             }
1748
1749             msg_Dbg( p_vout, " attribute list:" );
1750             p_attr = XvQueryPortAttributes( p_vout->p_sys->p_display,
1751                                             i_selected_port,
1752                                             &i_num_attributes );
1753             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
1754             {
1755                 msg_Dbg( p_vout, "  name=%s, flags=[%s%s ], min=%i, max=%i",
1756                       p_attr[i_attr].name,
1757                       (p_attr[i_attr].flags & XvGettable) ? " get" : "",
1758                       (p_attr[i_attr].flags & XvSettable) ? " set" : "",
1759                       p_attr[i_attr].min_value, p_attr[i_attr].max_value );
1760             }
1761
1762             if( p_attr != NULL )
1763             {
1764                 XFree( p_attr );
1765             }
1766 #endif
1767         }
1768
1769         if( p_formats != NULL )
1770         {
1771             XFree( p_formats );
1772         }
1773
1774     }
1775
1776     if( i_num_adaptors > 0 )
1777     {
1778         XvFreeAdaptorInfo( p_adaptor );
1779     }
1780
1781     if( i_selected_port == -1 )
1782     {
1783         int i_chroma_tmp = X112VLC_FOURCC( i_chroma );
1784         if( i_requested_adaptor == -1 )
1785         {
1786             msg_Warn( p_vout, "no free XVideo port found for format "
1787                       "0x%.8x (%4.4s)", i_chroma_tmp, (char*)&i_chroma_tmp );
1788         }
1789         else
1790         {
1791             msg_Warn( p_vout, "XVideo adaptor %i does not have a free "
1792                       "XVideo port for format 0x%.8x (%4.4s)",
1793                       i_requested_adaptor, i_chroma_tmp, (char*)&i_chroma_tmp );
1794         }
1795     }
1796
1797     return i_selected_port;
1798 }
1799
1800 /*****************************************************************************
1801  * XVideoReleasePort: release YUV12 port
1802  *****************************************************************************/
1803 static void XVideoReleasePort( vout_thread_t *p_vout, int i_port )
1804 {
1805     XvUngrabPort( p_vout->p_sys->p_display, i_port, CurrentTime );
1806 }
1807 #endif
1808
1809 /*****************************************************************************
1810  * InitDisplay: open and initialize X11 device
1811  *****************************************************************************
1812  * Create a window according to video output given size, and set other
1813  * properties according to the display properties.
1814  *****************************************************************************/
1815 static int InitDisplay( vout_thread_t *p_vout )
1816 {
1817 #ifdef MODULE_NAME_IS_x11
1818     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
1819     XVisualInfo *               p_xvisual;           /* visuals informations */
1820     XVisualInfo                 xvisual_template;         /* visual template */
1821     int                         i_count;                       /* array size */
1822 #endif
1823
1824 #ifdef HAVE_SYS_SHM_H
1825     p_vout->p_sys->b_shm = 0;
1826
1827     if( config_GetInt( p_vout, MODULE_STRING "-shm" ) )
1828     {
1829 #   ifdef SYS_DARWIN
1830         /* FIXME: As of 2001-03-16, XFree4 for MacOS X does not support Xshm */
1831 #   else
1832         p_vout->p_sys->b_shm =
1833                   ( XShmQueryExtension( p_vout->p_sys->p_display ) == True );
1834 #   endif
1835
1836         if( !p_vout->p_sys->b_shm )
1837         {
1838             msg_Warn( p_vout, "XShm video extension is unavailable" );
1839         }
1840     }
1841     else
1842     {
1843         msg_Dbg( p_vout, "disabling XShm video extension" );
1844     }
1845
1846 #else
1847     msg_Warn( p_vout, "XShm video extension is unavailable" );
1848
1849 #endif
1850
1851 #ifdef MODULE_NAME_IS_xvideo
1852     /* XXX The brightness and contrast values should be read from environment
1853      * XXX variables... */
1854 #if 0
1855     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
1856     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
1857 #endif
1858 #endif
1859
1860 #ifdef MODULE_NAME_IS_x11
1861     /* Initialize structure */
1862     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
1863
1864     /* Get screen depth */
1865     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
1866                                                    p_vout->p_sys->i_screen );
1867     switch( p_vout->p_sys->i_screen_depth )
1868     {
1869     case 8:
1870         /*
1871          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
1872          */
1873         xvisual_template.screen =   p_vout->p_sys->i_screen;
1874         xvisual_template.class =    DirectColor;
1875         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
1876                                     VisualScreenMask | VisualClassMask,
1877                                     &xvisual_template, &i_count );
1878         if( p_xvisual == NULL )
1879         {
1880             msg_Err( p_vout, "no PseudoColor visual available" );
1881             return VLC_EGENERIC;
1882         }
1883         p_vout->p_sys->i_bytes_per_pixel = 1;
1884         p_vout->output.pf_setpalette = SetPalette;
1885         break;
1886     case 15:
1887     case 16:
1888     case 24:
1889     default:
1890         /*
1891          * Screen depth is higher than 8bpp. TrueColor visual is used.
1892          */
1893         xvisual_template.screen =   p_vout->p_sys->i_screen;
1894         xvisual_template.class =    TrueColor;
1895         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
1896                                     VisualScreenMask | VisualClassMask,
1897                                     &xvisual_template, &i_count );
1898         if( p_xvisual == NULL )
1899         {
1900             msg_Err( p_vout, "no TrueColor visual available" );
1901             return VLC_EGENERIC;
1902         }
1903
1904         p_vout->output.i_rmask = p_xvisual->red_mask;
1905         p_vout->output.i_gmask = p_xvisual->green_mask;
1906         p_vout->output.i_bmask = p_xvisual->blue_mask;
1907
1908         /* There is no difference yet between 3 and 4 Bpp. The only way
1909          * to find the actual number of bytes per pixel is to list supported
1910          * pixmap formats. */
1911         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
1912         p_vout->p_sys->i_bytes_per_pixel = 0;
1913
1914         for( ; i_count-- ; p_formats++ )
1915         {
1916             /* Under XFree4.0, the list contains pixmap formats available
1917              * through all video depths ; so we have to check against current
1918              * depth. */
1919             if( p_formats->depth == (int)p_vout->p_sys->i_screen_depth )
1920             {
1921                 if( p_formats->bits_per_pixel / 8
1922                         > (int)p_vout->p_sys->i_bytes_per_pixel )
1923                 {
1924                     p_vout->p_sys->i_bytes_per_pixel =
1925                                                p_formats->bits_per_pixel / 8;
1926                 }
1927             }
1928         }
1929         break;
1930     }
1931     p_vout->p_sys->p_visual = p_xvisual->visual;
1932     XFree( p_xvisual );
1933 #endif
1934
1935     return VLC_SUCCESS;
1936 }
1937
1938 #ifdef HAVE_SYS_SHM_H
1939 /*****************************************************************************
1940  * CreateShmImage: create an XImage or XvImage using shared memory extension
1941  *****************************************************************************
1942  * Prepare an XImage or XvImage for display function.
1943  * The order of the operations respects the recommandations of the mit-shm
1944  * document by J.Corbet and K.Packard. Most of the parameters were copied from
1945  * there. See http://ftp.xfree86.org/pub/XFree86/4.0/doc/mit-shm.TXT
1946  *****************************************************************************/
1947 static IMAGE_TYPE * CreateShmImage( vout_thread_t *p_vout,
1948                                     Display* p_display, EXTRA_ARGS_SHM,
1949                                     int i_width, int i_height )
1950 {
1951     IMAGE_TYPE *p_image;
1952
1953     /* Create XImage / XvImage */
1954 #ifdef MODULE_NAME_IS_xvideo
1955     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
1956                                 i_width, i_height, p_shm );
1957 #else
1958     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
1959                                p_shm, i_width, i_height );
1960 #endif
1961     if( p_image == NULL )
1962     {
1963         msg_Err( p_vout, "image creation failed" );
1964         return NULL;
1965     }
1966
1967     /* Allocate shared memory segment - 0776 set the access permission
1968      * rights (like umask), they are not yet supported by all X servers */
1969     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE(p_image), IPC_CREAT | 0776 );
1970     if( p_shm->shmid < 0 )
1971     {
1972         msg_Err( p_vout, "cannot allocate shared image data (%s)",
1973                          strerror( errno ) );
1974         IMAGE_FREE( p_image );
1975         return NULL;
1976     }
1977
1978     /* Attach shared memory segment to process (read/write) */
1979     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
1980     if(! p_shm->shmaddr )
1981     {
1982         msg_Err( p_vout, "cannot attach shared memory (%s)",
1983                          strerror(errno));
1984         IMAGE_FREE( p_image );
1985         shmctl( p_shm->shmid, IPC_RMID, 0 );
1986         return NULL;
1987     }
1988
1989     /* Read-only data. We won't be using XShmGetImage */
1990     p_shm->readOnly = True;
1991
1992     /* Attach shared memory segment to X server */
1993     if( XShmAttach( p_display, p_shm ) == False )
1994     {
1995         msg_Err( p_vout, "cannot attach shared memory to X server" );
1996         IMAGE_FREE( p_image );
1997         shmctl( p_shm->shmid, IPC_RMID, 0 );
1998         shmdt( p_shm->shmaddr );
1999         return NULL;
2000     }
2001
2002     /* Send image to X server. This instruction is required, since having
2003      * built a Shm XImage and not using it causes an error on XCloseDisplay,
2004      * and remember NOT to use XFlush ! */
2005     XSync( p_display, False );
2006
2007 #if 0
2008     /* Mark the shm segment to be removed when there are no more
2009      * attachements, so it is automatic on process exit or after shmdt */
2010     shmctl( p_shm->shmid, IPC_RMID, 0 );
2011 #endif
2012
2013     return p_image;
2014 }
2015 #endif
2016
2017 /*****************************************************************************
2018  * CreateImage: create an XImage or XvImage
2019  *****************************************************************************
2020  * Create a simple image used as a buffer.
2021  *****************************************************************************/
2022 static IMAGE_TYPE * CreateImage( vout_thread_t *p_vout,
2023                                  Display *p_display, EXTRA_ARGS,
2024                                  int i_width, int i_height )
2025 {
2026     byte_t *    p_data;                           /* image data storage zone */
2027     IMAGE_TYPE *p_image;
2028 #ifdef MODULE_NAME_IS_x11
2029     int         i_quantum;                     /* XImage quantum (see below) */
2030     int         i_bytes_per_line;
2031 #endif
2032
2033     /* Allocate memory for image */
2034 #ifdef MODULE_NAME_IS_xvideo
2035     p_data = (byte_t *) malloc( i_width * i_height * i_bits_per_pixel / 8 );
2036 #else
2037     i_bytes_per_line = i_width * i_bytes_per_pixel;
2038     p_data = (byte_t *) malloc( i_bytes_per_line * i_height );
2039 #endif
2040     if( !p_data )
2041     {
2042         msg_Err( p_vout, "out of memory" );
2043         return NULL;
2044     }
2045
2046 #ifdef MODULE_NAME_IS_x11
2047     /* Optimize the quantum of a scanline regarding its size - the quantum is
2048        a diviser of the number of bits between the start of two scanlines. */
2049     if( i_bytes_per_line & 0xf )
2050     {
2051         i_quantum = 0x8;
2052     }
2053     else if( i_bytes_per_line & 0x10 )
2054     {
2055         i_quantum = 0x10;
2056     }
2057     else
2058     {
2059         i_quantum = 0x20;
2060     }
2061 #endif
2062
2063     /* Create XImage. p_data will be automatically freed */
2064 #ifdef MODULE_NAME_IS_xvideo
2065     p_image = XvCreateImage( p_display, i_xvport, i_chroma,
2066                              p_data, i_width, i_height );
2067 #else
2068     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2069                             p_data, i_width, i_height, i_quantum, 0 );
2070 #endif
2071     if( p_image == NULL )
2072     {
2073         msg_Err( p_vout, "XCreateImage() failed" );
2074         free( p_data );
2075         return NULL;
2076     }
2077
2078     return p_image;
2079 }
2080
2081 #ifdef MODULE_NAME_IS_x11
2082 /*****************************************************************************
2083  * SetPalette: sets an 8 bpp palette
2084  *****************************************************************************
2085  * This function sets the palette given as an argument. It does not return
2086  * anything, but could later send information on which colors it was unable
2087  * to set.
2088  *****************************************************************************/
2089 static void SetPalette( vout_thread_t *p_vout,
2090                         uint16_t *red, uint16_t *green, uint16_t *blue )
2091 {
2092     int i;
2093     XColor p_colors[255];
2094
2095     /* allocate palette */
2096     for( i = 0; i < 255; i++ )
2097     {
2098         /* kludge: colors are indexed reversely because color 255 seems
2099          * to be reserved for black even if we try to set it to white */
2100         p_colors[ i ].pixel = 255 - i;
2101         p_colors[ i ].pad   = 0;
2102         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
2103         p_colors[ i ].red   = red[ 255 - i ];
2104         p_colors[ i ].blue  = blue[ 255 - i ];
2105         p_colors[ i ].green = green[ 255 - i ];
2106     }
2107
2108     XStoreColors( p_vout->p_sys->p_display,
2109                   p_vout->p_sys->colormap, p_colors, 255 );
2110 }
2111 #endif
2112
2113 /*****************************************************************************
2114  * Control: control facility for the vout
2115  *****************************************************************************/
2116 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
2117 {
2118     double f_arg;
2119     vlc_bool_t b_arg;
2120
2121     switch( i_query )
2122     {
2123         case VOUT_SET_ZOOM:
2124             if( p_vout->p_sys->p_win->owner_window )
2125                 return vout_ControlWindow( p_vout,
2126                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2127
2128             f_arg = va_arg( args, double );
2129
2130             /* Update dimensions */
2131             XResizeWindow( p_vout->p_sys->p_display,
2132                            p_vout->p_sys->p_win->base_window,
2133                            p_vout->render.i_width * f_arg,
2134                            p_vout->render.i_height * f_arg );
2135
2136             return VLC_SUCCESS;
2137
2138        case VOUT_REPARENT:
2139             XReparentWindow( p_vout->p_sys->p_display,
2140                              p_vout->p_sys->p_win->base_window,
2141                              DefaultRootWindow( p_vout->p_sys->p_display ),
2142                              0, 0 );
2143             XSync( p_vout->p_sys->p_display, False );
2144             p_vout->p_sys->p_win->owner_window = 0;
2145             return VLC_SUCCESS;
2146
2147         case VOUT_SET_STAY_ON_TOP:
2148             if( p_vout->p_sys->p_win->owner_window )
2149                 return vout_ControlWindow( p_vout,
2150                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2151
2152             b_arg = va_arg( args, vlc_bool_t );
2153             WindowOnTop( p_vout, b_arg );
2154             return VLC_SUCCESS;
2155
2156        default:
2157             msg_Dbg( p_vout, "control query not supported" );
2158             return VLC_EGENERIC;
2159     }
2160 }
2161
2162 /*****************************************************************************
2163  * TestNetWMSupport: tests for Extended Window Manager Hints support
2164  *****************************************************************************/
2165 static void TestNetWMSupport( vout_thread_t *p_vout )
2166 {
2167     int i_ret, i_format;
2168     unsigned long i, i_items, i_bytesafter;
2169     Atom net_wm_supported, *p_args = NULL;
2170
2171     p_vout->p_sys->b_net_wm_state_fullscreen = VLC_FALSE;
2172     p_vout->p_sys->b_net_wm_state_above = VLC_FALSE;
2173     p_vout->p_sys->b_net_wm_state_below = VLC_FALSE;
2174     p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_FALSE;
2175
2176     net_wm_supported =
2177         XInternAtom( p_vout->p_sys->p_display, "_NET_SUPPORTED", False );
2178
2179     i_ret = XGetWindowProperty( p_vout->p_sys->p_display,
2180                                 DefaultRootWindow( p_vout->p_sys->p_display ),
2181                                 net_wm_supported,
2182                                 0, 16384, False, AnyPropertyType,
2183                                 &net_wm_supported,
2184                                 &i_format, &i_items, &i_bytesafter,
2185                                 (unsigned char **)(intptr_t)&p_args );
2186
2187     if( i_ret != Success || i_items == 0 ) return;
2188
2189     msg_Dbg( p_vout, "Window manager supports NetWM" );
2190
2191     p_vout->p_sys->net_wm_state =
2192         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE", False );
2193     p_vout->p_sys->net_wm_state_fullscreen =
2194         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_FULLSCREEN",
2195                      False );
2196     p_vout->p_sys->net_wm_state_above =
2197         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_ABOVE", False );
2198     p_vout->p_sys->net_wm_state_below =
2199         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_BELOW", False );
2200     p_vout->p_sys->net_wm_state_stays_on_top =
2201         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_STAYS_ON_TOP",
2202                      False );
2203
2204     for( i = 0; i < i_items; i++ )
2205     {
2206         if( p_args[i] == p_vout->p_sys->net_wm_state_fullscreen )
2207         {
2208             msg_Dbg( p_vout,
2209                      "Window manager supports _NET_WM_STATE_FULLSCREEN" );
2210             p_vout->p_sys->b_net_wm_state_fullscreen = VLC_TRUE;
2211         }
2212         else if( p_args[i] == p_vout->p_sys->net_wm_state_above )
2213         {
2214             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_ABOVE" );
2215             p_vout->p_sys->b_net_wm_state_above = VLC_TRUE;
2216         }
2217         else if( p_args[i] == p_vout->p_sys->net_wm_state_below )
2218         {
2219             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_BELOW" );
2220             p_vout->p_sys->b_net_wm_state_below = VLC_TRUE;
2221         }
2222         else if( p_args[i] == p_vout->p_sys->net_wm_state_stays_on_top )
2223         {
2224             msg_Dbg( p_vout,
2225                      "Window manager supports _NET_WM_STATE_STAYS_ON_TOP" );
2226             p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_TRUE;
2227         }
2228     }
2229
2230     XFree( p_args );
2231 }
2232
2233 /*****************************************************************************
2234  * Key events handling
2235  *****************************************************************************/
2236 static struct
2237 {
2238     int i_x11key;
2239     int i_vlckey;
2240
2241 } x11keys_to_vlckeys[] =
2242 {
2243     { XK_F1, KEY_F1 }, { XK_F2, KEY_F2 }, { XK_F3, KEY_F3 }, { XK_F4, KEY_F4 },
2244     { XK_F5, KEY_F5 }, { XK_F6, KEY_F6 }, { XK_F7, KEY_F7 }, { XK_F8, KEY_F8 },
2245     { XK_F9, KEY_F9 }, { XK_F10, KEY_F10 }, { XK_F11, KEY_F11 },
2246     { XK_F12, KEY_F12 },
2247
2248     { XK_Return, KEY_ENTER },
2249     { XK_KP_Enter, KEY_ENTER },
2250     { XK_space, KEY_SPACE },
2251     { XK_Escape, KEY_ESC },
2252
2253     { XK_Menu, KEY_MENU },
2254     { XK_Left, KEY_LEFT },
2255     { XK_Right, KEY_RIGHT },
2256     { XK_Up, KEY_UP },
2257     { XK_Down, KEY_DOWN },
2258
2259     { XK_Home, KEY_HOME },
2260     { XK_End, KEY_END },
2261     { XK_Page_Up, KEY_PAGEUP },
2262     { XK_Page_Down, KEY_PAGEDOWN },
2263     { 0, 0 }
2264 };
2265
2266 static int ConvertKey( int i_key )
2267 {
2268     int i;
2269
2270     for( i = 0; x11keys_to_vlckeys[i].i_x11key != 0; i++ )
2271     {
2272         if( x11keys_to_vlckeys[i].i_x11key == i_key )
2273         {
2274             return x11keys_to_vlckeys[i].i_vlckey;
2275         }
2276     }
2277
2278     return 0;
2279 }
2280
2281 /*****************************************************************************
2282  * WindowOnTop: Switches the "always on top" state of the video window.
2283  *****************************************************************************/
2284 static int WindowOnTop( vout_thread_t *p_vout, vlc_bool_t b_on_top )
2285 {
2286     if( p_vout->p_sys->b_net_wm_state_stays_on_top )
2287     {
2288         XClientMessageEvent event;
2289
2290         memset( &event, 0, sizeof( XClientMessageEvent ) );
2291
2292         event.type = ClientMessage;
2293         event.message_type = p_vout->p_sys->net_wm_state;
2294         event.display = p_vout->p_sys->p_display;
2295         event.window = p_vout->p_sys->p_win->base_window;
2296         event.format = 32;
2297         event.data.l[ 0 ] = b_on_top; /* set property */
2298         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_stays_on_top;
2299
2300         XSendEvent( p_vout->p_sys->p_display,
2301                     DefaultRootWindow( p_vout->p_sys->p_display ),
2302                     False, SubstructureRedirectMask,
2303                     (XEvent*)&event );
2304     }
2305
2306     return VLC_SUCCESS;
2307 }