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