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