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