]> git.sesse.net Git - vlc/blob - modules/video_output/x11/xcommon.c
Enables "stay on top" with window managers that don't handle _NET_WM_STATE_STAYS_ON_TOP
[vlc] / modules / video_output / x11 / xcommon.c
1 /*****************************************************************************
2  * xcommon.c: Functions common to the X11 and XVideo plugins
3  *****************************************************************************
4  * Copyright (C) 1998-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Sam Hocevar <sam@zoy.org>
9  *          David Kennedy <dkennedy@tinytoad.com>
10  *          Gildas Bazin <gbazin@videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, 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/Xproto.h>
56 #include <X11/Xmd.h>
57 #include <X11/Xutil.h>
58 #include <X11/keysym.h>
59 #ifdef HAVE_SYS_SHM_H
60 #   include <X11/extensions/XShm.h>
61 #endif
62 #ifdef DPMSINFO_IN_DPMS_H
63 #   include <X11/extensions/dpms.h>
64 #endif
65
66 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
67 #   include <X11/extensions/Xv.h>
68 #   include <X11/extensions/Xvlib.h>
69 #endif
70
71 #ifdef MODULE_NAME_IS_glx
72 #   include <GL/glx.h>
73 #endif
74
75 #ifdef HAVE_XINERAMA
76 #   include <X11/extensions/Xinerama.h>
77 #endif
78
79 #ifdef HAVE_X11_EXTENSIONS_XF86VMODE_H
80 #   include <X11/extensions/xf86vmode.h>
81 #endif
82
83 #ifdef MODULE_NAME_IS_xvmc
84 #   include <X11/extensions/vldXvMC.h>
85 #   include "../../codec/xvmc/accel_xvmc.h"
86 #endif
87
88 #include "xcommon.h"
89
90 /*****************************************************************************
91  * Local prototypes
92  *****************************************************************************/
93 int  E_(Activate)   ( vlc_object_t * );
94 void E_(Deactivate) ( vlc_object_t * );
95
96 static int  InitVideo      ( vout_thread_t * );
97 static void EndVideo       ( vout_thread_t * );
98 static void DisplayVideo   ( vout_thread_t *, picture_t * );
99 static int  ManageVideo    ( vout_thread_t * );
100 static int  Control        ( vout_thread_t *, int, va_list );
101
102 static int  InitDisplay    ( vout_thread_t * );
103
104 static int  CreateWindow   ( vout_thread_t *, x11_window_t * );
105 static void DestroyWindow  ( vout_thread_t *, x11_window_t * );
106
107 static int  NewPicture     ( vout_thread_t *, picture_t * );
108 static void FreePicture    ( vout_thread_t *, picture_t * );
109
110 static IMAGE_TYPE *CreateImage    ( vout_thread_t *,
111                                     Display *, EXTRA_ARGS, int, int );
112 #ifdef HAVE_SYS_SHM_H
113 static IMAGE_TYPE *CreateShmImage ( vout_thread_t *,
114                                     Display *, EXTRA_ARGS_SHM, int, int );
115 static vlc_bool_t b_shm = VLC_TRUE;
116 #endif
117
118 static void ToggleFullScreen      ( vout_thread_t * );
119
120 static void EnableXScreenSaver    ( vout_thread_t * );
121 static void DisableXScreenSaver   ( vout_thread_t * );
122
123 static void CreateCursor   ( vout_thread_t * );
124 static void DestroyCursor  ( vout_thread_t * );
125 static void ToggleCursor   ( vout_thread_t * );
126
127 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
128 static int  XVideoGetPort    ( vout_thread_t *, vlc_fourcc_t, vlc_fourcc_t * );
129 static void XVideoReleasePort( vout_thread_t *, int );
130 #endif
131
132 #ifdef MODULE_NAME_IS_x11
133 static void SetPalette     ( vout_thread_t *,
134                              uint16_t *, uint16_t *, uint16_t * );
135 #endif
136
137 #ifdef MODULE_NAME_IS_xvmc
138 static void RenderVideo    ( vout_thread_t *, picture_t * );
139 static int  xvmc_check_yv12( Display *display, XvPortID port );
140 static void xvmc_update_XV_DOUBLE_BUFFER( vout_thread_t *p_vout );
141 #endif
142
143 static void TestNetWMSupport( vout_thread_t * );
144 static int ConvertKey( int );
145
146 static int WindowOnTop( vout_thread_t *, vlc_bool_t );
147
148 static int X11ErrorHandler( Display *, XErrorEvent * );
149
150 /*****************************************************************************
151  * Activate: allocate X11 video thread output method
152  *****************************************************************************
153  * This function allocate and initialize a X11 vout method. It uses some of the
154  * vout properties to choose the window size, and change them according to the
155  * actual properties of the display.
156  *****************************************************************************/
157 int E_(Activate) ( vlc_object_t *p_this )
158 {
159     vout_thread_t *p_vout = (vout_thread_t *)p_this;
160     char *        psz_display;
161     vlc_value_t   val;
162 #if defined(MODULE_NAME_IS_xvmc)
163     char *psz_value;
164 #endif
165 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
166     char *       psz_chroma;
167     vlc_fourcc_t i_chroma = 0;
168     vlc_bool_t   b_chroma = 0;
169 #endif
170
171     p_vout->pf_init = InitVideo;
172     p_vout->pf_end = EndVideo;
173     p_vout->pf_manage = ManageVideo;
174 #ifdef MODULE_NAME_IS_xvmc
175     p_vout->pf_render = RenderVideo;
176 #else
177     p_vout->pf_render = NULL;
178 #endif
179     p_vout->pf_display = DisplayVideo;
180     p_vout->pf_control = Control;
181
182     /* Allocate structure */
183     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
184     if( p_vout->p_sys == NULL )
185     {
186         msg_Err( p_vout, "out of memory" );
187         return VLC_ENOMEM;
188     }
189
190     vlc_mutex_init( p_vout, &p_vout->p_sys->lock );
191
192     /* Open display, using the "display" config variable or the DISPLAY
193      * environment variable */
194     psz_display = config_GetPsz( p_vout, MODULE_STRING "-display" );
195
196     p_vout->p_sys->p_display = XOpenDisplay( psz_display );
197
198     if( p_vout->p_sys->p_display == NULL )                          /* error */
199     {
200         msg_Err( p_vout, "cannot open display %s",
201                          XDisplayName( psz_display ) );
202         free( p_vout->p_sys );
203         if( psz_display ) free( psz_display );
204         return VLC_EGENERIC;
205     }
206     if( psz_display ) free( psz_display );
207
208     /* Replace error handler so we can intercept some non-fatal errors */
209     XSetErrorHandler( X11ErrorHandler );
210
211     /* Get a screen ID matching the XOpenDisplay return value */
212     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
213
214 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
215     psz_chroma = config_GetPsz( p_vout, "xvideo-chroma" );
216     if( psz_chroma )
217     {
218         if( strlen( psz_chroma ) >= 4 )
219         {
220             /* Do not use direct assignment because we are not sure of the
221              * alignment. */
222             memcpy(&i_chroma, psz_chroma, 4);
223             b_chroma = 1;
224         }
225
226         free( psz_chroma );
227     }
228
229     if( b_chroma )
230     {
231         msg_Dbg( p_vout, "forcing chroma 0x%.8x (%4.4s)",
232                  i_chroma, (char*)&i_chroma );
233     }
234     else
235     {
236         i_chroma = p_vout->render.i_chroma;
237     }
238
239     /* Check that we have access to an XVideo port providing this chroma */
240     p_vout->p_sys->i_xvport = XVideoGetPort( p_vout, VLC2X11_FOURCC(i_chroma),
241                                              &p_vout->output.i_chroma );
242     if( p_vout->p_sys->i_xvport < 0 )
243     {
244         /* If a specific chroma format was requested, then we don't try to
245          * be cleverer than the user. He knew pretty well what he wanted. */
246         if( b_chroma )
247         {
248             XCloseDisplay( p_vout->p_sys->p_display );
249             free( p_vout->p_sys );
250             return VLC_EGENERIC;
251         }
252
253         /* It failed, but it's not completely lost ! We try to open an
254          * XVideo port for an YUY2 picture. We'll need to do an YUV
255          * conversion, but at least it has got scaling. */
256         p_vout->p_sys->i_xvport =
257                         XVideoGetPort( p_vout, X11_FOURCC('Y','U','Y','2'),
258                                                &p_vout->output.i_chroma );
259         if( p_vout->p_sys->i_xvport < 0 )
260         {
261             /* It failed, but it's not completely lost ! We try to open an
262              * XVideo port for a simple 16bpp RGB picture. We'll need to do
263              * an YUV conversion, but at least it has got scaling. */
264             p_vout->p_sys->i_xvport =
265                             XVideoGetPort( p_vout, X11_FOURCC('R','V','1','6'),
266                                                    &p_vout->output.i_chroma );
267             if( p_vout->p_sys->i_xvport < 0 )
268             {
269                 XCloseDisplay( p_vout->p_sys->p_display );
270                 free( p_vout->p_sys );
271                 return VLC_EGENERIC;
272             }
273         }
274     }
275     p_vout->output.i_chroma = X112VLC_FOURCC(p_vout->output.i_chroma);
276 #endif
277
278     /* Create blank cursor (for mouse cursor autohiding) */
279     p_vout->p_sys->i_time_mouse_last_moved = mdate();
280     p_vout->p_sys->b_mouse_pointer_visible = 1;
281     CreateCursor( p_vout );
282
283     /* Set main window's size */
284     p_vout->p_sys->original_window.i_width = p_vout->i_window_width;
285     p_vout->p_sys->original_window.i_height = p_vout->i_window_height;
286     var_Create( p_vout, "video-title", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
287     /* Spawn base window - this window will include the video output window,
288      * but also command buttons, subtitles and other indicators */
289     if( CreateWindow( p_vout, &p_vout->p_sys->original_window ) )
290     {
291         msg_Err( p_vout, "cannot create X11 window" );
292         DestroyCursor( p_vout );
293         XCloseDisplay( p_vout->p_sys->p_display );
294         free( p_vout->p_sys );
295         return VLC_EGENERIC;
296     }
297
298     /* Open and initialize device. */
299     if( InitDisplay( p_vout ) )
300     {
301         msg_Err( p_vout, "cannot initialize X11 display" );
302         DestroyCursor( p_vout );
303         DestroyWindow( p_vout, &p_vout->p_sys->original_window );
304         XCloseDisplay( p_vout->p_sys->p_display );
305         free( p_vout->p_sys );
306         return VLC_EGENERIC;
307     }
308
309     /* Disable screen saver */
310     DisableXScreenSaver( p_vout );
311
312     /* Misc init */
313     p_vout->p_sys->b_altfullscreen = 0;
314     p_vout->p_sys->i_time_button_last_pressed = 0;
315
316     TestNetWMSupport( p_vout );
317
318 #ifdef MODULE_NAME_IS_xvmc
319     p_vout->p_sys->p_last_subtitle_save = NULL;
320     psz_value = config_GetPsz( p_vout, "xvmc-deinterlace-mode" );
321
322     /* Look what method was requested */
323     //var_Create( p_vout, "xvmc-deinterlace-mode", VLC_VAR_STRING );
324     //var_Change( p_vout, "xvmc-deinterlace-mode", VLC_VAR_INHERITVALUE, &val, NULL );
325     if( psz_value )
326     {
327         if( (strcmp(psz_value, "bob") == 0) ||
328             (strcmp(psz_value, "blend") == 0) )
329            p_vout->p_sys->xvmc_deinterlace_method = 2;
330         else if (strcmp(psz_value, "discard") == 0)
331            p_vout->p_sys->xvmc_deinterlace_method = 1;
332         else
333            p_vout->p_sys->xvmc_deinterlace_method = 0;
334         free(psz_value );
335     }
336     else
337         p_vout->p_sys->xvmc_deinterlace_method = 0;
338
339     /* Look what method was requested */
340     //var_Create( p_vout, "xvmc-crop-style", VLC_VAR_STRING );
341     //var_Change( p_vout, "xvmc-crop-style", VLC_VAR_INHERITVALUE, &val, NULL );
342     psz_value = config_GetPsz( p_vout, "xvmc-crop-style" );
343
344     if( psz_value )
345     {
346         if( strncmp( psz_value, "eq", 2 ) == 0 )
347            p_vout->p_sys->xvmc_crop_style = 1;
348         else if( strncmp( psz_value, "4-16", 4 ) == 0)
349            p_vout->p_sys->xvmc_crop_style = 2;
350         else if( strncmp( psz_value, "16-4", 4 ) == 0)
351            p_vout->p_sys->xvmc_crop_style = 3;
352         else
353            p_vout->p_sys->xvmc_crop_style = 0;
354         free( psz_value );
355     }
356     else
357         p_vout->p_sys->xvmc_crop_style = 0;
358
359     msg_Dbg(p_vout, "Deinterlace = %d", p_vout->p_sys->xvmc_deinterlace_method);
360     msg_Dbg(p_vout, "Crop = %d", p_vout->p_sys->xvmc_crop_style);
361
362     if( !checkXvMCCap( p_vout ) )
363     {
364         msg_Err( p_vout, "no XVMC capability found" );
365         E_(Deactivate)( p_vout );
366         return VLC_EGENERIC;
367     }
368     sub_pic.p_sys = NULL;
369     p_vout->p_sys->last_date = 0;
370 #endif
371
372     /* Variable to indicate if the window should be on top of others */
373     /* Trigger a callback right now */
374     var_Get( p_vout, "video-on-top", &val );
375     var_Set( p_vout, "video-on-top", val );
376
377     return VLC_SUCCESS;
378 }
379
380 /*****************************************************************************
381  * Deactivate: destroy X11 video thread output method
382  *****************************************************************************
383  * Terminate an output method created by Open
384  *****************************************************************************/
385 void E_(Deactivate) ( vlc_object_t *p_this )
386 {
387     vout_thread_t *p_vout = (vout_thread_t *)p_this;
388
389     /* If the fullscreen window is still open, close it */
390     if( p_vout->b_fullscreen )
391     {
392         ToggleFullScreen( p_vout );
393     }
394
395     /* Restore cursor if it was blanked */
396     if( !p_vout->p_sys->b_mouse_pointer_visible )
397     {
398         ToggleCursor( p_vout );
399     }
400
401 #ifdef MODULE_NAME_IS_x11
402     /* Destroy colormap */
403     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
404     {
405         XFreeColormap( p_vout->p_sys->p_display, p_vout->p_sys->colormap );
406     }
407 #elif defined(MODULE_NAME_IS_xvideo)
408     XVideoReleasePort( p_vout, p_vout->p_sys->i_xvport );
409 #elif defined(MODULE_NAME_IS_xvmc)
410     if( p_vout->p_sys->xvmc_cap )
411     {
412         xvmc_context_writer_lock( &p_vout->p_sys->xvmc_lock );
413         xxmc_dispose_context( p_vout );
414         if( p_vout->p_sys->old_subpic )
415         {
416             xxmc_xvmc_free_subpicture( p_vout, p_vout->p_sys->old_subpic );
417             p_vout->p_sys->old_subpic = NULL;
418         }
419         if( p_vout->p_sys->new_subpic )
420         {
421             xxmc_xvmc_free_subpicture( p_vout, p_vout->p_sys->new_subpic );
422             p_vout->p_sys->new_subpic = NULL;
423         }
424         free( p_vout->p_sys->xvmc_cap );
425         xvmc_context_writer_unlock( &p_vout->p_sys->xvmc_lock );
426     }
427 #endif
428
429     DestroyCursor( p_vout );
430     EnableXScreenSaver( p_vout );
431     DestroyWindow( p_vout, &p_vout->p_sys->original_window );
432     XCloseDisplay( p_vout->p_sys->p_display );
433
434     /* Destroy structure */
435     vlc_mutex_destroy( &p_vout->p_sys->lock );
436 #ifdef MODULE_NAME_IS_xvmc
437     free_context_lock( &p_vout->p_sys->xvmc_lock );
438 #endif
439
440     free( p_vout->p_sys );
441 }
442
443 #ifdef MODULE_NAME_IS_xvmc
444
445 #define XINE_IMGFMT_YV12 (('2'<<24)|('1'<<16)|('V'<<8)|'Y')
446
447 /* called xlocked */
448 static int xvmc_check_yv12( Display *display, XvPortID port )
449 {
450     XvImageFormatValues *formatValues;
451     int                  formats;
452     int                  i;
453
454     formatValues = XvListImageFormats( display, port, &formats );
455
456     for( i = 0; i < formats; i++ )
457     {
458         if( ( formatValues[i].id == XINE_IMGFMT_YV12 ) &&
459             ( !( strncmp( formatValues[i].guid, "YV12", 4 ) ) ) )
460         {
461             XFree (formatValues);
462             return 0;
463         }
464     }
465
466     XFree (formatValues);
467     return 1;
468 }
469
470 static void xvmc_sync_surface( vout_thread_t *p_vout, XvMCSurface * srf )
471 {
472     XvMCSyncSurface( p_vout->p_sys->p_display, srf );
473 }
474
475 static void xvmc_update_XV_DOUBLE_BUFFER( vout_thread_t *p_vout )
476 {
477     Atom         atom;
478     int          xv_double_buffer;
479
480     xv_double_buffer = 1;
481
482     XLockDisplay( p_vout->p_sys->p_display );
483     atom = XInternAtom( p_vout->p_sys->p_display, "XV_DOUBLE_BUFFER", False );
484 #if 0
485     XvSetPortAttribute (p_vout->p_sys->p_display, p_vout->p_sys->i_xvport, atom, xv_double_buffer);
486 #endif
487     XvMCSetAttribute( p_vout->p_sys->p_display, &p_vout->p_sys->context, atom, xv_double_buffer );
488     XUnlockDisplay( p_vout->p_sys->p_display );
489
490     //xprintf(this->xine, XINE_VERBOSITY_DEBUG,
491     //    "video_out_xxmc: double buffering mode = %d\n", xv_double_buffer);
492 }
493
494 static void RenderVideo( vout_thread_t *p_vout, picture_t *p_pic )
495 {
496     vlc_xxmc_t *xxmc = NULL;
497
498     vlc_mutex_lock( &p_vout->p_sys->lock );
499     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
500
501     xxmc = &p_pic->p_sys->xxmc_data;
502     if( (!xxmc->decoded ||
503         !xxmc_xvmc_surface_valid( p_vout, p_pic->p_sys->xvmc_surf )) )
504     {
505         vlc_mutex_unlock( &p_vout->p_sys->lock );
506         xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
507         return;
508     }
509
510     vlc_mutex_lock( &p_vout->lastsubtitle_lock );
511
512     if (p_vout->p_last_subtitle != NULL)
513     {
514         if( p_vout->p_sys->p_last_subtitle_save != p_vout->p_last_subtitle )
515         {
516             p_vout->p_sys->new_subpic =
517                 xxmc_xvmc_alloc_subpicture( p_vout, &p_vout->p_sys->context,
518                     p_vout->p_sys->xvmc_width,
519                     p_vout->p_sys->xvmc_height,
520                     p_vout->p_sys->xvmc_cap[p_vout->p_sys->xvmc_cur_cap].subPicType.id );
521
522             if (p_vout->p_sys->new_subpic)
523             {
524                 XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
525                 XvMCClearSubpicture( p_vout->p_sys->p_display,
526                         p_vout->p_sys->new_subpic,
527                         0,
528                         0,
529                         p_vout->p_sys->xvmc_width,
530                         p_vout->p_sys->xvmc_height,
531                         0x00 );
532                 XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
533                 clear_xx44_palette( &p_vout->p_sys->palette );
534
535                 if( sub_pic.p_sys == NULL )
536                 {
537                     sub_pic.p_sys = malloc( sizeof( picture_sys_t ) );
538                     if( sub_pic.p_sys != NULL )
539                     {
540                         sub_pic.p_sys->p_vout = p_vout;
541                         sub_pic.p_sys->xvmc_surf = NULL;
542                         sub_pic.p_sys->p_image = p_vout->p_sys->subImage;
543                     }
544                 }
545                 sub_pic.p_sys->p_image = p_vout->p_sys->subImage;
546                 sub_pic.p->p_pixels = sub_pic.p_sys->p_image->data;
547                 sub_pic.p->i_pitch = p_vout->output.i_width;
548
549                 memset( p_vout->p_sys->subImage->data, 0,
550                         (p_vout->p_sys->subImage->width * p_vout->p_sys->subImage->height) );
551
552                 if (p_vout->p_last_subtitle != NULL)
553                 {
554                     blend_xx44( p_vout->p_sys->subImage->data,
555                                 p_vout->p_last_subtitle,
556                                 p_vout->p_sys->subImage->width,
557                                 p_vout->p_sys->subImage->height,
558                                 p_vout->p_sys->subImage->width,
559                                 &p_vout->p_sys->palette,
560                                 (p_vout->p_sys->subImage->id == FOURCC_IA44) );
561                 }
562
563                 XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
564                 XvMCCompositeSubpicture( p_vout->p_sys->p_display,
565                                          p_vout->p_sys->new_subpic,
566                                          p_vout->p_sys->subImage,
567                                          0, /* overlay->x */
568                                          0, /* overlay->y */
569                                          p_vout->output.i_width, /* overlay->width, */
570                                          p_vout->output.i_height, /* overlay->height */
571                                          0, /* overlay->x */
572                                          0 ); /*overlay->y */
573                 XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
574                 if (p_vout->p_sys->old_subpic)
575                 {
576                     xxmc_xvmc_free_subpicture( p_vout,
577                                                p_vout->p_sys->old_subpic);
578                     p_vout->p_sys->old_subpic = NULL;
579                 }
580                 if (p_vout->p_sys->new_subpic)
581                 {
582                     p_vout->p_sys->old_subpic = p_vout->p_sys->new_subpic;
583                     p_vout->p_sys->new_subpic = NULL;
584                     xx44_to_xvmc_palette( &p_vout->p_sys->palette,
585                             p_vout->p_sys->xvmc_palette,
586                             0,
587                             p_vout->p_sys->old_subpic->num_palette_entries,
588                             p_vout->p_sys->old_subpic->entry_bytes,
589                             p_vout->p_sys->old_subpic->component_order );
590                     XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
591                     XvMCSetSubpicturePalette( p_vout->p_sys->p_display,
592                                               p_vout->p_sys->old_subpic,
593                                               p_vout->p_sys->xvmc_palette );
594                     XvMCFlushSubpicture( p_vout->p_sys->p_display,
595                                          p_vout->p_sys->old_subpic);
596                     XvMCSyncSubpicture( p_vout->p_sys->p_display,
597                                         p_vout->p_sys->old_subpic );
598                     XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
599                 }
600
601                 XVMCLOCKDISPLAY( p_vout->p_sys->p_display);
602                 if (p_vout->p_sys->xvmc_backend_subpic )
603                 {
604                     XvMCBlendSubpicture( p_vout->p_sys->p_display,
605                                          p_pic->p_sys->xvmc_surf,
606                                          p_vout->p_sys->old_subpic,
607                                          0,
608                                          0,
609                                          p_vout->p_sys->xvmc_width,
610                                          p_vout->p_sys->xvmc_height,
611                                          0,
612                                          0,
613                                          p_vout->p_sys->xvmc_width,
614                                          p_vout->p_sys->xvmc_height );
615                 }
616                 else
617                 {
618                     XvMCBlendSubpicture2( p_vout->p_sys->p_display,
619                                           p_pic->p_sys->xvmc_surf,
620                                           p_pic->p_sys->xvmc_surf,
621                                           p_vout->p_sys->old_subpic,
622                                           0,
623                                           0,
624                                           p_vout->p_sys->xvmc_width,
625                                           p_vout->p_sys->xvmc_height,
626                                           0,
627                                           0,
628                                           p_vout->p_sys->xvmc_width,
629                                           p_vout->p_sys->xvmc_height );
630                }
631                XVMCUNLOCKDISPLAY(p_vout->p_sys->p_display);
632             }
633         }
634         else
635         {
636             XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
637             if( p_vout->p_sys->xvmc_backend_subpic )
638             {
639                 XvMCBlendSubpicture( p_vout->p_sys->p_display,
640                                      p_pic->p_sys->xvmc_surf,
641                                      p_vout->p_sys->old_subpic,
642                                      0, 0,
643                                      p_vout->p_sys->xvmc_width,
644                                      p_vout->p_sys->xvmc_height,
645                                      0, 0,
646                                      p_vout->p_sys->xvmc_width,
647                                      p_vout->p_sys->xvmc_height );
648             }
649             else
650             {
651                 XvMCBlendSubpicture2( p_vout->p_sys->p_display,
652                                       p_pic->p_sys->xvmc_surf,
653                                       p_pic->p_sys->xvmc_surf,
654                                       p_vout->p_sys->old_subpic,
655                                       0, 0,
656                                       p_vout->p_sys->xvmc_width,
657                                       p_vout->p_sys->xvmc_height,
658                                       0, 0,
659                                       p_vout->p_sys->xvmc_width,
660                                       p_vout->p_sys->xvmc_height );
661             }
662             XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
663         }
664     }
665     p_vout->p_sys->p_last_subtitle_save = p_vout->p_last_subtitle;
666
667     vlc_mutex_unlock( &p_vout->lastsubtitle_lock );
668     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
669
670     vlc_mutex_unlock( &p_vout->p_sys->lock );
671 }
672 #endif
673
674 /*****************************************************************************
675  * InitVideo: initialize X11 video thread output method
676  *****************************************************************************
677  * This function create the XImages needed by the output thread. It is called
678  * at the beginning of the thread, but also each time the window is resized.
679  *****************************************************************************/
680 static int InitVideo( vout_thread_t *p_vout )
681 {
682     unsigned int i_index = 0;
683     picture_t *p_pic;
684
685     I_OUTPUTPICTURES = 0;
686
687 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
688     /* Initialize the output structure; we already found an XVideo port,
689      * and the corresponding chroma we will be using. Since we can
690      * arbitrary scale, stick to the coordinates and aspect. */
691     p_vout->output.i_width  = p_vout->render.i_width;
692     p_vout->output.i_height = p_vout->render.i_height;
693     p_vout->output.i_aspect = p_vout->render.i_aspect;
694
695     p_vout->fmt_out = p_vout->fmt_in;
696     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
697
698     switch( p_vout->output.i_chroma )
699     {
700         case VLC_FOURCC('R','V','1','6'):
701 #if defined( WORDS_BIGENDIAN )
702             p_vout->output.i_rmask = 0xf800;
703             p_vout->output.i_gmask = 0x07e0;
704             p_vout->output.i_bmask = 0x001f;
705 #else
706             p_vout->output.i_rmask = 0x001f;
707             p_vout->output.i_gmask = 0x07e0;
708             p_vout->output.i_bmask = 0xf800;
709 #endif
710             break;
711         case VLC_FOURCC('R','V','1','5'):
712 #if defined( WORDS_BIGENDIAN )
713             p_vout->output.i_rmask = 0x7c00;
714             p_vout->output.i_gmask = 0x03e0;
715             p_vout->output.i_bmask = 0x001f;
716 #else
717             p_vout->output.i_rmask = 0x001f;
718             p_vout->output.i_gmask = 0x03e0;
719             p_vout->output.i_bmask = 0x7c00;
720 #endif
721             break;
722     }
723
724 #elif defined(MODULE_NAME_IS_x11)
725     /* Initialize the output structure: RGB with square pixels, whatever
726      * the input format is, since it's the only format we know */
727     switch( p_vout->p_sys->i_screen_depth )
728     {
729         case 8: /* FIXME: set the palette */
730             p_vout->output.i_chroma = VLC_FOURCC('R','G','B','2'); break;
731         case 15:
732             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','5'); break;
733         case 16:
734             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','6'); break;
735         case 24:
736         case 32:
737             p_vout->output.i_chroma = VLC_FOURCC('R','V','3','2'); break;
738         default:
739             msg_Err( p_vout, "unknown screen depth %i",
740                      p_vout->p_sys->i_screen_depth );
741             return VLC_SUCCESS;
742     }
743
744     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
745                        p_vout->p_sys->p_win->i_height,
746                        &i_index, &i_index,
747                        &p_vout->fmt_out.i_visible_width,
748                        &p_vout->fmt_out.i_visible_height );
749
750     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
751
752     p_vout->output.i_width = p_vout->fmt_out.i_width =
753         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_width /
754         p_vout->fmt_in.i_visible_width;
755     p_vout->output.i_height = p_vout->fmt_out.i_height =
756         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_height /
757         p_vout->fmt_in.i_visible_height;
758     p_vout->fmt_out.i_x_offset =
759         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_x_offset /
760         p_vout->fmt_in.i_visible_width;
761     p_vout->fmt_out.i_y_offset =
762         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_y_offset /
763         p_vout->fmt_in.i_visible_height;
764
765     p_vout->fmt_out.i_sar_num = p_vout->fmt_out.i_sar_den = 1;
766     p_vout->output.i_aspect = p_vout->fmt_out.i_aspect =
767         p_vout->fmt_out.i_width * VOUT_ASPECT_FACTOR /p_vout->fmt_out.i_height;
768
769     msg_Dbg( p_vout, "x11 image size %ix%i (%i,%i,%ix%i)",
770              p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
771              p_vout->fmt_out.i_x_offset, p_vout->fmt_out.i_y_offset,
772              p_vout->fmt_out.i_visible_width,
773              p_vout->fmt_out.i_visible_height );
774 #endif
775
776     /* Try to initialize up to MAX_DIRECTBUFFERS direct buffers */
777     while( I_OUTPUTPICTURES < MAX_DIRECTBUFFERS )
778     {
779         p_pic = NULL;
780
781         /* Find an empty picture slot */
782         for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
783         {
784           if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
785             {
786                 p_pic = p_vout->p_picture + i_index;
787                 break;
788             }
789         }
790
791         /* Allocate the picture */
792         if( p_pic == NULL || NewPicture( p_vout, p_pic ) )
793         {
794             break;
795         }
796
797         p_pic->i_status = DESTROYED_PICTURE;
798         p_pic->i_type   = DIRECT_PICTURE;
799
800         PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
801
802         I_OUTPUTPICTURES++;
803     }
804
805     if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
806     {
807         /* U and V inverted compared to I420
808          * Fixme: this should be handled by the vout core */
809         p_vout->output.i_chroma = VLC_FOURCC('I','4','2','0');
810         p_vout->fmt_out.i_chroma = VLC_FOURCC('I','4','2','0');
811     }
812
813     return VLC_SUCCESS;
814 }
815
816 /*****************************************************************************
817  * DisplayVideo: displays previously rendered output
818  *****************************************************************************
819  * This function sends the currently rendered image to X11 server.
820  * (The Xv extension takes care of "double-buffering".)
821  *****************************************************************************/
822 static void DisplayVideo( vout_thread_t *p_vout, picture_t *p_pic )
823 {
824     unsigned int i_width, i_height, i_x, i_y;
825
826     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
827                        p_vout->p_sys->p_win->i_height,
828                        &i_x, &i_y, &i_width, &i_height );
829
830     vlc_mutex_lock( &p_vout->p_sys->lock );
831
832 #ifdef MODULE_NAME_IS_xvmc
833     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
834
835     vlc_xxmc_t *xxmc = &p_picture->p_sys->xxmc_data;
836     if( !xxmc->decoded ||
837         !xxmc_xvmc_surface_valid( p_vout, p_picture->p_sys->xvmc_surf ) )
838     {
839       msg_Dbg( p_vout, "DisplayVideo decoded=%d\tsurfacevalid=%d",
840                xxmc->decoded,
841                xxmc_xvmc_surface_valid( p_vout, p_picture->p_sys->xvmc_surf ) );
842       vlc_mutex_unlock( &p_vout->p_sys->lock );
843       xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
844       return;
845     }
846
847     src_width = p_vout->output.i_width;
848     src_height = p_vout->output.i_height;
849
850     if( p_vout->p_sys->xvmc_crop_style == 1 )
851     {
852         src_x = 20;
853         src_y = 20;
854         src_width -= 40;
855         src_height -= 40;
856     }
857     else if( p_vout->p_sys->xvmc_crop_style == 2 )
858     {
859         src_x = 20;
860         src_y = 40;
861         src_width -= 40;
862         src_height -= 80;
863     }
864     else if( p_vout->p_sys->xvmc_crop_style == 3 )
865     {
866         src_x = 40;
867         src_y = 20;
868         src_width -= 80;
869         src_height -= 40;
870     }
871     else
872     {
873         src_x = 0;
874         src_y = 0;
875     }
876
877     if( p_vout->p_sys->xvmc_deinterlace_method > 0 )
878     {   /* BOB DEINTERLACE */
879         if( (p_picture->p_sys->nb_display == 0) ||
880             (p_vout->p_sys->xvmc_deinterlace_method == 1) )
881         {
882             first_field = (p_picture->b_top_field_first) ?
883                                 XVMC_BOTTOM_FIELD : XVMC_TOP_FIELD;
884         }
885         else
886         {
887             first_field = (p_picture->b_top_field_first) ?
888                                 XVMC_TOP_FIELD : XVMC_BOTTOM_FIELD;
889         }
890     }
891     else
892     {
893         first_field = XVMC_FRAME_PICTURE;
894      }
895
896     XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
897     XvMCFlushSurface( p_vout->p_sys->p_display, p_picture->p_sys->xvmc_surf );
898     /* XvMCSyncSurface(p_vout->p_sys->p_display, p_picture->p_sys->xvmc_surf); */
899     XvMCPutSurface( p_vout->p_sys->p_display,
900                     p_picture->p_sys->xvmc_surf,
901                     p_vout->p_sys->p_win->video_window,
902                     src_x,
903                     src_y,
904                     src_width,
905                     src_height,
906                     0 /*dest_x*/,
907                     0 /*dest_y*/,
908                     i_width,
909                     i_height,
910                     first_field);
911
912     XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
913     if( p_vout->p_sys->xvmc_deinterlace_method == 2 ) 
914     {   /* BOB DEINTERLACE */
915         if( p_picture->p_sys->nb_display == 0 )/* && ((t2-t1) < 15000)) */
916         {
917             mtime_t last_date = p_picture->date;
918
919             vlc_mutex_lock( &p_vout->picture_lock );
920             if( !p_vout->p_sys->last_date )
921             {
922                 p_picture->date += 20000;
923             }
924             else
925             {
926                 p_picture->date = ((3 * p_picture->date -
927                                     p_vout->p_sys->last_date) / 2 );
928             }
929             p_vout->p_sys->last_date = last_date;
930             p_picture->b_force = 1;
931             p_picture->p_sys->nb_display = 1;
932             vlc_mutex_unlock( &p_vout->picture_lock );
933         }
934         else
935         {
936             p_picture->p_sys->nb_display = 0;
937             p_picture->b_force = 0;
938         }
939     }
940     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
941 #endif
942
943 #ifdef HAVE_SYS_SHM_H
944     if( p_vout->p_sys->b_shm )
945     {
946         /* Display rendered image using shared memory extension */
947 #   if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
948         XvShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
949                        p_vout->p_sys->p_win->video_window,
950                        p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
951                        p_vout->fmt_out.i_x_offset,
952                        p_vout->fmt_out.i_y_offset,
953                        p_vout->fmt_out.i_visible_width,
954                        p_vout->fmt_out.i_visible_height,
955                        0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height,
956                        False /* Don't put True here or you'll waste your CPU */ );
957 #   else
958         XShmPutImage( p_vout->p_sys->p_display,
959                       p_vout->p_sys->p_win->video_window,
960                       p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
961                       p_vout->fmt_out.i_x_offset,
962                       p_vout->fmt_out.i_y_offset,
963                       0 /*dest_x*/, 0 /*dest_y*/,
964                       p_vout->fmt_out.i_visible_width,
965                       p_vout->fmt_out.i_visible_height,
966                       False /* Don't put True here ! */ );
967 #   endif
968     }
969     else
970 #endif /* HAVE_SYS_SHM_H */
971     {
972         /* Use standard XPutImage -- this is gonna be slow ! */
973 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
974         XvPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
975                     p_vout->p_sys->p_win->video_window,
976                     p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
977                     p_vout->fmt_out.i_x_offset,
978                     p_vout->fmt_out.i_y_offset,
979                     p_vout->fmt_out.i_visible_width,
980                     p_vout->fmt_out.i_visible_height,
981                     0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height );
982 #else
983         XPutImage( p_vout->p_sys->p_display,
984                    p_vout->p_sys->p_win->video_window,
985                    p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
986                    p_vout->fmt_out.i_x_offset,
987                    p_vout->fmt_out.i_y_offset,
988                    0 /*dest_x*/, 0 /*dest_y*/,
989                    p_vout->fmt_out.i_visible_width,
990                    p_vout->fmt_out.i_visible_height );
991 #endif
992     }
993
994     /* Make sure the command is sent now - do NOT use XFlush !*/
995     XSync( p_vout->p_sys->p_display, False );
996
997     vlc_mutex_unlock( &p_vout->p_sys->lock );
998 }
999
1000 /*****************************************************************************
1001  * ManageVideo: handle X11 events
1002  *****************************************************************************
1003  * This function should be called regularly by video output thread. It manages
1004  * X11 events and allows window resizing. It returns a non null value on
1005  * error.
1006  *****************************************************************************/
1007 static int ManageVideo( vout_thread_t *p_vout )
1008 {
1009     XEvent      xevent;                                         /* X11 event */
1010     vlc_value_t val;
1011
1012     vlc_mutex_lock( &p_vout->p_sys->lock );
1013
1014 #ifdef MODULE_NAME_IS_xvmc
1015     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
1016 #endif
1017
1018     /* Handle events from the owner window */
1019     if( p_vout->p_sys->p_win->owner_window )
1020     {
1021         while( XCheckWindowEvent( p_vout->p_sys->p_display,
1022                                   p_vout->p_sys->p_win->owner_window,
1023                                   StructureNotifyMask, &xevent ) == True )
1024         {
1025             /* ConfigureNotify event: prepare  */
1026             if( xevent.type == ConfigureNotify )
1027             {
1028                 /* Update dimensions */
1029                 XResizeWindow( p_vout->p_sys->p_display,
1030                                p_vout->p_sys->p_win->base_window,
1031                                xevent.xconfigure.width,
1032                                xevent.xconfigure.height );
1033             }
1034         }
1035     }
1036
1037     /* Handle X11 events: ConfigureNotify events are parsed to know if the
1038      * output window's size changed, MapNotify and UnmapNotify to know if the
1039      * window is mapped (and if the display is useful), and ClientMessages
1040      * to intercept window destruction requests */
1041
1042     while( XCheckWindowEvent( p_vout->p_sys->p_display,
1043                               p_vout->p_sys->p_win->base_window,
1044                               StructureNotifyMask | KeyPressMask |
1045                               ButtonPressMask | ButtonReleaseMask |
1046                               PointerMotionMask | Button1MotionMask , &xevent )
1047            == True )
1048     {
1049         /* ConfigureNotify event: prepare  */
1050         if( xevent.type == ConfigureNotify )
1051         {
1052             if( (unsigned int)xevent.xconfigure.width
1053                    != p_vout->p_sys->p_win->i_width
1054               || (unsigned int)xevent.xconfigure.height
1055                     != p_vout->p_sys->p_win->i_height )
1056             {
1057                 /* Update dimensions */
1058                 p_vout->i_changes |= VOUT_SIZE_CHANGE;
1059                 p_vout->p_sys->p_win->i_width = xevent.xconfigure.width;
1060                 p_vout->p_sys->p_win->i_height = xevent.xconfigure.height;
1061             }
1062         }
1063         /* Keyboard event */
1064         else if( xevent.type == KeyPress )
1065         {
1066             unsigned int state = xevent.xkey.state;
1067             KeySym x_key_symbol;
1068             char i_key;                                   /* ISO Latin-1 key */
1069
1070             /* We may have keys like F1 trough F12, ESC ... */
1071             x_key_symbol = XKeycodeToKeysym( p_vout->p_sys->p_display,
1072                                              xevent.xkey.keycode, 0 );
1073             val.i_int = ConvertKey( (int)x_key_symbol );
1074
1075             xevent.xkey.state &= ~ShiftMask;
1076             xevent.xkey.state &= ~ControlMask;
1077             xevent.xkey.state &= ~Mod1Mask;
1078
1079             if( !val.i_int &&
1080                 XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
1081             {
1082                 /* "Normal Keys"
1083                  * The reason why I use this instead of XK_0 is that
1084                  * with XLookupString, we don't have to care about
1085                  * keymaps. */
1086                 val.i_int = i_key;
1087             }
1088
1089             if( val.i_int )
1090             {
1091                 if( state & ShiftMask )
1092                 {
1093                     val.i_int |= KEY_MODIFIER_SHIFT;
1094                 }
1095                 if( state & ControlMask )
1096                 {
1097                     val.i_int |= KEY_MODIFIER_CTRL;
1098                 }
1099                 if( state & Mod1Mask )
1100                 {
1101                     val.i_int |= KEY_MODIFIER_ALT;
1102                 }
1103                 var_Set( p_vout->p_libvlc, "key-pressed", val );
1104             }
1105         }
1106         /* Mouse click */
1107         else if( xevent.type == ButtonPress )
1108         {
1109             switch( ((XButtonEvent *)&xevent)->button )
1110             {
1111                 case Button1:
1112                     var_Get( p_vout, "mouse-button-down", &val );
1113                     val.i_int |= 1;
1114                     var_Set( p_vout, "mouse-button-down", val );
1115
1116                     /* detect double-clicks */
1117                     if( ( ((XButtonEvent *)&xevent)->time -
1118                           p_vout->p_sys->i_time_button_last_pressed ) < 300 )
1119                     {
1120                         p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
1121                     }
1122
1123                     p_vout->p_sys->i_time_button_last_pressed =
1124                         ((XButtonEvent *)&xevent)->time;
1125                     break;
1126                 case Button2:
1127                     var_Get( p_vout, "mouse-button-down", &val );
1128                     val.i_int |= 2;
1129                     var_Set( p_vout, "mouse-button-down", val );
1130                     break;
1131
1132                 case Button3:
1133                     var_Get( p_vout, "mouse-button-down", &val );
1134                     val.i_int |= 4;
1135                     var_Set( p_vout, "mouse-button-down", val );
1136                     break;
1137
1138                 case Button4:
1139                     var_Get( p_vout, "mouse-button-down", &val );
1140                     val.i_int |= 8;
1141                     var_Set( p_vout, "mouse-button-down", val );
1142                     break;
1143
1144                 case Button5:
1145                     var_Get( p_vout, "mouse-button-down", &val );
1146                     val.i_int |= 16;
1147                     var_Set( p_vout, "mouse-button-down", val );
1148                     break;
1149             }
1150         }
1151         /* Mouse release */
1152         else if( xevent.type == ButtonRelease )
1153         {
1154             switch( ((XButtonEvent *)&xevent)->button )
1155             {
1156                 case Button1:
1157                     var_Get( p_vout, "mouse-button-down", &val );
1158                     val.i_int &= ~1;
1159                     var_Set( p_vout, "mouse-button-down", val );
1160
1161                     val.b_bool = VLC_TRUE;
1162                     var_Set( p_vout, "mouse-clicked", val );
1163                     break;
1164
1165                 case Button2:
1166                     {
1167                         playlist_t *p_playlist;
1168
1169                         var_Get( p_vout, "mouse-button-down", &val );
1170                         val.i_int &= ~2;
1171                         var_Set( p_vout, "mouse-button-down", val );
1172
1173                         p_playlist = vlc_object_find( p_vout,
1174                                                       VLC_OBJECT_PLAYLIST,
1175                                                       FIND_ANYWHERE );
1176                         if( p_playlist != NULL )
1177                         {
1178                             vlc_value_t val;
1179                             var_Get( p_playlist, "intf-show", &val );
1180                             val.b_bool = !val.b_bool;
1181                             var_Set( p_playlist, "intf-show", val );
1182                             vlc_object_release( p_playlist );
1183                         }
1184                     }
1185                     break;
1186
1187                 case Button3:
1188                     {
1189                         intf_thread_t *p_intf;
1190                         playlist_t *p_playlist;
1191
1192                         var_Get( p_vout, "mouse-button-down", &val );
1193                         val.i_int &= ~4;
1194                         var_Set( p_vout, "mouse-button-down", val );
1195                         p_intf = vlc_object_find( p_vout, VLC_OBJECT_INTF,
1196                                                           FIND_ANYWHERE );
1197                         if( p_intf )
1198                         {
1199                             p_intf->b_menu_change = 1;
1200                             vlc_object_release( p_intf );
1201                         }
1202
1203                         p_playlist = vlc_object_find( p_vout,
1204                                                       VLC_OBJECT_PLAYLIST,
1205                                                       FIND_ANYWHERE );
1206                         if( p_playlist != NULL )
1207                         {
1208                             vlc_value_t val; val.b_bool = VLC_TRUE;
1209                             var_Set( p_playlist, "intf-popupmenu", val );
1210                             vlc_object_release( p_playlist );
1211                         }
1212                     }
1213                     break;
1214
1215                 case Button4:
1216                     var_Get( p_vout, "mouse-button-down", &val );
1217                     val.i_int &= ~8;
1218                     var_Set( p_vout, "mouse-button-down", val );
1219                     break;
1220
1221                 case Button5:
1222                     var_Get( p_vout, "mouse-button-down", &val );
1223                     val.i_int &= ~16;
1224                     var_Set( p_vout, "mouse-button-down", val );
1225                     break;
1226
1227             }
1228         }
1229         /* Mouse move */
1230         else if( xevent.type == MotionNotify )
1231         {
1232             unsigned int i_width, i_height, i_x, i_y;
1233             vlc_value_t val;
1234
1235             /* somewhat different use for vout_PlacePicture:
1236              * here the values are needed to give to mouse coordinates
1237              * in the original picture space */
1238             vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
1239                                p_vout->p_sys->p_win->i_height,
1240                                &i_x, &i_y, &i_width, &i_height );
1241
1242             val.i_int = ( xevent.xmotion.x - i_x ) *
1243                 p_vout->fmt_in.i_visible_width / i_width +
1244                 p_vout->fmt_in.i_x_offset;
1245             var_Set( p_vout, "mouse-x", val );
1246             val.i_int = ( xevent.xmotion.y - i_y ) *
1247                 p_vout->fmt_in.i_visible_height / i_height +
1248                 p_vout->fmt_in.i_y_offset;
1249             var_Set( p_vout, "mouse-y", val );
1250
1251             val.b_bool = VLC_TRUE;
1252             var_Set( p_vout, "mouse-moved", val );
1253
1254             p_vout->p_sys->i_time_mouse_last_moved = mdate();
1255             if( ! p_vout->p_sys->b_mouse_pointer_visible )
1256             {
1257                 ToggleCursor( p_vout );
1258             }
1259         }
1260         else if( xevent.type == ReparentNotify /* XXX: why do we get this? */
1261                   || xevent.type == MapNotify
1262                   || xevent.type == UnmapNotify )
1263         {
1264             /* Ignore these events */
1265         }
1266         else /* Other events */
1267         {
1268             msg_Warn( p_vout, "unhandled event %d received", xevent.type );
1269         }
1270     }
1271
1272     /* Handle events for video output sub-window */
1273     while( XCheckWindowEvent( p_vout->p_sys->p_display,
1274                               p_vout->p_sys->p_win->video_window,
1275                               ExposureMask, &xevent ) == True )
1276     {
1277         /* Window exposed (only handled if stream playback is paused) */
1278         if( xevent.type == Expose )
1279         {
1280             if( ((XExposeEvent *)&xevent)->count == 0 )
1281             {
1282                 /* (if this is the last a collection of expose events...) */
1283 #if 0
1284                 if( p_vout->p_libvlc->p_input_bank->pp_input[0] != NULL )
1285                 {
1286                     if( PAUSE_S == p_vout->p_libvlc->p_input_bank->pp_input[0]
1287                                                    ->stream.control.i_status )
1288                     {
1289                         /* XVideoDisplay( p_vout )*/;
1290                     }
1291                 }
1292 #endif
1293             }
1294         }
1295     }
1296
1297     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
1298      * are handled - according to the man pages, the format is always 32
1299      * in this case */
1300     while( XCheckTypedEvent( p_vout->p_sys->p_display,
1301                              ClientMessage, &xevent ) )
1302     {
1303         if( (xevent.xclient.message_type == p_vout->p_sys->p_win->wm_protocols)
1304                && ((Atom)xevent.xclient.data.l[0]
1305                      == p_vout->p_sys->p_win->wm_delete_window ) )
1306         {
1307             /* the user wants to close the window */
1308             playlist_t * p_playlist =
1309                 (playlist_t *)vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
1310                                                FIND_ANYWHERE );
1311             if( p_playlist != NULL )
1312             {
1313                 playlist_Stop( p_playlist );
1314                 vlc_object_release( p_playlist );
1315             }
1316         }
1317     }
1318
1319     /*
1320      * Fullscreen Change
1321      */
1322     if ( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
1323     {
1324         vlc_value_t val;
1325
1326         /* Update the object variable and trigger callback */
1327         val.b_bool = !p_vout->b_fullscreen;
1328         var_Set( p_vout, "fullscreen", val );
1329
1330         ToggleFullScreen( p_vout );
1331         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
1332     }
1333
1334     if( p_vout->i_changes & VOUT_CROP_CHANGE ||
1335         p_vout->i_changes & VOUT_ASPECT_CHANGE )
1336     {
1337         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
1338         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
1339
1340         p_vout->fmt_out.i_x_offset = p_vout->fmt_in.i_x_offset;
1341         p_vout->fmt_out.i_y_offset = p_vout->fmt_in.i_y_offset;
1342         p_vout->fmt_out.i_visible_width = p_vout->fmt_in.i_visible_width;
1343         p_vout->fmt_out.i_visible_height = p_vout->fmt_in.i_visible_height;
1344         p_vout->fmt_out.i_aspect = p_vout->fmt_in.i_aspect;
1345         p_vout->fmt_out.i_sar_num = p_vout->fmt_in.i_sar_num;
1346         p_vout->fmt_out.i_sar_den = p_vout->fmt_in.i_sar_den;
1347         p_vout->output.i_aspect = p_vout->fmt_in.i_aspect;
1348
1349         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1350     }
1351
1352     /*
1353      * Size change
1354      *
1355      * (Needs to be placed after VOUT_FULLSREEN_CHANGE because we can activate
1356      *  the size flag inside the fullscreen routine)
1357      */
1358     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
1359     {
1360         unsigned int i_width, i_height, i_x, i_y;
1361
1362         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
1363
1364 #ifdef MODULE_NAME_IS_x11
1365         /* We need to signal the vout thread about the size change because it
1366          * is doing the rescaling */
1367         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1368 #endif
1369
1370         vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
1371                            p_vout->p_sys->p_win->i_height,
1372                            &i_x, &i_y, &i_width, &i_height );
1373
1374         XMoveResizeWindow( p_vout->p_sys->p_display,
1375                            p_vout->p_sys->p_win->video_window,
1376                            i_x, i_y, i_width, i_height );
1377     }
1378
1379     /* Autohide Cursour */
1380     if( mdate() - p_vout->p_sys->i_time_mouse_last_moved > 2000000 )
1381     {
1382         /* Hide the mouse automatically */
1383         if( p_vout->p_sys->b_mouse_pointer_visible )
1384         {
1385             ToggleCursor( p_vout );
1386         }
1387     }
1388
1389 #ifdef MODULE_NAME_IS_xvmc
1390     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1391 #endif
1392
1393     vlc_mutex_unlock( &p_vout->p_sys->lock );
1394     return 0;
1395 }
1396
1397 /*****************************************************************************
1398  * EndVideo: terminate X11 video thread output method
1399  *****************************************************************************
1400  * Destroy the X11 XImages created by Init. It is called at the end of
1401  * the thread, but also each time the window is resized.
1402  *****************************************************************************/
1403 static void EndVideo( vout_thread_t *p_vout )
1404 {
1405     int i_index;
1406
1407     /* Free the direct buffers we allocated */
1408     for( i_index = I_OUTPUTPICTURES ; i_index ; )
1409     {
1410         i_index--;
1411         FreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
1412     }
1413 }
1414
1415 /* following functions are local */
1416
1417 /*****************************************************************************
1418  * CreateWindow: open and set-up X11 main window
1419  *****************************************************************************/
1420 static int CreateWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1421 {
1422     XSizeHints              xsize_hints;
1423     XSetWindowAttributes    xwindow_attributes;
1424     XGCValues               xgcvalues;
1425     XEvent                  xevent;
1426
1427     vlc_bool_t              b_expose = VLC_FALSE;
1428     vlc_bool_t              b_configure_notify = VLC_FALSE;
1429     vlc_bool_t              b_map_notify = VLC_FALSE;
1430     vlc_value_t             val;
1431
1432     /* Prepare window manager hints and properties */
1433     p_win->wm_protocols =
1434              XInternAtom( p_vout->p_sys->p_display, "WM_PROTOCOLS", True );
1435     p_win->wm_delete_window =
1436              XInternAtom( p_vout->p_sys->p_display, "WM_DELETE_WINDOW", True );
1437
1438     /* Never have a 0-pixel-wide window */
1439     xsize_hints.min_width = 2;
1440     xsize_hints.min_height = 1;
1441
1442     /* Prepare window attributes */
1443     xwindow_attributes.backing_store = Always;       /* save the hidden part */
1444     xwindow_attributes.background_pixel = BlackPixel(p_vout->p_sys->p_display,
1445                                                      p_vout->p_sys->i_screen);
1446     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
1447
1448     if( !p_vout->b_fullscreen )
1449     {
1450         p_win->owner_window =
1451             (Window)vout_RequestWindow( p_vout, &p_win->i_x, &p_win->i_y,
1452                                         &p_win->i_width, &p_win->i_height );
1453
1454         xsize_hints.base_width  = xsize_hints.width = p_win->i_width;
1455         xsize_hints.base_height = xsize_hints.height = p_win->i_height;
1456         xsize_hints.flags       = PSize | PMinSize;
1457
1458         if( p_win->i_x >=0 || p_win->i_y >= 0 )
1459         {
1460             xsize_hints.x = p_win->i_x;
1461             xsize_hints.y = p_win->i_y;
1462             xsize_hints.flags |= PPosition;
1463         }
1464     }
1465     else
1466     {
1467         /* Fullscreen window size and position */
1468         p_win->owner_window = 0;
1469         p_win->i_x = p_win->i_y = 0;
1470         p_win->i_width =
1471             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1472         p_win->i_height =
1473             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1474     }
1475
1476     if( !p_win->owner_window )
1477     {
1478         /* Create the window and set hints - the window must receive
1479          * ConfigureNotify events, and until it is displayed, Expose and
1480          * MapNotify events. */
1481
1482         p_win->base_window =
1483             XCreateWindow( p_vout->p_sys->p_display,
1484                            DefaultRootWindow( p_vout->p_sys->p_display ),
1485                            p_win->i_x, p_win->i_y,
1486                            p_win->i_width, p_win->i_height,
1487                            0,
1488                            0, InputOutput, 0,
1489                            CWBackingStore | CWBackPixel | CWEventMask,
1490                            &xwindow_attributes );
1491
1492         if( !p_vout->b_fullscreen )
1493         {
1494             /* Set window manager hints and properties: size hints, command,
1495              * window's name, and accepted protocols */
1496             XSetWMNormalHints( p_vout->p_sys->p_display,
1497                                p_win->base_window, &xsize_hints );
1498             XSetCommand( p_vout->p_sys->p_display, p_win->base_window,
1499                          p_vout->p_libvlc->ppsz_argv, p_vout->p_libvlc->i_argc );
1500
1501             if( !var_GetBool( p_vout, "video-deco") )
1502             {
1503                 Atom prop;
1504                 mwmhints_t mwmhints;
1505
1506                 mwmhints.flags = MWM_HINTS_DECORATIONS;
1507                 mwmhints.decorations = False;
1508
1509                 prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1510                                     False );
1511
1512                 XChangeProperty( p_vout->p_sys->p_display,
1513                                  p_win->base_window,
1514                                  prop, prop, 32, PropModeReplace,
1515                                  (unsigned char *)&mwmhints,
1516                                  PROP_MWM_HINTS_ELEMENTS );
1517             }
1518             else
1519             {
1520                  var_Get( p_vout, "video-title", &val );
1521                  if( !val.psz_string || !*val.psz_string )
1522                  {
1523                     XStoreName( p_vout->p_sys->p_display, p_win->base_window,
1524 #ifdef MODULE_NAME_IS_x11
1525                                 VOUT_TITLE " (X11 output)"
1526 #elif defined(MODULE_NAME_IS_glx)
1527                                 VOUT_TITLE " (GLX output)"
1528 #else
1529                                 VOUT_TITLE " (XVideo output)"
1530 #endif
1531                       );
1532                 }
1533                 else
1534                 {
1535                     XStoreName( p_vout->p_sys->p_display,
1536                                p_win->base_window, val.psz_string );
1537                 }
1538                 if( val.psz_string ) free( val.psz_string );
1539             }
1540         }
1541     }
1542     else
1543     {
1544         Window dummy1;
1545         int dummy2, dummy3;
1546         unsigned int dummy4, dummy5;
1547
1548         /* Select events we are interested in. */
1549         XSelectInput( p_vout->p_sys->p_display, p_win->owner_window,
1550                       StructureNotifyMask );
1551
1552         /* Get the parent window's geometry information */
1553         XGetGeometry( p_vout->p_sys->p_display, p_win->owner_window,
1554                       &dummy1, &dummy2, &dummy3,
1555                       &p_win->i_width,
1556                       &p_win->i_height,
1557                       &dummy4, &dummy5 );
1558
1559         /* We are already configured */
1560         b_configure_notify = VLC_TRUE;
1561
1562         /* From man XSelectInput: only one client at a time can select a
1563          * ButtonPress event, so we need to open a new window anyway. */
1564         p_win->base_window =
1565             XCreateWindow( p_vout->p_sys->p_display,
1566                            p_win->owner_window,
1567                            0, 0,
1568                            p_win->i_width, p_win->i_height,
1569                            0,
1570                            0, CopyFromParent, 0,
1571                            CWBackingStore | CWBackPixel | CWEventMask,
1572                            &xwindow_attributes );
1573     }
1574
1575     if( (p_win->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1576         || (p_win->wm_delete_window == None)
1577         || !XSetWMProtocols( p_vout->p_sys->p_display, p_win->base_window,
1578                              &p_win->wm_delete_window, 1 ) )
1579     {
1580         /* WM_DELETE_WINDOW is not supported by window manager */
1581         msg_Warn( p_vout, "missing or bad window manager" );
1582     }
1583
1584     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1585      * event when using functions like XCopyArea */
1586     xgcvalues.graphics_exposures = False;
1587     p_win->gc = XCreateGC( p_vout->p_sys->p_display,
1588                            p_win->base_window,
1589                            GCGraphicsExposures, &xgcvalues );
1590
1591     /* Send orders to server, and wait until window is displayed - three
1592      * events must be received: a MapNotify event, an Expose event allowing
1593      * drawing in the window, and a ConfigureNotify to get the window
1594      * dimensions. Once those events have been received, only
1595      * ConfigureNotify events need to be received. */
1596     XMapWindow( p_vout->p_sys->p_display, p_win->base_window );
1597     do
1598     {
1599         XWindowEvent( p_vout->p_sys->p_display, p_win->base_window,
1600                       SubstructureNotifyMask | StructureNotifyMask |
1601                       ExposureMask, &xevent);
1602         if( (xevent.type == Expose)
1603             && (xevent.xexpose.window == p_win->base_window) )
1604         {
1605             b_expose = VLC_TRUE;
1606             /* ConfigureNotify isn't sent if there isn't a window manager.
1607              * Expose should be the last event to be received so it should
1608              * be fine to assume we won't receive it anymore. */
1609             b_configure_notify = VLC_TRUE;
1610         }
1611         else if( (xevent.type == MapNotify)
1612                  && (xevent.xmap.window == p_win->base_window) )
1613         {
1614             b_map_notify = VLC_TRUE;
1615         }
1616         else if( (xevent.type == ConfigureNotify)
1617                  && (xevent.xconfigure.window == p_win->base_window) )
1618         {
1619             b_configure_notify = VLC_TRUE;
1620             p_win->i_width = xevent.xconfigure.width;
1621             p_win->i_height = xevent.xconfigure.height;
1622         }
1623     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1624
1625     XSelectInput( p_vout->p_sys->p_display, p_win->base_window,
1626                   StructureNotifyMask | KeyPressMask |
1627                   ButtonPressMask | ButtonReleaseMask |
1628                   PointerMotionMask );
1629
1630 #ifdef MODULE_NAME_IS_x11
1631     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1632     {
1633         /* Allocate a new palette */
1634         p_vout->p_sys->colormap =
1635             XCreateColormap( p_vout->p_sys->p_display,
1636                              DefaultRootWindow( p_vout->p_sys->p_display ),
1637                              DefaultVisual( p_vout->p_sys->p_display,
1638                                             p_vout->p_sys->i_screen ),
1639                              AllocAll );
1640
1641         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1642         XChangeWindowAttributes( p_vout->p_sys->p_display, p_win->base_window,
1643                                  CWColormap, &xwindow_attributes );
1644     }
1645 #endif
1646
1647     /* Create video output sub-window. */
1648     p_win->video_window =  XCreateSimpleWindow(
1649                                       p_vout->p_sys->p_display,
1650                                       p_win->base_window, 0, 0,
1651                                       p_win->i_width, p_win->i_height,
1652                                       0,
1653                                       BlackPixel( p_vout->p_sys->p_display,
1654                                                   p_vout->p_sys->i_screen ),
1655                                       WhitePixel( p_vout->p_sys->p_display,
1656                                                   p_vout->p_sys->i_screen ) );
1657
1658     XSetWindowBackground( p_vout->p_sys->p_display, p_win->video_window,
1659                           BlackPixel( p_vout->p_sys->p_display,
1660                                       p_vout->p_sys->i_screen ) );
1661
1662     XMapWindow( p_vout->p_sys->p_display, p_win->video_window );
1663     XSelectInput( p_vout->p_sys->p_display, p_win->video_window,
1664                   ExposureMask );
1665
1666     /* make sure the video window will be centered in the next ManageVideo() */
1667     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1668
1669     /* If the cursor was formerly blank than blank it again */
1670     if( !p_vout->p_sys->b_mouse_pointer_visible )
1671     {
1672         ToggleCursor( p_vout );
1673         ToggleCursor( p_vout );
1674     }
1675
1676     /* Do NOT use XFlush here ! */
1677     XSync( p_vout->p_sys->p_display, False );
1678
1679     /* At this stage, the window is open, displayed, and ready to
1680      * receive data */
1681     p_vout->p_sys->p_win = p_win;
1682
1683     return VLC_SUCCESS;
1684 }
1685
1686 /*****************************************************************************
1687  * DestroyWindow: destroy the window
1688  *****************************************************************************
1689  *
1690  *****************************************************************************/
1691 static void DestroyWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1692 {
1693     /* Do NOT use XFlush here ! */
1694     XSync( p_vout->p_sys->p_display, False );
1695
1696     if( p_win->video_window != None )
1697         XDestroyWindow( p_vout->p_sys->p_display, p_win->video_window );
1698
1699     XFreeGC( p_vout->p_sys->p_display, p_win->gc );
1700
1701     XUnmapWindow( p_vout->p_sys->p_display, p_win->base_window );
1702     XDestroyWindow( p_vout->p_sys->p_display, p_win->base_window );
1703
1704     if( p_win->owner_window )
1705         vout_ReleaseWindow( p_vout, (void *)p_win->owner_window );
1706 }
1707
1708 /*****************************************************************************
1709  * NewPicture: allocate a picture
1710  *****************************************************************************
1711  * Returns 0 on success, -1 otherwise
1712  *****************************************************************************/
1713 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1714 {
1715 #ifndef MODULE_NAME_IS_glx
1716
1717 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1718     int i_plane;
1719 #endif
1720
1721     /* We know the chroma, allocate a buffer which will be used
1722      * directly by the decoder */
1723     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1724
1725     if( p_pic->p_sys == NULL )
1726     {
1727         return -1;
1728     }
1729
1730 #ifdef MODULE_NAME_IS_xvmc
1731     p_pic->p_sys->p_vout = p_vout;
1732     p_pic->p_sys->xvmc_surf = NULL;
1733     p_pic->p_sys->xxmc_data.decoded = 0;
1734     p_pic->p_sys->xxmc_data.proc_xxmc_update_frame = xxmc_do_update_frame;
1735     p_pic->p_accel_data = &p_pic->p_sys->xxmc_data;
1736     p_pic->p_sys->nb_display = 0;
1737 #endif
1738
1739     /* Fill in picture_t fields */
1740     vout_InitPicture( VLC_OBJECT(p_vout), p_pic, p_vout->output.i_chroma,
1741                       p_vout->output.i_width, p_vout->output.i_height,
1742                       p_vout->output.i_aspect );
1743
1744 #ifdef HAVE_SYS_SHM_H
1745     if( p_vout->p_sys->b_shm )
1746     {
1747         /* Create image using XShm extension */
1748         p_pic->p_sys->p_image =
1749             CreateShmImage( p_vout, p_vout->p_sys->p_display,
1750 #   if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1751                             p_vout->p_sys->i_xvport,
1752                             VLC2X11_FOURCC(p_vout->output.i_chroma),
1753 #   else
1754                             p_vout->p_sys->p_visual,
1755                             p_vout->p_sys->i_screen_depth,
1756 #   endif
1757                             &p_pic->p_sys->shminfo,
1758                             p_vout->output.i_width, p_vout->output.i_height );
1759     }
1760
1761     if( !p_vout->p_sys->b_shm || !p_pic->p_sys->p_image )
1762 #endif /* HAVE_SYS_SHM_H */
1763     {
1764         /* Create image without XShm extension */
1765         p_pic->p_sys->p_image =
1766             CreateImage( p_vout, p_vout->p_sys->p_display,
1767 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1768                          p_vout->p_sys->i_xvport, 
1769                          VLC2X11_FOURCC(p_vout->output.i_chroma),
1770                          p_pic->format.i_bits_per_pixel,
1771 #else
1772                          p_vout->p_sys->p_visual,
1773                          p_vout->p_sys->i_screen_depth,
1774                          p_vout->p_sys->i_bytes_per_pixel,
1775 #endif
1776                          p_vout->output.i_width, p_vout->output.i_height );
1777
1778 #ifdef HAVE_SYS_SHM_H
1779         if( p_pic->p_sys->p_image && p_vout->p_sys->b_shm )
1780         {
1781             msg_Warn( p_vout, "couldn't create SHM image, disabling SHM" );
1782             p_vout->p_sys->b_shm = VLC_FALSE;
1783         }
1784 #endif /* HAVE_SYS_SHM_H */
1785     }
1786
1787     if( p_pic->p_sys->p_image == NULL )
1788     {
1789         free( p_pic->p_sys );
1790         return -1;
1791     }
1792
1793     switch( p_vout->output.i_chroma )
1794     {
1795 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1796         case VLC_FOURCC('I','4','2','0'):
1797         case VLC_FOURCC('Y','V','1','2'):
1798         case VLC_FOURCC('Y','2','1','1'):
1799         case VLC_FOURCC('Y','U','Y','2'):
1800         case VLC_FOURCC('U','Y','V','Y'):
1801         case VLC_FOURCC('R','V','1','5'):
1802         case VLC_FOURCC('R','V','1','6'):
1803         case VLC_FOURCC('R','V','2','4'): /* Fixme: pixel pitch == 4 ? */
1804         case VLC_FOURCC('R','V','3','2'):
1805
1806             for( i_plane = 0; i_plane < p_pic->p_sys->p_image->num_planes;
1807                  i_plane++ )
1808             {
1809                 p_pic->p[i_plane].p_pixels = p_pic->p_sys->p_image->data
1810                     + p_pic->p_sys->p_image->offsets[i_plane];
1811                 p_pic->p[i_plane].i_pitch =
1812                     p_pic->p_sys->p_image->pitches[i_plane];
1813             }
1814             if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
1815             {
1816                 /* U and V inverted compared to I420
1817                  * Fixme: this should be handled by the vout core */
1818                 p_pic->U_PIXELS = p_pic->p_sys->p_image->data
1819                     + p_pic->p_sys->p_image->offsets[2];
1820                 p_pic->V_PIXELS = p_pic->p_sys->p_image->data
1821                     + p_pic->p_sys->p_image->offsets[1];
1822             }
1823             break;
1824
1825 #else
1826         case VLC_FOURCC('R','G','B','2'):
1827         case VLC_FOURCC('R','V','1','6'):
1828         case VLC_FOURCC('R','V','1','5'):
1829         case VLC_FOURCC('R','V','2','4'):
1830         case VLC_FOURCC('R','V','3','2'):
1831
1832             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
1833             p_pic->p->i_visible_lines = p_pic->p_sys->p_image->height;
1834             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1835                                   + p_pic->p_sys->p_image->xoffset;
1836             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
1837
1838             /* p_pic->p->i_pixel_pitch = 4 for RV24 but this should be set
1839              * properly by vout_InitPicture() */
1840             p_pic->p->i_visible_pitch = p_pic->p->i_pixel_pitch
1841                                          * p_pic->p_sys->p_image->width;
1842             break;
1843 #endif
1844
1845         default:
1846             /* Unknown chroma, tell the guy to get lost */
1847             IMAGE_FREE( p_pic->p_sys->p_image );
1848             free( p_pic->p_sys );
1849             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1850                      p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
1851             p_pic->i_planes = 0;
1852             return -1;
1853     }
1854
1855 #endif /* !MODULE_NAME_IS_glx */
1856
1857     return 0;
1858 }
1859
1860 /*****************************************************************************
1861  * FreePicture: destroy a picture allocated with NewPicture
1862  *****************************************************************************
1863  * Destroy XImage AND associated data. If using Shm, detach shared memory
1864  * segment from server and process, then free it. The XDestroyImage manpage
1865  * says that both the image structure _and_ the data pointed to by the
1866  * image structure are freed, so no need to free p_image->data.
1867  *****************************************************************************/
1868 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
1869 {
1870     /* The order of operations is correct */
1871 #ifdef HAVE_SYS_SHM_H
1872     if( p_vout->p_sys->b_shm )
1873     {
1874         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
1875         IMAGE_FREE( p_pic->p_sys->p_image );
1876
1877         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
1878         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
1879         {
1880             msg_Err( p_vout, "cannot detach shared memory (%s)",
1881                              strerror(errno) );
1882         }
1883     }
1884     else
1885 #endif
1886     {
1887         IMAGE_FREE( p_pic->p_sys->p_image );
1888     }
1889
1890 #ifdef MODULE_NAME_IS_xvmc
1891     if( p_pic->p_sys->xvmc_surf != NULL )
1892     {
1893         xxmc_xvmc_free_surface(p_vout , p_pic->p_sys->xvmc_surf);
1894         p_pic->p_sys->xvmc_surf = NULL;
1895     }
1896 #endif
1897
1898     /* Do NOT use XFlush here ! */
1899     XSync( p_vout->p_sys->p_display, False );
1900
1901     free( p_pic->p_sys );
1902 }
1903
1904 /*****************************************************************************
1905  * ToggleFullScreen: Enable or disable full screen mode
1906  *****************************************************************************
1907  * This function will switch between fullscreen and window mode.
1908  *****************************************************************************/
1909 static void ToggleFullScreen ( vout_thread_t *p_vout )
1910 {
1911     Atom prop;
1912     XEvent xevent;
1913     mwmhints_t mwmhints;
1914     XSetWindowAttributes attributes;
1915
1916 #ifdef HAVE_XINERAMA
1917     int i_d1, i_d2;
1918 #endif
1919
1920     p_vout->b_fullscreen = !p_vout->b_fullscreen;
1921
1922     if( p_vout->b_fullscreen )
1923     {
1924         msg_Dbg( p_vout, "entering fullscreen mode" );
1925
1926         p_vout->p_sys->b_altfullscreen =
1927             config_GetInt( p_vout, MODULE_STRING "-altfullscreen" );
1928
1929         XUnmapWindow( p_vout->p_sys->p_display,
1930                       p_vout->p_sys->p_win->base_window );
1931
1932         p_vout->p_sys->p_win = &p_vout->p_sys->fullscreen_window;
1933
1934         CreateWindow( p_vout, p_vout->p_sys->p_win );
1935         XDestroyWindow( p_vout->p_sys->p_display,
1936                         p_vout->p_sys->fullscreen_window.video_window );
1937         XReparentWindow( p_vout->p_sys->p_display,
1938                          p_vout->p_sys->original_window.video_window,
1939                          p_vout->p_sys->fullscreen_window.base_window, 0, 0 );
1940         p_vout->p_sys->fullscreen_window.video_window =
1941             p_vout->p_sys->original_window.video_window;
1942
1943         /* To my knowledge there are two ways to create a borderless window.
1944          * There's the generic way which is to tell x to bypass the window
1945          * manager, but this creates problems with the focus of other
1946          * applications.
1947          * The other way is to use the motif property "_MOTIF_WM_HINTS" which
1948          * luckily seems to be supported by most window managers. */
1949         if( !p_vout->p_sys->b_altfullscreen )
1950         {
1951             mwmhints.flags = MWM_HINTS_DECORATIONS;
1952             mwmhints.decorations = False;
1953
1954             prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1955                                 False );
1956             XChangeProperty( p_vout->p_sys->p_display,
1957                              p_vout->p_sys->p_win->base_window,
1958                              prop, prop, 32, PropModeReplace,
1959                              (unsigned char *)&mwmhints,
1960                              PROP_MWM_HINTS_ELEMENTS );
1961         }
1962         else
1963         {
1964             /* brute force way to remove decorations */
1965             attributes.override_redirect = True;
1966             XChangeWindowAttributes( p_vout->p_sys->p_display,
1967                                      p_vout->p_sys->p_win->base_window,
1968                                      CWOverrideRedirect,
1969                                      &attributes);
1970
1971             /* Make sure the change is effective */
1972             XReparentWindow( p_vout->p_sys->p_display,
1973                              p_vout->p_sys->p_win->base_window,
1974                              DefaultRootWindow( p_vout->p_sys->p_display ),
1975                              0, 0 );
1976         }
1977
1978         if( p_vout->p_sys->b_net_wm_state_fullscreen )
1979         {
1980             XClientMessageEvent event;
1981
1982             memset( &event, 0, sizeof( XClientMessageEvent ) );
1983
1984             event.type = ClientMessage;
1985             event.message_type = p_vout->p_sys->net_wm_state;
1986             event.display = p_vout->p_sys->p_display;
1987             event.window = p_vout->p_sys->p_win->base_window;
1988             event.format = 32;
1989             event.data.l[ 0 ] = 1; /* set property */
1990             event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_fullscreen;
1991
1992             XSendEvent( p_vout->p_sys->p_display,
1993                         DefaultRootWindow( p_vout->p_sys->p_display ),
1994                         False, SubstructureRedirectMask,
1995                         (XEvent*)&event );
1996         }
1997
1998         /* Make sure the change is effective */
1999         XReparentWindow( p_vout->p_sys->p_display,
2000                          p_vout->p_sys->p_win->base_window,
2001                          DefaultRootWindow( p_vout->p_sys->p_display ),
2002                          0, 0 );
2003
2004 #ifdef HAVE_XINERAMA
2005         if( XineramaQueryExtension( p_vout->p_sys->p_display, &i_d1, &i_d2 ) &&
2006             XineramaIsActive( p_vout->p_sys->p_display ) )
2007         {
2008             XineramaScreenInfo *screens;   /* infos for xinerama */
2009             int i_num_screens;
2010
2011             msg_Dbg( p_vout, "using XFree Xinerama extension");
2012
2013 #define SCREEN p_vout->p_sys->p_win->i_screen
2014
2015             /* Get Information about Xinerama (num of screens) */
2016             screens = XineramaQueryScreens( p_vout->p_sys->p_display,
2017                                             &i_num_screens );
2018
2019             SCREEN = config_GetInt( p_vout,
2020                                         MODULE_STRING "-xineramascreen" );
2021
2022             /* just check that user has entered a good value */
2023             if( SCREEN >= i_num_screens || SCREEN < 0 )
2024             {
2025                 msg_Dbg( p_vout, "requested screen number invalid (%d/%d)", SCREEN, i_num_screens );
2026                 SCREEN = 0;
2027             }
2028
2029             /* Get the X/Y upper left corner coordinate of the above screen */
2030             p_vout->p_sys->p_win->i_x = screens[SCREEN].x_org;
2031             p_vout->p_sys->p_win->i_y = screens[SCREEN].y_org;
2032
2033             /* Set the Height/width to the screen resolution */
2034             p_vout->p_sys->p_win->i_width = screens[SCREEN].width;
2035             p_vout->p_sys->p_win->i_height = screens[SCREEN].height;
2036
2037             XFree(screens);
2038
2039 #undef SCREEN
2040
2041         }
2042         else
2043 #endif
2044         {
2045             /* The window wasn't necessarily created at the requested size */
2046             p_vout->p_sys->p_win->i_x = p_vout->p_sys->p_win->i_y = 0;
2047
2048 #ifdef HAVE_XF86VIDMODE
2049             XF86VidModeModeLine mode;
2050             int i_dummy;
2051
2052             if( XF86VidModeGetModeLine( p_vout->p_sys->p_display,
2053                                         p_vout->p_sys->i_screen, &i_dummy,
2054                                         &mode ) )
2055             {
2056                 p_vout->p_sys->p_win->i_width = mode.hdisplay;
2057                 p_vout->p_sys->p_win->i_height = mode.vdisplay;
2058
2059                 /* move cursor to the middle of the window to prevent
2060                  * unwanted display move if the display is smaller than the
2061                  * full desktop */
2062                 XWarpPointer( p_vout->p_sys->p_display, None,
2063                               p_vout->p_sys->p_win->base_window, 0, 0, 0, 0,
2064                               mode.hdisplay / 2 , mode.vdisplay / 2 );
2065                 /* force desktop view to upper left corner */
2066                 XF86VidModeSetViewPort( p_vout->p_sys->p_display,
2067                                         p_vout->p_sys->i_screen, 0, 0 );
2068             }
2069             else
2070 #endif
2071             {
2072                 p_vout->p_sys->p_win->i_width =
2073                     DisplayWidth( p_vout->p_sys->p_display,
2074                                 p_vout->p_sys->i_screen );
2075                 p_vout->p_sys->p_win->i_height =
2076                     DisplayHeight( p_vout->p_sys->p_display,
2077                                 p_vout->p_sys->i_screen );
2078             }
2079
2080         }
2081
2082         XMoveResizeWindow( p_vout->p_sys->p_display,
2083                            p_vout->p_sys->p_win->base_window,
2084                            p_vout->p_sys->p_win->i_x,
2085                            p_vout->p_sys->p_win->i_y,
2086                            p_vout->p_sys->p_win->i_width,
2087                            p_vout->p_sys->p_win->i_height );
2088     }
2089     else
2090     {
2091         msg_Dbg( p_vout, "leaving fullscreen mode" );
2092
2093         XReparentWindow( p_vout->p_sys->p_display,
2094                          p_vout->p_sys->original_window.video_window,
2095                          p_vout->p_sys->original_window.base_window, 0, 0 );
2096
2097         p_vout->p_sys->fullscreen_window.video_window = None;
2098         DestroyWindow( p_vout, &p_vout->p_sys->fullscreen_window );
2099         p_vout->p_sys->p_win = &p_vout->p_sys->original_window;
2100
2101         XMapWindow( p_vout->p_sys->p_display,
2102                     p_vout->p_sys->p_win->base_window );
2103     }
2104
2105     /* Unfortunately, using XSync() here is not enough to ensure the
2106      * window has already been mapped because the XMapWindow() request
2107      * has not necessarily been sent directly to our window (remember,
2108      * the call is first redirected to the window manager) */
2109     do
2110     {
2111         XWindowEvent( p_vout->p_sys->p_display,
2112                       p_vout->p_sys->p_win->base_window,
2113                       StructureNotifyMask, &xevent );
2114     } while( xevent.type != MapNotify );
2115
2116     /* Be careful, this can generate a BadMatch error if the window is not
2117      * already mapped by the server (see above) */
2118     XSetInputFocus(p_vout->p_sys->p_display,
2119                    p_vout->p_sys->p_win->base_window,
2120                    RevertToParent,
2121                    CurrentTime);
2122
2123     /* signal that the size needs to be updated */
2124     p_vout->i_changes |= VOUT_SIZE_CHANGE;
2125 }
2126
2127 /*****************************************************************************
2128  * EnableXScreenSaver: enable screen saver
2129  *****************************************************************************
2130  * This function enables the screen saver on a display after it has been
2131  * disabled by XDisableScreenSaver.
2132  * FIXME: what happens if multiple vlc sessions are running at the same
2133  *        time ???
2134  *****************************************************************************/
2135 static void EnableXScreenSaver( vout_thread_t *p_vout )
2136 {
2137 #ifdef DPMSINFO_IN_DPMS_H
2138     int dummy;
2139 #endif
2140
2141     if( p_vout->p_sys->i_ss_timeout )
2142     {
2143         XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
2144                          p_vout->p_sys->i_ss_interval,
2145                          p_vout->p_sys->i_ss_blanking,
2146                          p_vout->p_sys->i_ss_exposure );
2147     }
2148
2149     /* Restore DPMS settings */
2150 #ifdef DPMSINFO_IN_DPMS_H
2151     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2152     {
2153         if( p_vout->p_sys->b_ss_dpms )
2154         {
2155             DPMSEnable( p_vout->p_sys->p_display );
2156         }
2157     }
2158 #endif
2159 }
2160
2161 /*****************************************************************************
2162  * DisableXScreenSaver: disable screen saver
2163  *****************************************************************************
2164  * See XEnableXScreenSaver
2165  *****************************************************************************/
2166 static void DisableXScreenSaver( vout_thread_t *p_vout )
2167 {
2168 #ifdef DPMSINFO_IN_DPMS_H
2169     int dummy;
2170 #endif
2171
2172     /* Save screen saver information */
2173     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
2174                      &p_vout->p_sys->i_ss_interval,
2175                      &p_vout->p_sys->i_ss_blanking,
2176                      &p_vout->p_sys->i_ss_exposure );
2177
2178     /* Disable screen saver */
2179     if( p_vout->p_sys->i_ss_timeout )
2180     {
2181         XSetScreenSaver( p_vout->p_sys->p_display, 0,
2182                          p_vout->p_sys->i_ss_interval,
2183                          p_vout->p_sys->i_ss_blanking,
2184                          p_vout->p_sys->i_ss_exposure );
2185     }
2186
2187     /* Disable DPMS */
2188 #ifdef DPMSINFO_IN_DPMS_H
2189     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2190     {
2191         CARD16 unused;
2192         /* Save DPMS current state */
2193         DPMSInfo( p_vout->p_sys->p_display, &unused,
2194                   &p_vout->p_sys->b_ss_dpms );
2195         DPMSDisable( p_vout->p_sys->p_display );
2196    }
2197 #endif
2198 }
2199
2200 /*****************************************************************************
2201  * CreateCursor: create a blank mouse pointer
2202  *****************************************************************************/
2203 static void CreateCursor( vout_thread_t *p_vout )
2204 {
2205     XColor cursor_color;
2206
2207     p_vout->p_sys->cursor_pixmap =
2208         XCreatePixmap( p_vout->p_sys->p_display,
2209                        DefaultRootWindow( p_vout->p_sys->p_display ),
2210                        1, 1, 1 );
2211
2212     XParseColor( p_vout->p_sys->p_display,
2213                  XCreateColormap( p_vout->p_sys->p_display,
2214                                   DefaultRootWindow(
2215                                                     p_vout->p_sys->p_display ),
2216                                   DefaultVisual(
2217                                                 p_vout->p_sys->p_display,
2218                                                 p_vout->p_sys->i_screen ),
2219                                   AllocNone ),
2220                  "black", &cursor_color );
2221
2222     p_vout->p_sys->blank_cursor =
2223         XCreatePixmapCursor( p_vout->p_sys->p_display,
2224                              p_vout->p_sys->cursor_pixmap,
2225                              p_vout->p_sys->cursor_pixmap,
2226                              &cursor_color, &cursor_color, 1, 1 );
2227 }
2228
2229 /*****************************************************************************
2230  * DestroyCursor: destroy the blank mouse pointer
2231  *****************************************************************************/
2232 static void DestroyCursor( vout_thread_t *p_vout )
2233 {
2234     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
2235 }
2236
2237 /*****************************************************************************
2238  * ToggleCursor: hide or show the mouse pointer
2239  *****************************************************************************
2240  * This function hides the X pointer if it is visible by setting the pointer
2241  * sprite to a blank one. To show it again, we disable the sprite.
2242  *****************************************************************************/
2243 static void ToggleCursor( vout_thread_t *p_vout )
2244 {
2245     if( p_vout->p_sys->b_mouse_pointer_visible )
2246     {
2247         XDefineCursor( p_vout->p_sys->p_display,
2248                        p_vout->p_sys->p_win->base_window,
2249                        p_vout->p_sys->blank_cursor );
2250         p_vout->p_sys->b_mouse_pointer_visible = 0;
2251     }
2252     else
2253     {
2254         XUndefineCursor( p_vout->p_sys->p_display,
2255                          p_vout->p_sys->p_win->base_window );
2256         p_vout->p_sys->b_mouse_pointer_visible = 1;
2257     }
2258 }
2259
2260 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
2261 /*****************************************************************************
2262  * XVideoGetPort: get YUV12 port
2263  *****************************************************************************/
2264 static int XVideoGetPort( vout_thread_t *p_vout,
2265                           vlc_fourcc_t i_chroma, vlc_fourcc_t *pi_newchroma )
2266 {
2267     XvAdaptorInfo *p_adaptor;
2268     unsigned int i;
2269     unsigned int i_adaptor, i_num_adaptors;
2270     int i_requested_adaptor;
2271     int i_selected_port;
2272
2273     switch( XvQueryExtension( p_vout->p_sys->p_display, &i, &i, &i, &i, &i ) )
2274     {
2275         case Success:
2276             break;
2277
2278         case XvBadExtension:
2279             msg_Warn( p_vout, "XvBadExtension" );
2280             return -1;
2281
2282         case XvBadAlloc:
2283             msg_Warn( p_vout, "XvBadAlloc" );
2284             return -1;
2285
2286         default:
2287             msg_Warn( p_vout, "XvQueryExtension failed" );
2288             return -1;
2289     }
2290
2291     switch( XvQueryAdaptors( p_vout->p_sys->p_display,
2292                              DefaultRootWindow( p_vout->p_sys->p_display ),
2293                              &i_num_adaptors, &p_adaptor ) )
2294     {
2295         case Success:
2296             break;
2297
2298         case XvBadExtension:
2299             msg_Warn( p_vout, "XvBadExtension for XvQueryAdaptors" );
2300             return -1;
2301
2302         case XvBadAlloc:
2303             msg_Warn( p_vout, "XvBadAlloc for XvQueryAdaptors" );
2304             return -1;
2305
2306         default:
2307             msg_Warn( p_vout, "XvQueryAdaptors failed" );
2308             return -1;
2309     }
2310
2311     i_selected_port = -1;
2312 #ifdef MODULE_NAME_IS_xvmc
2313     i_requested_adaptor = config_GetInt( p_vout, "xvmc-adaptor" );
2314 #else
2315     i_requested_adaptor = config_GetInt( p_vout, "xvideo-adaptor" );
2316 #endif
2317     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
2318     {
2319         XvImageFormatValues *p_formats;
2320         int i_format, i_num_formats;
2321         int i_port;
2322
2323         /* If we requested an adaptor and it's not this one, we aren't
2324          * interested */
2325         if( i_requested_adaptor != -1 && ((int)i_adaptor != i_requested_adaptor) )
2326         {
2327             continue;
2328         }
2329
2330         /* If the adaptor doesn't have the required properties, skip it */
2331         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
2332             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
2333         {
2334             continue;
2335         }
2336
2337         /* Check that adaptor supports our requested format... */
2338         p_formats = XvListImageFormats( p_vout->p_sys->p_display,
2339                                         p_adaptor[i_adaptor].base_id,
2340                                         &i_num_formats );
2341
2342         for( i_format = 0;
2343              i_format < i_num_formats && ( i_selected_port == -1 );
2344              i_format++ )
2345         {
2346             XvAttribute     *p_attr;
2347             int             i_attr, i_num_attributes;
2348
2349             /* If this is not the format we want, or at least a
2350              * similar one, forget it */
2351             if( !vout_ChromaCmp( p_formats[ i_format ].id, i_chroma ) )
2352             {
2353                 continue;
2354             }
2355
2356             /* Look for the first available port supporting this format */
2357             for( i_port = p_adaptor[i_adaptor].base_id;
2358                  ( i_port < (int)(p_adaptor[i_adaptor].base_id
2359                                    + p_adaptor[i_adaptor].num_ports) )
2360                    && ( i_selected_port == -1 );
2361                  i_port++ )
2362             {
2363                 if( XvGrabPort( p_vout->p_sys->p_display, i_port, CurrentTime )
2364                      == Success )
2365                 {
2366                     i_selected_port = i_port;
2367                     *pi_newchroma = p_formats[ i_format ].id;
2368                 }
2369             }
2370
2371             /* If no free port was found, forget it */
2372             if( i_selected_port == -1 )
2373             {
2374                 continue;
2375             }
2376
2377             /* If we found a port, print information about it */
2378             msg_Dbg( p_vout, "adaptor %i, port %i, format 0x%x (%4.4s) %s",
2379                      i_adaptor, i_selected_port, p_formats[ i_format ].id,
2380                      (char *)&p_formats[ i_format ].id,
2381                      ( p_formats[ i_format ].format == XvPacked ) ?
2382                          "packed" : "planar" );
2383
2384             /* Make sure XV_AUTOPAINT_COLORKEY is set */
2385             p_attr = XvQueryPortAttributes( p_vout->p_sys->p_display,
2386                                             i_selected_port,
2387                                             &i_num_attributes );
2388
2389             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
2390             {
2391                 if( !strcmp( p_attr[i_attr].name, "XV_AUTOPAINT_COLORKEY" ) )
2392                 {
2393                     const Atom autopaint =
2394                         XInternAtom( p_vout->p_sys->p_display,
2395                                      "XV_AUTOPAINT_COLORKEY", False );
2396                     XvSetPortAttribute( p_vout->p_sys->p_display,
2397                                         i_selected_port, autopaint, 1 );
2398                     break;
2399                 }
2400             }
2401
2402             if( p_attr != NULL )
2403             {
2404                 XFree( p_attr );
2405             }
2406         }
2407
2408         if( p_formats != NULL )
2409         {
2410             XFree( p_formats );
2411         }
2412
2413     }
2414
2415     if( i_num_adaptors > 0 )
2416     {
2417         XvFreeAdaptorInfo( p_adaptor );
2418     }
2419
2420     if( i_selected_port == -1 )
2421     {
2422         int i_chroma_tmp = X112VLC_FOURCC( i_chroma );
2423         if( i_requested_adaptor == -1 )
2424         {
2425             msg_Warn( p_vout, "no free XVideo port found for format "
2426                       "0x%.8x (%4.4s)", i_chroma_tmp, (char*)&i_chroma_tmp );
2427         }
2428         else
2429         {
2430             msg_Warn( p_vout, "XVideo adaptor %i does not have a free "
2431                       "XVideo port for format 0x%.8x (%4.4s)",
2432                       i_requested_adaptor, i_chroma_tmp, (char*)&i_chroma_tmp );
2433         }
2434     }
2435
2436     return i_selected_port;
2437 }
2438
2439 /*****************************************************************************
2440  * XVideoReleasePort: release YUV12 port
2441  *****************************************************************************/
2442 static void XVideoReleasePort( vout_thread_t *p_vout, int i_port )
2443 {
2444     XvUngrabPort( p_vout->p_sys->p_display, i_port, CurrentTime );
2445 }
2446 #endif
2447
2448 /*****************************************************************************
2449  * InitDisplay: open and initialize X11 device
2450  *****************************************************************************
2451  * Create a window according to video output given size, and set other
2452  * properties according to the display properties.
2453  *****************************************************************************/
2454 static int InitDisplay( vout_thread_t *p_vout )
2455 {
2456 #ifdef MODULE_NAME_IS_x11
2457     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
2458     XVisualInfo *               p_xvisual;            /* visuals information */
2459     XVisualInfo                 xvisual_template;         /* visual template */
2460     int                         i_count, i;                    /* array size */
2461 #endif
2462
2463 #ifdef HAVE_SYS_SHM_H
2464     p_vout->p_sys->b_shm = 0;
2465
2466     if( config_GetInt( p_vout, MODULE_STRING "-shm" ) )
2467     {
2468 #   ifdef __APPLE__
2469         /* FIXME: As of 2001-03-16, XFree4 for MacOS X does not support Xshm */
2470 #   else
2471         p_vout->p_sys->b_shm =
2472                   ( XShmQueryExtension( p_vout->p_sys->p_display ) == True );
2473 #   endif
2474
2475         if( !p_vout->p_sys->b_shm )
2476         {
2477             msg_Warn( p_vout, "XShm video extension is unavailable" );
2478         }
2479     }
2480     else
2481     {
2482         msg_Dbg( p_vout, "disabling XShm video extension" );
2483     }
2484
2485 #else
2486     msg_Warn( p_vout, "XShm video extension is unavailable" );
2487
2488 #endif
2489
2490 #ifdef MODULE_NAME_IS_xvideo
2491     /* XXX The brightness and contrast values should be read from environment
2492      * XXX variables... */
2493 #if 0
2494     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
2495     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
2496 #endif
2497 #endif
2498
2499 #ifdef MODULE_NAME_IS_x11
2500     /* Initialize structure */
2501     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
2502
2503     /* Get screen depth */
2504     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
2505                                                    p_vout->p_sys->i_screen );
2506     switch( p_vout->p_sys->i_screen_depth )
2507     {
2508     case 8:
2509         /*
2510          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
2511          */
2512         xvisual_template.screen =   p_vout->p_sys->i_screen;
2513         xvisual_template.class =    DirectColor;
2514         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2515                                     VisualScreenMask | VisualClassMask,
2516                                     &xvisual_template, &i_count );
2517         if( p_xvisual == NULL )
2518         {
2519             msg_Err( p_vout, "no PseudoColor visual available" );
2520             return VLC_EGENERIC;
2521         }
2522         p_vout->p_sys->i_bytes_per_pixel = 1;
2523         p_vout->output.pf_setpalette = SetPalette;
2524         break;
2525     case 15:
2526     case 16:
2527     case 24:
2528     default:
2529         /*
2530          * Screen depth is higher than 8bpp. TrueColor visual is used.
2531          */
2532         xvisual_template.screen =   p_vout->p_sys->i_screen;
2533         xvisual_template.class =    TrueColor;
2534 /* In some cases, we get a truecolor class adaptor that has a different
2535    color depth. So try to get a real true color one first */
2536         xvisual_template.depth =    p_vout->p_sys->i_screen_depth;
2537
2538         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2539                                     VisualScreenMask | VisualClassMask |
2540                                     VisualDepthMask,
2541                                     &xvisual_template, &i_count );
2542         if( p_xvisual == NULL )
2543         {
2544             msg_Warn( p_vout, "No screen matching the required color depth" );
2545             p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2546                                     VisualScreenMask | VisualClassMask,
2547                                     &xvisual_template, &i_count );
2548             if( p_xvisual == NULL )
2549             {
2550
2551                 msg_Err( p_vout, "no TrueColor visual available" );
2552                 return VLC_EGENERIC;
2553             }
2554         }
2555
2556         p_vout->output.i_rmask = p_xvisual->red_mask;
2557         p_vout->output.i_gmask = p_xvisual->green_mask;
2558         p_vout->output.i_bmask = p_xvisual->blue_mask;
2559
2560         /* There is no difference yet between 3 and 4 Bpp. The only way
2561          * to find the actual number of bytes per pixel is to list supported
2562          * pixmap formats. */
2563         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
2564         p_vout->p_sys->i_bytes_per_pixel = 0;
2565
2566         for( i = 0; i < i_count; i++ )
2567         {
2568             /* Under XFree4.0, the list contains pixmap formats available
2569              * through all video depths ; so we have to check against current
2570              * depth. */
2571             if( p_formats[i].depth == (int)p_vout->p_sys->i_screen_depth )
2572             {
2573                 if( p_formats[i].bits_per_pixel / 8
2574                         > (int)p_vout->p_sys->i_bytes_per_pixel )
2575                 {
2576                     p_vout->p_sys->i_bytes_per_pixel =
2577                         p_formats[i].bits_per_pixel / 8;
2578                 }
2579             }
2580         }
2581         if( p_formats ) XFree( p_formats );
2582
2583         break;
2584     }
2585     p_vout->p_sys->p_visual = p_xvisual->visual;
2586     XFree( p_xvisual );
2587 #endif
2588
2589     return VLC_SUCCESS;
2590 }
2591
2592 #ifdef HAVE_SYS_SHM_H
2593 /*****************************************************************************
2594  * CreateShmImage: create an XImage or XvImage using shared memory extension
2595  *****************************************************************************
2596  * Prepare an XImage or XvImage for display function.
2597  * The order of the operations respects the recommandations of the mit-shm
2598  * document by J.Corbet and K.Packard. Most of the parameters were copied from
2599  * there. See http://ftp.xfree86.org/pub/XFree86/4.0/doc/mit-shm.TXT
2600  *****************************************************************************/
2601 static IMAGE_TYPE * CreateShmImage( vout_thread_t *p_vout,
2602                                     Display* p_display, EXTRA_ARGS_SHM,
2603                                     int i_width, int i_height )
2604 {
2605     IMAGE_TYPE *p_image;
2606     Status result;
2607
2608     /* Create XImage / XvImage */
2609 #ifdef MODULE_NAME_IS_xvideo
2610
2611     /* Make sure the buffer is aligned to multiple of 16 */
2612     i_height = ( i_height + 15 ) >> 4 << 4;
2613     i_width = ( i_width + 15 ) >> 4 << 4;
2614
2615     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2616                                 i_width, i_height, p_shm );
2617 #elif defined(MODULE_NAME_IS_xvmc)
2618     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2619                                 i_width, i_height, p_shm );
2620 #else
2621     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2622                                p_shm, i_width, i_height );
2623 #endif
2624     if( p_image == NULL )
2625     {
2626         msg_Err( p_vout, "image creation failed" );
2627         return NULL;
2628     }
2629
2630     /* Allocate shared memory segment - 0776 set the access permission
2631      * rights (like umask), they are not yet supported by all X servers */
2632     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE(p_image), IPC_CREAT | 0776 );
2633     if( p_shm->shmid < 0 )
2634     {
2635         msg_Err( p_vout, "cannot allocate shared image data (%s)",
2636                          strerror( errno ) );
2637         IMAGE_FREE( p_image );
2638         return NULL;
2639     }
2640
2641     /* Attach shared memory segment to process (read/write) */
2642     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
2643     if(! p_shm->shmaddr )
2644     {
2645         msg_Err( p_vout, "cannot attach shared memory (%s)",
2646                          strerror(errno));
2647         IMAGE_FREE( p_image );
2648         shmctl( p_shm->shmid, IPC_RMID, 0 );
2649         return NULL;
2650     }
2651
2652     /* Read-only data. We won't be using XShmGetImage */
2653     p_shm->readOnly = True;
2654
2655     /* Attach shared memory segment to X server */
2656     XSynchronize( p_display, True );
2657     b_shm = VLC_TRUE;
2658     result = XShmAttach( p_display, p_shm );
2659     if( result == False || !b_shm )
2660     {
2661         msg_Err( p_vout, "cannot attach shared memory to X server" );
2662         IMAGE_FREE( p_image );
2663         shmctl( p_shm->shmid, IPC_RMID, 0 );
2664         shmdt( p_shm->shmaddr );
2665         return NULL;
2666     }
2667     XSynchronize( p_display, False );
2668
2669     /* Send image to X server. This instruction is required, since having
2670      * built a Shm XImage and not using it causes an error on XCloseDisplay,
2671      * and remember NOT to use XFlush ! */
2672     XSync( p_display, False );
2673
2674 #if 0
2675     /* Mark the shm segment to be removed when there are no more
2676      * attachements, so it is automatic on process exit or after shmdt */
2677     shmctl( p_shm->shmid, IPC_RMID, 0 );
2678 #endif
2679
2680     return p_image;
2681 }
2682 #endif
2683
2684 /*****************************************************************************
2685  * CreateImage: create an XImage or XvImage
2686  *****************************************************************************
2687  * Create a simple image used as a buffer.
2688  *****************************************************************************/
2689 static IMAGE_TYPE * CreateImage( vout_thread_t *p_vout,
2690                                  Display *p_display, EXTRA_ARGS,
2691                                  int i_width, int i_height )
2692 {
2693     byte_t *    p_data;                           /* image data storage zone */
2694     IMAGE_TYPE *p_image;
2695 #ifdef MODULE_NAME_IS_x11
2696     int         i_quantum;                     /* XImage quantum (see below) */
2697     int         i_bytes_per_line;
2698 #endif
2699
2700     /* Allocate memory for image */
2701 #ifdef MODULE_NAME_IS_xvideo
2702
2703     /* Make sure the buffer is aligned to multiple of 16 */
2704     i_height = ( i_height + 15 ) >> 4 << 4;
2705     i_width = ( i_width + 15 ) >> 4 << 4;
2706
2707     p_data = (byte_t *) malloc( i_width * i_height * i_bits_per_pixel / 8 );
2708 #elif defined(MODULE_NAME_IS_x11)
2709     i_bytes_per_line = i_width * i_bytes_per_pixel;
2710     p_data = (byte_t *) malloc( i_bytes_per_line * i_height );
2711 #endif
2712     if( !p_data )
2713     {
2714         msg_Err( p_vout, "out of memory" );
2715         return NULL;
2716     }
2717
2718 #ifdef MODULE_NAME_IS_x11
2719     /* Optimize the quantum of a scanline regarding its size - the quantum is
2720        a diviser of the number of bits between the start of two scanlines. */
2721     if( i_bytes_per_line & 0xf )
2722     {
2723         i_quantum = 0x8;
2724     }
2725     else if( i_bytes_per_line & 0x10 )
2726     {
2727         i_quantum = 0x10;
2728     }
2729     else
2730     {
2731         i_quantum = 0x20;
2732     }
2733 #endif
2734
2735     /* Create XImage. p_data will be automatically freed */
2736 #ifdef MODULE_NAME_IS_xvideo
2737     p_image = XvCreateImage( p_display, i_xvport, i_chroma,
2738                              (char *)p_data, i_width, i_height );
2739 #elif defined(MODULE_NAME_IS_x11)
2740     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2741                             (char *)p_data, i_width, i_height, i_quantum, 0 );
2742 #endif
2743     if( p_image == NULL )
2744     {
2745         msg_Err( p_vout, "XCreateImage() failed" );
2746         free( p_data );
2747         return NULL;
2748     }
2749
2750     return p_image;
2751 }
2752
2753 /*****************************************************************************
2754  * X11ErrorHandler: replace error handler so we can intercept some of them
2755  *****************************************************************************/
2756 static int X11ErrorHandler( Display * display, XErrorEvent * event )
2757 {
2758     /* Ingnore errors on XSetInputFocus()
2759      * (they happen when a window is not yet mapped) */
2760     if( event->request_code == X_SetInputFocus )
2761     {
2762         fprintf(stderr, "XSetInputFocus failed\n");
2763         return 0;
2764     }
2765
2766     if( event->request_code == 150 /* MIT-SHM */ &&
2767         event->minor_code == X_ShmAttach )
2768     {
2769         fprintf(stderr, "XShmAttach failed\n");
2770         b_shm = VLC_FALSE;
2771         return 0;
2772     }
2773
2774     XSetErrorHandler(NULL);
2775     return (XSetErrorHandler(X11ErrorHandler))( display, event );
2776 }
2777
2778 #ifdef MODULE_NAME_IS_x11
2779 /*****************************************************************************
2780  * SetPalette: sets an 8 bpp palette
2781  *****************************************************************************
2782  * This function sets the palette given as an argument. It does not return
2783  * anything, but could later send information on which colors it was unable
2784  * to set.
2785  *****************************************************************************/
2786 static void SetPalette( vout_thread_t *p_vout,
2787                         uint16_t *red, uint16_t *green, uint16_t *blue )
2788 {
2789     int i;
2790     XColor p_colors[255];
2791
2792     /* allocate palette */
2793     for( i = 0; i < 255; i++ )
2794     {
2795         /* kludge: colors are indexed reversely because color 255 seems
2796          * to be reserved for black even if we try to set it to white */
2797         p_colors[ i ].pixel = 255 - i;
2798         p_colors[ i ].pad   = 0;
2799         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
2800         p_colors[ i ].red   = red[ 255 - i ];
2801         p_colors[ i ].blue  = blue[ 255 - i ];
2802         p_colors[ i ].green = green[ 255 - i ];
2803     }
2804
2805     XStoreColors( p_vout->p_sys->p_display,
2806                   p_vout->p_sys->colormap, p_colors, 255 );
2807 }
2808 #endif
2809
2810 /*****************************************************************************
2811  * Control: control facility for the vout
2812  *****************************************************************************/
2813 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
2814 {
2815     vlc_bool_t b_arg;
2816     unsigned int i_width, i_height;
2817     unsigned int *pi_width, *pi_height;
2818     Drawable d = 0;
2819
2820     switch( i_query )
2821     {
2822         case VOUT_GET_SIZE:
2823             if( p_vout->p_sys->p_win->owner_window )
2824                 return vout_ControlWindow( p_vout,
2825                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2826
2827             pi_width  = va_arg( args, unsigned int * );
2828             pi_height = va_arg( args, unsigned int * );
2829
2830             vlc_mutex_lock( &p_vout->p_sys->lock );
2831             *pi_width  = p_vout->p_sys->p_win->i_width;
2832             *pi_height = p_vout->p_sys->p_win->i_height;
2833             vlc_mutex_unlock( &p_vout->p_sys->lock );
2834             return VLC_SUCCESS;
2835
2836         case VOUT_SET_SIZE:
2837             if( p_vout->p_sys->p_win->owner_window )
2838                 return vout_ControlWindow( p_vout,
2839                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2840
2841             vlc_mutex_lock( &p_vout->p_sys->lock );
2842
2843             i_width  = va_arg( args, unsigned int );
2844             i_height = va_arg( args, unsigned int );
2845             if( !i_width ) i_width = p_vout->i_window_width;
2846             if( !i_height ) i_height = p_vout->i_window_height;
2847
2848 #ifdef MODULE_NAME_IS_xvmc
2849             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
2850 #endif
2851             /* Update dimensions */
2852             XResizeWindow( p_vout->p_sys->p_display,
2853                            p_vout->p_sys->p_win->base_window,
2854                            i_width, i_height );
2855 #ifdef MODULE_NAME_IS_xvmc
2856             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
2857 #endif
2858             vlc_mutex_unlock( &p_vout->p_sys->lock );
2859             return VLC_SUCCESS;
2860
2861        case VOUT_CLOSE:
2862             vlc_mutex_lock( &p_vout->p_sys->lock );
2863             XUnmapWindow( p_vout->p_sys->p_display,
2864                           p_vout->p_sys->original_window.base_window );
2865             vlc_mutex_unlock( &p_vout->p_sys->lock );
2866             /* Fall through */
2867
2868        case VOUT_REPARENT:
2869             vlc_mutex_lock( &p_vout->p_sys->lock );
2870             if( i_query == VOUT_REPARENT ) d = (Drawable)va_arg( args, int );
2871             if( !d )
2872 #ifdef MODULE_NAME_IS_xvmc
2873             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
2874 #endif
2875             XReparentWindow( p_vout->p_sys->p_display,
2876                              p_vout->p_sys->original_window.base_window,
2877                              DefaultRootWindow( p_vout->p_sys->p_display ),
2878                              0, 0 );
2879             else
2880             XReparentWindow( p_vout->p_sys->p_display,
2881                              p_vout->p_sys->original_window.base_window,
2882                              d, 0, 0);
2883             XSync( p_vout->p_sys->p_display, False );
2884             p_vout->p_sys->original_window.owner_window = 0;
2885 #ifdef MODULE_NAME_IS_xvmc
2886             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
2887 #endif
2888             vlc_mutex_unlock( &p_vout->p_sys->lock );
2889             return vout_vaControlDefault( p_vout, i_query, args );
2890
2891         case VOUT_SET_STAY_ON_TOP:
2892             if( p_vout->p_sys->p_win->owner_window )
2893                 return vout_ControlWindow( p_vout,
2894                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2895
2896             b_arg = va_arg( args, vlc_bool_t );
2897             vlc_mutex_lock( &p_vout->p_sys->lock );
2898 #ifdef MODULE_NAME_IS_xvmc
2899             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
2900 #endif
2901             WindowOnTop( p_vout, b_arg );
2902 #ifdef MODULE_NAME_IS_xvmc
2903             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
2904 #endif
2905             vlc_mutex_unlock( &p_vout->p_sys->lock );
2906             return VLC_SUCCESS;
2907
2908        default:
2909             return vout_vaControlDefault( p_vout, i_query, args );
2910     }
2911 }
2912
2913 /*****************************************************************************
2914  * TestNetWMSupport: tests for Extended Window Manager Hints support
2915  *****************************************************************************/
2916 static void TestNetWMSupport( vout_thread_t *p_vout )
2917 {
2918     int i_ret, i_format;
2919     unsigned long i, i_items, i_bytesafter;
2920     Atom net_wm_supported;
2921     union { Atom *p_atom; unsigned char *p_char; } p_args;
2922
2923     p_args.p_atom = NULL;
2924
2925     p_vout->p_sys->b_net_wm_state_fullscreen = VLC_FALSE;
2926     p_vout->p_sys->b_net_wm_state_above = VLC_FALSE;
2927     p_vout->p_sys->b_net_wm_state_below = VLC_FALSE;
2928     p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_FALSE;
2929
2930     net_wm_supported =
2931         XInternAtom( p_vout->p_sys->p_display, "_NET_SUPPORTED", False );
2932
2933     i_ret = XGetWindowProperty( p_vout->p_sys->p_display,
2934                                 DefaultRootWindow( p_vout->p_sys->p_display ),
2935                                 net_wm_supported,
2936                                 0, 16384, False, AnyPropertyType,
2937                                 &net_wm_supported,
2938                                 &i_format, &i_items, &i_bytesafter,
2939                                 (unsigned char **)&p_args );
2940
2941     if( i_ret != Success || i_items == 0 ) return;
2942
2943     msg_Dbg( p_vout, "Window manager supports NetWM" );
2944
2945     p_vout->p_sys->net_wm_state =
2946         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE", False );
2947     p_vout->p_sys->net_wm_state_fullscreen =
2948         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_FULLSCREEN",
2949                      False );
2950     p_vout->p_sys->net_wm_state_above =
2951         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_ABOVE", False );
2952     p_vout->p_sys->net_wm_state_below =
2953         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_BELOW", False );
2954     p_vout->p_sys->net_wm_state_stays_on_top =
2955         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_STAYS_ON_TOP",
2956                      False );
2957
2958     for( i = 0; i < i_items; i++ )
2959     {
2960         if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_fullscreen )
2961         {
2962             msg_Dbg( p_vout,
2963                      "Window manager supports _NET_WM_STATE_FULLSCREEN" );
2964             p_vout->p_sys->b_net_wm_state_fullscreen = VLC_TRUE;
2965         }
2966         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_above )
2967         {
2968             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_ABOVE" );
2969             p_vout->p_sys->b_net_wm_state_above = VLC_TRUE;
2970         }
2971         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_below )
2972         {
2973             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_BELOW" );
2974             p_vout->p_sys->b_net_wm_state_below = VLC_TRUE;
2975         }
2976         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_stays_on_top )
2977         {
2978             msg_Dbg( p_vout,
2979                      "Window manager supports _NET_WM_STATE_STAYS_ON_TOP" );
2980             p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_TRUE;
2981         }
2982     }
2983
2984     XFree( p_args.p_atom );
2985 }
2986
2987 /*****************************************************************************
2988  * Key events handling
2989  *****************************************************************************/
2990 static struct
2991 {
2992     int i_x11key;
2993     int i_vlckey;
2994
2995 } x11keys_to_vlckeys[] =
2996 {
2997     { XK_F1, KEY_F1 }, { XK_F2, KEY_F2 }, { XK_F3, KEY_F3 }, { XK_F4, KEY_F4 },
2998     { XK_F5, KEY_F5 }, { XK_F6, KEY_F6 }, { XK_F7, KEY_F7 }, { XK_F8, KEY_F8 },
2999     { XK_F9, KEY_F9 }, { XK_F10, KEY_F10 }, { XK_F11, KEY_F11 },
3000     { XK_F12, KEY_F12 },
3001
3002     { XK_Return, KEY_ENTER },
3003     { XK_KP_Enter, KEY_ENTER },
3004     { XK_space, KEY_SPACE },
3005     { XK_Escape, KEY_ESC },
3006
3007     { XK_Menu, KEY_MENU },
3008     { XK_Left, KEY_LEFT },
3009     { XK_Right, KEY_RIGHT },
3010     { XK_Up, KEY_UP },
3011     { XK_Down, KEY_DOWN },
3012
3013     { XK_Home, KEY_HOME },
3014     { XK_End, KEY_END },
3015     { XK_Page_Up, KEY_PAGEUP },
3016     { XK_Page_Down, KEY_PAGEDOWN },
3017
3018     { XK_Insert, KEY_INSERT },
3019     { XK_Delete, KEY_DELETE },
3020
3021     { 0, 0 }
3022 };
3023
3024 static int ConvertKey( int i_key )
3025 {
3026     int i;
3027
3028     for( i = 0; x11keys_to_vlckeys[i].i_x11key != 0; i++ )
3029     {
3030         if( x11keys_to_vlckeys[i].i_x11key == i_key )
3031         {
3032             return x11keys_to_vlckeys[i].i_vlckey;
3033         }
3034     }
3035
3036     return 0;
3037 }
3038
3039 /*****************************************************************************
3040  * WindowOnTop: Switches the "always on top" state of the video window.
3041  *****************************************************************************/
3042 static int WindowOnTop( vout_thread_t *p_vout, vlc_bool_t b_on_top )
3043 {
3044     if( p_vout->p_sys->b_net_wm_state_stays_on_top )
3045     {
3046         XClientMessageEvent event;
3047
3048         memset( &event, 0, sizeof( XClientMessageEvent ) );
3049
3050         event.type = ClientMessage;
3051         event.message_type = p_vout->p_sys->net_wm_state;
3052         event.display = p_vout->p_sys->p_display;
3053         event.window = p_vout->p_sys->p_win->base_window;
3054         event.format = 32;
3055         event.data.l[ 0 ] = b_on_top; /* set property */
3056         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_stays_on_top;
3057
3058         XSendEvent( p_vout->p_sys->p_display,
3059                     DefaultRootWindow( p_vout->p_sys->p_display ),
3060                     False, SubstructureRedirectMask,
3061                     (XEvent*)&event );
3062     }
3063
3064     /* use _NET_WM_STATE_ABOVE if window manager
3065      * doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
3066     else if( p_vout->p_sys->b_net_wm_state_above )
3067     {
3068         XClientMessageEvent event;
3069
3070         memset( &event, 0, sizeof( XClientMessageEvent ) );
3071
3072         event.type = ClientMessage;
3073         event.message_type = p_vout->p_sys->net_wm_state;
3074         event.display = p_vout->p_sys->p_display;
3075         event.window = p_vout->p_sys->p_win->base_window;
3076         event.format = 32;
3077         event.data.l[ 0 ] = b_on_top; /* set property */
3078         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_above;
3079
3080         XSendEvent( p_vout->p_sys->p_display,
3081                     DefaultRootWindow( p_vout->p_sys->p_display ),
3082                     False, SubstructureRedirectMask,
3083                     (XEvent*)&event );
3084     }
3085
3086     return VLC_SUCCESS;
3087 }