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