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