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