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