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