]> git.sesse.net Git - vlc/blob - modules/video_output/x11/xcommon.c
Work-around window-on-top + fullscreen deadlock (refs #882)
[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
1330         /*
1331          * FIXME FIXME FIXME FIXME: EXPLICIT HACK.
1332          * On the one hand, we cannot hold the lock while triggering a
1333          * callback, as it causes a deadlock with video-on-top handling.
1334          * On the other hand, we have to lock while triggering the
1335          * callback to:
1336          *  1/ make sure video-on-top remains in sync with fullscreen
1337          *    (i.e. unlocking creates a race condition if fullscreen is
1338          *     switched on and off VERY FAST).
1339          *  2/ avoid possible corruption bugs if another thread gets the
1340          *     mutex and modifies our data in-between.
1341          *
1342          * This is obviously contradictory. Correct solutions may include:
1343          *  - putting the fullscreen NAND video-on-top logic out of libvlc,
1344          *    back into the video output plugins (ugly code duplication...),
1345          *  - serializing fullscreen and video-on-top handling properly
1346          *    instead of doing it via the fullscreen callback. That's got to
1347          *    be the correct one.
1348          */
1349 #ifdef MODULE_NAME_IS_xvmc
1350         xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1351 #endif
1352         vlc_mutex_unlock( &p_vout->p_sys->lock );
1353
1354         var_Set( p_vout, "fullscreen", val );
1355
1356         vlc_mutex_lock( &p_vout->p_sys->lock );
1357 #ifdef MODULE_NAME_IS_xvmc
1358         xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
1359 #endif
1360
1361         ToggleFullScreen( p_vout );
1362         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
1363     }
1364
1365     if( p_vout->i_changes & VOUT_CROP_CHANGE ||
1366         p_vout->i_changes & VOUT_ASPECT_CHANGE )
1367     {
1368         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
1369         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
1370
1371         p_vout->fmt_out.i_x_offset = p_vout->fmt_in.i_x_offset;
1372         p_vout->fmt_out.i_y_offset = p_vout->fmt_in.i_y_offset;
1373         p_vout->fmt_out.i_visible_width = p_vout->fmt_in.i_visible_width;
1374         p_vout->fmt_out.i_visible_height = p_vout->fmt_in.i_visible_height;
1375         p_vout->fmt_out.i_aspect = p_vout->fmt_in.i_aspect;
1376         p_vout->fmt_out.i_sar_num = p_vout->fmt_in.i_sar_num;
1377         p_vout->fmt_out.i_sar_den = p_vout->fmt_in.i_sar_den;
1378         p_vout->output.i_aspect = p_vout->fmt_in.i_aspect;
1379
1380         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1381     }
1382
1383     /*
1384      * Size change
1385      *
1386      * (Needs to be placed after VOUT_FULLSREEN_CHANGE because we can activate
1387      *  the size flag inside the fullscreen routine)
1388      */
1389     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
1390     {
1391         unsigned int i_width, i_height, i_x, i_y;
1392
1393         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
1394
1395 #ifdef MODULE_NAME_IS_x11
1396         /* We need to signal the vout thread about the size change because it
1397          * is doing the rescaling */
1398         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1399 #endif
1400
1401         vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
1402                            p_vout->p_sys->p_win->i_height,
1403                            &i_x, &i_y, &i_width, &i_height );
1404
1405         XMoveResizeWindow( p_vout->p_sys->p_display,
1406                            p_vout->p_sys->p_win->video_window,
1407                            i_x, i_y, i_width, i_height );
1408     }
1409
1410     /* Autohide Cursour */
1411     if( mdate() - p_vout->p_sys->i_time_mouse_last_moved > 2000000 )
1412     {
1413         /* Hide the mouse automatically */
1414         if( p_vout->p_sys->b_mouse_pointer_visible )
1415         {
1416             ToggleCursor( p_vout );
1417         }
1418     }
1419
1420 #ifdef MODULE_NAME_IS_xvmc
1421     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1422 #endif
1423
1424     vlc_mutex_unlock( &p_vout->p_sys->lock );
1425     return 0;
1426 }
1427
1428 /*****************************************************************************
1429  * EndVideo: terminate X11 video thread output method
1430  *****************************************************************************
1431  * Destroy the X11 XImages created by Init. It is called at the end of
1432  * the thread, but also each time the window is resized.
1433  *****************************************************************************/
1434 static void EndVideo( vout_thread_t *p_vout )
1435 {
1436     int i_index;
1437
1438     /* Free the direct buffers we allocated */
1439     for( i_index = I_OUTPUTPICTURES ; i_index ; )
1440     {
1441         i_index--;
1442         FreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
1443     }
1444 }
1445
1446 /* following functions are local */
1447
1448 /*****************************************************************************
1449  * CreateWindow: open and set-up X11 main window
1450  *****************************************************************************/
1451 static int CreateWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1452 {
1453     XSizeHints              xsize_hints;
1454     XSetWindowAttributes    xwindow_attributes;
1455     XGCValues               xgcvalues;
1456     XEvent                  xevent;
1457
1458     vlc_bool_t              b_expose = VLC_FALSE;
1459     vlc_bool_t              b_configure_notify = VLC_FALSE;
1460     vlc_bool_t              b_map_notify = VLC_FALSE;
1461     vlc_value_t             val;
1462
1463     /* Prepare window manager hints and properties */
1464     p_win->wm_protocols =
1465              XInternAtom( p_vout->p_sys->p_display, "WM_PROTOCOLS", True );
1466     p_win->wm_delete_window =
1467              XInternAtom( p_vout->p_sys->p_display, "WM_DELETE_WINDOW", True );
1468
1469     /* Never have a 0-pixel-wide window */
1470     xsize_hints.min_width = 2;
1471     xsize_hints.min_height = 1;
1472
1473     /* Prepare window attributes */
1474     xwindow_attributes.backing_store = Always;       /* save the hidden part */
1475     xwindow_attributes.background_pixel = BlackPixel(p_vout->p_sys->p_display,
1476                                                      p_vout->p_sys->i_screen);
1477     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
1478
1479     if( !p_vout->b_fullscreen )
1480     {
1481         p_win->owner_window =
1482             (Window)vout_RequestWindow( p_vout, &p_win->i_x, &p_win->i_y,
1483                                         &p_win->i_width, &p_win->i_height );
1484
1485         xsize_hints.base_width  = xsize_hints.width = p_win->i_width;
1486         xsize_hints.base_height = xsize_hints.height = p_win->i_height;
1487         xsize_hints.flags       = PSize | PMinSize;
1488
1489         if( p_win->i_x >=0 || p_win->i_y >= 0 )
1490         {
1491             xsize_hints.x = p_win->i_x;
1492             xsize_hints.y = p_win->i_y;
1493             xsize_hints.flags |= PPosition;
1494         }
1495     }
1496     else
1497     {
1498         /* Fullscreen window size and position */
1499         p_win->owner_window = 0;
1500         p_win->i_x = p_win->i_y = 0;
1501         p_win->i_width =
1502             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1503         p_win->i_height =
1504             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1505     }
1506
1507     if( !p_win->owner_window )
1508     {
1509         /* Create the window and set hints - the window must receive
1510          * ConfigureNotify events, and until it is displayed, Expose and
1511          * MapNotify events. */
1512
1513         p_win->base_window =
1514             XCreateWindow( p_vout->p_sys->p_display,
1515                            DefaultRootWindow( p_vout->p_sys->p_display ),
1516                            p_win->i_x, p_win->i_y,
1517                            p_win->i_width, p_win->i_height,
1518                            0,
1519                            0, InputOutput, 0,
1520                            CWBackingStore | CWBackPixel | CWEventMask,
1521                            &xwindow_attributes );
1522
1523         if( !p_vout->b_fullscreen )
1524         {
1525             /* Set window manager hints and properties: size hints, command,
1526              * window's name, and accepted protocols */
1527             XSetWMNormalHints( p_vout->p_sys->p_display,
1528                                p_win->base_window, &xsize_hints );
1529             XSetCommand( p_vout->p_sys->p_display, p_win->base_window,
1530                          p_vout->p_libvlc->ppsz_argv, p_vout->p_libvlc->i_argc );
1531
1532             if( !var_GetBool( p_vout, "video-deco") )
1533             {
1534                 Atom prop;
1535                 mwmhints_t mwmhints;
1536
1537                 mwmhints.flags = MWM_HINTS_DECORATIONS;
1538                 mwmhints.decorations = False;
1539
1540                 prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1541                                     False );
1542
1543                 XChangeProperty( p_vout->p_sys->p_display,
1544                                  p_win->base_window,
1545                                  prop, prop, 32, PropModeReplace,
1546                                  (unsigned char *)&mwmhints,
1547                                  PROP_MWM_HINTS_ELEMENTS );
1548             }
1549             else
1550             {
1551                  var_Get( p_vout, "video-title", &val );
1552                  if( !val.psz_string || !*val.psz_string )
1553                  {
1554                     XStoreName( p_vout->p_sys->p_display, p_win->base_window,
1555 #ifdef MODULE_NAME_IS_x11
1556                                 VOUT_TITLE " (X11 output)"
1557 #elif defined(MODULE_NAME_IS_glx)
1558                                 VOUT_TITLE " (GLX output)"
1559 #else
1560                                 VOUT_TITLE " (XVideo output)"
1561 #endif
1562                       );
1563                 }
1564                 else
1565                 {
1566                     XStoreName( p_vout->p_sys->p_display,
1567                                p_win->base_window, val.psz_string );
1568                 }
1569                 if( val.psz_string ) free( val.psz_string );
1570             }
1571         }
1572     }
1573     else
1574     {
1575         Window dummy1;
1576         int dummy2, dummy3;
1577         unsigned int dummy4, dummy5;
1578
1579         /* Select events we are interested in. */
1580         XSelectInput( p_vout->p_sys->p_display, p_win->owner_window,
1581                       StructureNotifyMask );
1582
1583         /* Get the parent window's geometry information */
1584         XGetGeometry( p_vout->p_sys->p_display, p_win->owner_window,
1585                       &dummy1, &dummy2, &dummy3,
1586                       &p_win->i_width,
1587                       &p_win->i_height,
1588                       &dummy4, &dummy5 );
1589
1590         /* We are already configured */
1591         b_configure_notify = VLC_TRUE;
1592
1593         /* From man XSelectInput: only one client at a time can select a
1594          * ButtonPress event, so we need to open a new window anyway. */
1595         p_win->base_window =
1596             XCreateWindow( p_vout->p_sys->p_display,
1597                            p_win->owner_window,
1598                            0, 0,
1599                            p_win->i_width, p_win->i_height,
1600                            0,
1601                            0, CopyFromParent, 0,
1602                            CWBackingStore | CWBackPixel | CWEventMask,
1603                            &xwindow_attributes );
1604     }
1605
1606     if( (p_win->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1607         || (p_win->wm_delete_window == None)
1608         || !XSetWMProtocols( p_vout->p_sys->p_display, p_win->base_window,
1609                              &p_win->wm_delete_window, 1 ) )
1610     {
1611         /* WM_DELETE_WINDOW is not supported by window manager */
1612         msg_Warn( p_vout, "missing or bad window manager" );
1613     }
1614
1615     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1616      * event when using functions like XCopyArea */
1617     xgcvalues.graphics_exposures = False;
1618     p_win->gc = XCreateGC( p_vout->p_sys->p_display,
1619                            p_win->base_window,
1620                            GCGraphicsExposures, &xgcvalues );
1621
1622     /* Send orders to server, and wait until window is displayed - three
1623      * events must be received: a MapNotify event, an Expose event allowing
1624      * drawing in the window, and a ConfigureNotify to get the window
1625      * dimensions. Once those events have been received, only
1626      * ConfigureNotify events need to be received. */
1627     XMapWindow( p_vout->p_sys->p_display, p_win->base_window );
1628     do
1629     {
1630         XWindowEvent( p_vout->p_sys->p_display, p_win->base_window,
1631                       SubstructureNotifyMask | StructureNotifyMask |
1632                       ExposureMask, &xevent);
1633         if( (xevent.type == Expose)
1634             && (xevent.xexpose.window == p_win->base_window) )
1635         {
1636             b_expose = VLC_TRUE;
1637             /* ConfigureNotify isn't sent if there isn't a window manager.
1638              * Expose should be the last event to be received so it should
1639              * be fine to assume we won't receive it anymore. */
1640             b_configure_notify = VLC_TRUE;
1641         }
1642         else if( (xevent.type == MapNotify)
1643                  && (xevent.xmap.window == p_win->base_window) )
1644         {
1645             b_map_notify = VLC_TRUE;
1646         }
1647         else if( (xevent.type == ConfigureNotify)
1648                  && (xevent.xconfigure.window == p_win->base_window) )
1649         {
1650             b_configure_notify = VLC_TRUE;
1651             p_win->i_width = xevent.xconfigure.width;
1652             p_win->i_height = xevent.xconfigure.height;
1653         }
1654     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1655
1656     XSelectInput( p_vout->p_sys->p_display, p_win->base_window,
1657                   StructureNotifyMask | KeyPressMask |
1658                   ButtonPressMask | ButtonReleaseMask |
1659                   PointerMotionMask );
1660
1661 #ifdef MODULE_NAME_IS_x11
1662     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1663     {
1664         /* Allocate a new palette */
1665         p_vout->p_sys->colormap =
1666             XCreateColormap( p_vout->p_sys->p_display,
1667                              DefaultRootWindow( p_vout->p_sys->p_display ),
1668                              DefaultVisual( p_vout->p_sys->p_display,
1669                                             p_vout->p_sys->i_screen ),
1670                              AllocAll );
1671
1672         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1673         XChangeWindowAttributes( p_vout->p_sys->p_display, p_win->base_window,
1674                                  CWColormap, &xwindow_attributes );
1675     }
1676 #endif
1677
1678     /* Create video output sub-window. */
1679     p_win->video_window =  XCreateSimpleWindow(
1680                                       p_vout->p_sys->p_display,
1681                                       p_win->base_window, 0, 0,
1682                                       p_win->i_width, p_win->i_height,
1683                                       0,
1684                                       BlackPixel( p_vout->p_sys->p_display,
1685                                                   p_vout->p_sys->i_screen ),
1686                                       WhitePixel( p_vout->p_sys->p_display,
1687                                                   p_vout->p_sys->i_screen ) );
1688
1689     XSetWindowBackground( p_vout->p_sys->p_display, p_win->video_window,
1690                           BlackPixel( p_vout->p_sys->p_display,
1691                                       p_vout->p_sys->i_screen ) );
1692
1693     XMapWindow( p_vout->p_sys->p_display, p_win->video_window );
1694     XSelectInput( p_vout->p_sys->p_display, p_win->video_window,
1695                   ExposureMask );
1696
1697     /* make sure the video window will be centered in the next ManageVideo() */
1698     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1699
1700     /* If the cursor was formerly blank than blank it again */
1701     if( !p_vout->p_sys->b_mouse_pointer_visible )
1702     {
1703         ToggleCursor( p_vout );
1704         ToggleCursor( p_vout );
1705     }
1706
1707     /* Do NOT use XFlush here ! */
1708     XSync( p_vout->p_sys->p_display, False );
1709
1710     /* At this stage, the window is open, displayed, and ready to
1711      * receive data */
1712     p_vout->p_sys->p_win = p_win;
1713
1714     return VLC_SUCCESS;
1715 }
1716
1717 /*****************************************************************************
1718  * DestroyWindow: destroy the window
1719  *****************************************************************************
1720  *
1721  *****************************************************************************/
1722 static void DestroyWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1723 {
1724     /* Do NOT use XFlush here ! */
1725     XSync( p_vout->p_sys->p_display, False );
1726
1727     if( p_win->video_window != None )
1728         XDestroyWindow( p_vout->p_sys->p_display, p_win->video_window );
1729
1730     XFreeGC( p_vout->p_sys->p_display, p_win->gc );
1731
1732     XUnmapWindow( p_vout->p_sys->p_display, p_win->base_window );
1733     XDestroyWindow( p_vout->p_sys->p_display, p_win->base_window );
1734
1735     if( p_win->owner_window )
1736         vout_ReleaseWindow( p_vout, (void *)p_win->owner_window );
1737 }
1738
1739 /*****************************************************************************
1740  * NewPicture: allocate a picture
1741  *****************************************************************************
1742  * Returns 0 on success, -1 otherwise
1743  *****************************************************************************/
1744 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1745 {
1746 #ifndef MODULE_NAME_IS_glx
1747
1748 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1749     int i_plane;
1750 #endif
1751
1752     /* We know the chroma, allocate a buffer which will be used
1753      * directly by the decoder */
1754     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1755
1756     if( p_pic->p_sys == NULL )
1757     {
1758         return -1;
1759     }
1760
1761 #ifdef MODULE_NAME_IS_xvmc
1762     p_pic->p_sys->p_vout = p_vout;
1763     p_pic->p_sys->xvmc_surf = NULL;
1764     p_pic->p_sys->xxmc_data.decoded = 0;
1765     p_pic->p_sys->xxmc_data.proc_xxmc_update_frame = xxmc_do_update_frame;
1766     p_pic->p_accel_data = &p_pic->p_sys->xxmc_data;
1767     p_pic->p_sys->nb_display = 0;
1768 #endif
1769
1770     /* Fill in picture_t fields */
1771     vout_InitPicture( VLC_OBJECT(p_vout), p_pic, p_vout->output.i_chroma,
1772                       p_vout->output.i_width, p_vout->output.i_height,
1773                       p_vout->output.i_aspect );
1774
1775 #ifdef HAVE_SYS_SHM_H
1776     if( p_vout->p_sys->b_shm )
1777     {
1778         /* Create image using XShm extension */
1779         p_pic->p_sys->p_image =
1780             CreateShmImage( p_vout, p_vout->p_sys->p_display,
1781 #   if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1782                             p_vout->p_sys->i_xvport,
1783                             VLC2X11_FOURCC(p_vout->output.i_chroma),
1784 #   else
1785                             p_vout->p_sys->p_visual,
1786                             p_vout->p_sys->i_screen_depth,
1787 #   endif
1788                             &p_pic->p_sys->shminfo,
1789                             p_vout->output.i_width, p_vout->output.i_height );
1790     }
1791
1792     if( !p_vout->p_sys->b_shm || !p_pic->p_sys->p_image )
1793 #endif /* HAVE_SYS_SHM_H */
1794     {
1795         /* Create image without XShm extension */
1796         p_pic->p_sys->p_image =
1797             CreateImage( p_vout, p_vout->p_sys->p_display,
1798 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1799                          p_vout->p_sys->i_xvport, 
1800                          VLC2X11_FOURCC(p_vout->output.i_chroma),
1801                          p_pic->format.i_bits_per_pixel,
1802 #else
1803                          p_vout->p_sys->p_visual,
1804                          p_vout->p_sys->i_screen_depth,
1805                          p_vout->p_sys->i_bytes_per_pixel,
1806 #endif
1807                          p_vout->output.i_width, p_vout->output.i_height );
1808
1809 #ifdef HAVE_SYS_SHM_H
1810         if( p_pic->p_sys->p_image && p_vout->p_sys->b_shm )
1811         {
1812             msg_Warn( p_vout, "couldn't create SHM image, disabling SHM" );
1813             p_vout->p_sys->b_shm = VLC_FALSE;
1814         }
1815 #endif /* HAVE_SYS_SHM_H */
1816     }
1817
1818     if( p_pic->p_sys->p_image == NULL )
1819     {
1820         free( p_pic->p_sys );
1821         return -1;
1822     }
1823
1824     switch( p_vout->output.i_chroma )
1825     {
1826 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1827         case VLC_FOURCC('I','4','2','0'):
1828         case VLC_FOURCC('Y','V','1','2'):
1829         case VLC_FOURCC('Y','2','1','1'):
1830         case VLC_FOURCC('Y','U','Y','2'):
1831         case VLC_FOURCC('U','Y','V','Y'):
1832         case VLC_FOURCC('R','V','1','5'):
1833         case VLC_FOURCC('R','V','1','6'):
1834         case VLC_FOURCC('R','V','2','4'): /* Fixme: pixel pitch == 4 ? */
1835         case VLC_FOURCC('R','V','3','2'):
1836
1837             for( i_plane = 0; i_plane < p_pic->p_sys->p_image->num_planes;
1838                  i_plane++ )
1839             {
1840                 p_pic->p[i_plane].p_pixels = p_pic->p_sys->p_image->data
1841                     + p_pic->p_sys->p_image->offsets[i_plane];
1842                 p_pic->p[i_plane].i_pitch =
1843                     p_pic->p_sys->p_image->pitches[i_plane];
1844             }
1845             if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
1846             {
1847                 /* U and V inverted compared to I420
1848                  * Fixme: this should be handled by the vout core */
1849                 p_pic->U_PIXELS = p_pic->p_sys->p_image->data
1850                     + p_pic->p_sys->p_image->offsets[2];
1851                 p_pic->V_PIXELS = p_pic->p_sys->p_image->data
1852                     + p_pic->p_sys->p_image->offsets[1];
1853             }
1854             break;
1855
1856 #else
1857         case VLC_FOURCC('R','G','B','2'):
1858         case VLC_FOURCC('R','V','1','6'):
1859         case VLC_FOURCC('R','V','1','5'):
1860         case VLC_FOURCC('R','V','2','4'):
1861         case VLC_FOURCC('R','V','3','2'):
1862
1863             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
1864             p_pic->p->i_visible_lines = p_pic->p_sys->p_image->height;
1865             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1866                                   + p_pic->p_sys->p_image->xoffset;
1867             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
1868
1869             /* p_pic->p->i_pixel_pitch = 4 for RV24 but this should be set
1870              * properly by vout_InitPicture() */
1871             p_pic->p->i_visible_pitch = p_pic->p->i_pixel_pitch
1872                                          * p_pic->p_sys->p_image->width;
1873             break;
1874 #endif
1875
1876         default:
1877             /* Unknown chroma, tell the guy to get lost */
1878             IMAGE_FREE( p_pic->p_sys->p_image );
1879             free( p_pic->p_sys );
1880             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1881                      p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
1882             p_pic->i_planes = 0;
1883             return -1;
1884     }
1885
1886 #endif /* !MODULE_NAME_IS_glx */
1887
1888     return 0;
1889 }
1890
1891 /*****************************************************************************
1892  * FreePicture: destroy a picture allocated with NewPicture
1893  *****************************************************************************
1894  * Destroy XImage AND associated data. If using Shm, detach shared memory
1895  * segment from server and process, then free it. The XDestroyImage manpage
1896  * says that both the image structure _and_ the data pointed to by the
1897  * image structure are freed, so no need to free p_image->data.
1898  *****************************************************************************/
1899 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
1900 {
1901     /* The order of operations is correct */
1902 #ifdef HAVE_SYS_SHM_H
1903     if( p_vout->p_sys->b_shm )
1904     {
1905         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
1906         IMAGE_FREE( p_pic->p_sys->p_image );
1907
1908         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
1909         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
1910         {
1911             msg_Err( p_vout, "cannot detach shared memory (%s)",
1912                              strerror(errno) );
1913         }
1914     }
1915     else
1916 #endif
1917     {
1918         IMAGE_FREE( p_pic->p_sys->p_image );
1919     }
1920
1921 #ifdef MODULE_NAME_IS_xvmc
1922     if( p_pic->p_sys->xvmc_surf != NULL )
1923     {
1924         xxmc_xvmc_free_surface(p_vout , p_pic->p_sys->xvmc_surf);
1925         p_pic->p_sys->xvmc_surf = NULL;
1926     }
1927 #endif
1928
1929     /* Do NOT use XFlush here ! */
1930     XSync( p_vout->p_sys->p_display, False );
1931
1932     free( p_pic->p_sys );
1933 }
1934
1935 /*****************************************************************************
1936  * ToggleFullScreen: Enable or disable full screen mode
1937  *****************************************************************************
1938  * This function will switch between fullscreen and window mode.
1939  *****************************************************************************/
1940 static void ToggleFullScreen ( vout_thread_t *p_vout )
1941 {
1942     Atom prop;
1943     XEvent xevent;
1944     mwmhints_t mwmhints;
1945     XSetWindowAttributes attributes;
1946
1947 #ifdef HAVE_XINERAMA
1948     int i_d1, i_d2;
1949 #endif
1950
1951     p_vout->b_fullscreen = !p_vout->b_fullscreen;
1952
1953     if( p_vout->b_fullscreen )
1954     {
1955         msg_Dbg( p_vout, "entering fullscreen mode" );
1956
1957         p_vout->p_sys->b_altfullscreen =
1958             config_GetInt( p_vout, MODULE_STRING "-altfullscreen" );
1959
1960         XUnmapWindow( p_vout->p_sys->p_display,
1961                       p_vout->p_sys->p_win->base_window );
1962
1963         p_vout->p_sys->p_win = &p_vout->p_sys->fullscreen_window;
1964
1965         CreateWindow( p_vout, p_vout->p_sys->p_win );
1966         XDestroyWindow( p_vout->p_sys->p_display,
1967                         p_vout->p_sys->fullscreen_window.video_window );
1968         XReparentWindow( p_vout->p_sys->p_display,
1969                          p_vout->p_sys->original_window.video_window,
1970                          p_vout->p_sys->fullscreen_window.base_window, 0, 0 );
1971         p_vout->p_sys->fullscreen_window.video_window =
1972             p_vout->p_sys->original_window.video_window;
1973
1974         /* To my knowledge there are two ways to create a borderless window.
1975          * There's the generic way which is to tell x to bypass the window
1976          * manager, but this creates problems with the focus of other
1977          * applications.
1978          * The other way is to use the motif property "_MOTIF_WM_HINTS" which
1979          * luckily seems to be supported by most window managers. */
1980         if( !p_vout->p_sys->b_altfullscreen )
1981         {
1982             mwmhints.flags = MWM_HINTS_DECORATIONS;
1983             mwmhints.decorations = False;
1984
1985             prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1986                                 False );
1987             XChangeProperty( p_vout->p_sys->p_display,
1988                              p_vout->p_sys->p_win->base_window,
1989                              prop, prop, 32, PropModeReplace,
1990                              (unsigned char *)&mwmhints,
1991                              PROP_MWM_HINTS_ELEMENTS );
1992         }
1993         else
1994         {
1995             /* brute force way to remove decorations */
1996             attributes.override_redirect = True;
1997             XChangeWindowAttributes( p_vout->p_sys->p_display,
1998                                      p_vout->p_sys->p_win->base_window,
1999                                      CWOverrideRedirect,
2000                                      &attributes);
2001
2002             /* Make sure the change is effective */
2003             XReparentWindow( p_vout->p_sys->p_display,
2004                              p_vout->p_sys->p_win->base_window,
2005                              DefaultRootWindow( p_vout->p_sys->p_display ),
2006                              0, 0 );
2007         }
2008
2009         if( p_vout->p_sys->b_net_wm_state_fullscreen )
2010         {
2011             XClientMessageEvent event;
2012
2013             memset( &event, 0, sizeof( XClientMessageEvent ) );
2014
2015             event.type = ClientMessage;
2016             event.message_type = p_vout->p_sys->net_wm_state;
2017             event.display = p_vout->p_sys->p_display;
2018             event.window = p_vout->p_sys->p_win->base_window;
2019             event.format = 32;
2020             event.data.l[ 0 ] = 1; /* set property */
2021             event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_fullscreen;
2022
2023             XSendEvent( p_vout->p_sys->p_display,
2024                         DefaultRootWindow( p_vout->p_sys->p_display ),
2025                         False, SubstructureRedirectMask,
2026                         (XEvent*)&event );
2027         }
2028
2029         /* Make sure the change is effective */
2030         XReparentWindow( p_vout->p_sys->p_display,
2031                          p_vout->p_sys->p_win->base_window,
2032                          DefaultRootWindow( p_vout->p_sys->p_display ),
2033                          0, 0 );
2034
2035 #ifdef HAVE_XINERAMA
2036         if( XineramaQueryExtension( p_vout->p_sys->p_display, &i_d1, &i_d2 ) &&
2037             XineramaIsActive( p_vout->p_sys->p_display ) )
2038         {
2039             XineramaScreenInfo *screens;   /* infos for xinerama */
2040             int i_num_screens;
2041
2042             msg_Dbg( p_vout, "using XFree Xinerama extension");
2043
2044 #define SCREEN p_vout->p_sys->p_win->i_screen
2045
2046             /* Get Information about Xinerama (num of screens) */
2047             screens = XineramaQueryScreens( p_vout->p_sys->p_display,
2048                                             &i_num_screens );
2049
2050             SCREEN = config_GetInt( p_vout,
2051                                         MODULE_STRING "-xineramascreen" );
2052
2053             /* just check that user has entered a good value */
2054             if( SCREEN >= i_num_screens || SCREEN < 0 )
2055             {
2056                 msg_Dbg( p_vout, "requested screen number invalid (%d/%d)", SCREEN, i_num_screens );
2057                 SCREEN = 0;
2058             }
2059
2060             /* Get the X/Y upper left corner coordinate of the above screen */
2061             p_vout->p_sys->p_win->i_x = screens[SCREEN].x_org;
2062             p_vout->p_sys->p_win->i_y = screens[SCREEN].y_org;
2063
2064             /* Set the Height/width to the screen resolution */
2065             p_vout->p_sys->p_win->i_width = screens[SCREEN].width;
2066             p_vout->p_sys->p_win->i_height = screens[SCREEN].height;
2067
2068             XFree(screens);
2069
2070 #undef SCREEN
2071
2072         }
2073         else
2074 #endif
2075         {
2076             /* The window wasn't necessarily created at the requested size */
2077             p_vout->p_sys->p_win->i_x = p_vout->p_sys->p_win->i_y = 0;
2078
2079 #ifdef HAVE_XF86VIDMODE
2080             XF86VidModeModeLine mode;
2081             int i_dummy;
2082
2083             if( XF86VidModeGetModeLine( p_vout->p_sys->p_display,
2084                                         p_vout->p_sys->i_screen, &i_dummy,
2085                                         &mode ) )
2086             {
2087                 p_vout->p_sys->p_win->i_width = mode.hdisplay;
2088                 p_vout->p_sys->p_win->i_height = mode.vdisplay;
2089
2090                 /* move cursor to the middle of the window to prevent
2091                  * unwanted display move if the display is smaller than the
2092                  * full desktop */
2093                 XWarpPointer( p_vout->p_sys->p_display, None,
2094                               p_vout->p_sys->p_win->base_window, 0, 0, 0, 0,
2095                               mode.hdisplay / 2 , mode.vdisplay / 2 );
2096                 /* force desktop view to upper left corner */
2097                 XF86VidModeSetViewPort( p_vout->p_sys->p_display,
2098                                         p_vout->p_sys->i_screen, 0, 0 );
2099             }
2100             else
2101 #endif
2102             {
2103                 p_vout->p_sys->p_win->i_width =
2104                     DisplayWidth( p_vout->p_sys->p_display,
2105                                 p_vout->p_sys->i_screen );
2106                 p_vout->p_sys->p_win->i_height =
2107                     DisplayHeight( p_vout->p_sys->p_display,
2108                                 p_vout->p_sys->i_screen );
2109             }
2110
2111         }
2112
2113         XMoveResizeWindow( p_vout->p_sys->p_display,
2114                            p_vout->p_sys->p_win->base_window,
2115                            p_vout->p_sys->p_win->i_x,
2116                            p_vout->p_sys->p_win->i_y,
2117                            p_vout->p_sys->p_win->i_width,
2118                            p_vout->p_sys->p_win->i_height );
2119     }
2120     else
2121     {
2122         msg_Dbg( p_vout, "leaving fullscreen mode" );
2123
2124         XReparentWindow( p_vout->p_sys->p_display,
2125                          p_vout->p_sys->original_window.video_window,
2126                          p_vout->p_sys->original_window.base_window, 0, 0 );
2127
2128         p_vout->p_sys->fullscreen_window.video_window = None;
2129         DestroyWindow( p_vout, &p_vout->p_sys->fullscreen_window );
2130         p_vout->p_sys->p_win = &p_vout->p_sys->original_window;
2131
2132         XMapWindow( p_vout->p_sys->p_display,
2133                     p_vout->p_sys->p_win->base_window );
2134     }
2135
2136     /* Unfortunately, using XSync() here is not enough to ensure the
2137      * window has already been mapped because the XMapWindow() request
2138      * has not necessarily been sent directly to our window (remember,
2139      * the call is first redirected to the window manager) */
2140     do
2141     {
2142         XWindowEvent( p_vout->p_sys->p_display,
2143                       p_vout->p_sys->p_win->base_window,
2144                       StructureNotifyMask, &xevent );
2145     } while( xevent.type != MapNotify );
2146
2147     /* Be careful, this can generate a BadMatch error if the window is not
2148      * already mapped by the server (see above) */
2149     XSetInputFocus(p_vout->p_sys->p_display,
2150                    p_vout->p_sys->p_win->base_window,
2151                    RevertToParent,
2152                    CurrentTime);
2153
2154     /* signal that the size needs to be updated */
2155     p_vout->i_changes |= VOUT_SIZE_CHANGE;
2156 }
2157
2158 /*****************************************************************************
2159  * EnableXScreenSaver: enable screen saver
2160  *****************************************************************************
2161  * This function enables the screen saver on a display after it has been
2162  * disabled by XDisableScreenSaver.
2163  * FIXME: what happens if multiple vlc sessions are running at the same
2164  *        time ???
2165  *****************************************************************************/
2166 static void EnableXScreenSaver( vout_thread_t *p_vout )
2167 {
2168 #ifdef DPMSINFO_IN_DPMS_H
2169     int dummy;
2170 #endif
2171
2172     if( p_vout->p_sys->i_ss_timeout )
2173     {
2174         XSetScreenSaver( 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
2180     /* Restore DPMS settings */
2181 #ifdef DPMSINFO_IN_DPMS_H
2182     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2183     {
2184         if( p_vout->p_sys->b_ss_dpms )
2185         {
2186             DPMSEnable( p_vout->p_sys->p_display );
2187         }
2188     }
2189 #endif
2190 }
2191
2192 /*****************************************************************************
2193  * DisableXScreenSaver: disable screen saver
2194  *****************************************************************************
2195  * See XEnableXScreenSaver
2196  *****************************************************************************/
2197 static void DisableXScreenSaver( vout_thread_t *p_vout )
2198 {
2199 #ifdef DPMSINFO_IN_DPMS_H
2200     int dummy;
2201 #endif
2202
2203     /* Save screen saver information */
2204     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
2205                      &p_vout->p_sys->i_ss_interval,
2206                      &p_vout->p_sys->i_ss_blanking,
2207                      &p_vout->p_sys->i_ss_exposure );
2208
2209     /* Disable screen saver */
2210     if( p_vout->p_sys->i_ss_timeout )
2211     {
2212         XSetScreenSaver( p_vout->p_sys->p_display, 0,
2213                          p_vout->p_sys->i_ss_interval,
2214                          p_vout->p_sys->i_ss_blanking,
2215                          p_vout->p_sys->i_ss_exposure );
2216     }
2217
2218     /* Disable DPMS */
2219 #ifdef DPMSINFO_IN_DPMS_H
2220     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2221     {
2222         CARD16 unused;
2223         /* Save DPMS current state */
2224         DPMSInfo( p_vout->p_sys->p_display, &unused,
2225                   &p_vout->p_sys->b_ss_dpms );
2226         DPMSDisable( p_vout->p_sys->p_display );
2227    }
2228 #endif
2229 }
2230
2231 /*****************************************************************************
2232  * CreateCursor: create a blank mouse pointer
2233  *****************************************************************************/
2234 static void CreateCursor( vout_thread_t *p_vout )
2235 {
2236     XColor cursor_color;
2237
2238     p_vout->p_sys->cursor_pixmap =
2239         XCreatePixmap( p_vout->p_sys->p_display,
2240                        DefaultRootWindow( p_vout->p_sys->p_display ),
2241                        1, 1, 1 );
2242
2243     XParseColor( p_vout->p_sys->p_display,
2244                  XCreateColormap( p_vout->p_sys->p_display,
2245                                   DefaultRootWindow(
2246                                                     p_vout->p_sys->p_display ),
2247                                   DefaultVisual(
2248                                                 p_vout->p_sys->p_display,
2249                                                 p_vout->p_sys->i_screen ),
2250                                   AllocNone ),
2251                  "black", &cursor_color );
2252
2253     p_vout->p_sys->blank_cursor =
2254         XCreatePixmapCursor( p_vout->p_sys->p_display,
2255                              p_vout->p_sys->cursor_pixmap,
2256                              p_vout->p_sys->cursor_pixmap,
2257                              &cursor_color, &cursor_color, 1, 1 );
2258 }
2259
2260 /*****************************************************************************
2261  * DestroyCursor: destroy the blank mouse pointer
2262  *****************************************************************************/
2263 static void DestroyCursor( vout_thread_t *p_vout )
2264 {
2265     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
2266 }
2267
2268 /*****************************************************************************
2269  * ToggleCursor: hide or show the mouse pointer
2270  *****************************************************************************
2271  * This function hides the X pointer if it is visible by setting the pointer
2272  * sprite to a blank one. To show it again, we disable the sprite.
2273  *****************************************************************************/
2274 static void ToggleCursor( vout_thread_t *p_vout )
2275 {
2276     if( p_vout->p_sys->b_mouse_pointer_visible )
2277     {
2278         XDefineCursor( p_vout->p_sys->p_display,
2279                        p_vout->p_sys->p_win->base_window,
2280                        p_vout->p_sys->blank_cursor );
2281         p_vout->p_sys->b_mouse_pointer_visible = 0;
2282     }
2283     else
2284     {
2285         XUndefineCursor( p_vout->p_sys->p_display,
2286                          p_vout->p_sys->p_win->base_window );
2287         p_vout->p_sys->b_mouse_pointer_visible = 1;
2288     }
2289 }
2290
2291 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
2292 /*****************************************************************************
2293  * XVideoGetPort: get YUV12 port
2294  *****************************************************************************/
2295 static int XVideoGetPort( vout_thread_t *p_vout,
2296                           vlc_fourcc_t i_chroma, vlc_fourcc_t *pi_newchroma )
2297 {
2298     XvAdaptorInfo *p_adaptor;
2299     unsigned int i;
2300     unsigned int i_adaptor, i_num_adaptors;
2301     int i_requested_adaptor;
2302     int i_selected_port;
2303
2304     switch( XvQueryExtension( p_vout->p_sys->p_display, &i, &i, &i, &i, &i ) )
2305     {
2306         case Success:
2307             break;
2308
2309         case XvBadExtension:
2310             msg_Warn( p_vout, "XvBadExtension" );
2311             return -1;
2312
2313         case XvBadAlloc:
2314             msg_Warn( p_vout, "XvBadAlloc" );
2315             return -1;
2316
2317         default:
2318             msg_Warn( p_vout, "XvQueryExtension failed" );
2319             return -1;
2320     }
2321
2322     switch( XvQueryAdaptors( p_vout->p_sys->p_display,
2323                              DefaultRootWindow( p_vout->p_sys->p_display ),
2324                              &i_num_adaptors, &p_adaptor ) )
2325     {
2326         case Success:
2327             break;
2328
2329         case XvBadExtension:
2330             msg_Warn( p_vout, "XvBadExtension for XvQueryAdaptors" );
2331             return -1;
2332
2333         case XvBadAlloc:
2334             msg_Warn( p_vout, "XvBadAlloc for XvQueryAdaptors" );
2335             return -1;
2336
2337         default:
2338             msg_Warn( p_vout, "XvQueryAdaptors failed" );
2339             return -1;
2340     }
2341
2342     i_selected_port = -1;
2343 #ifdef MODULE_NAME_IS_xvmc
2344     i_requested_adaptor = config_GetInt( p_vout, "xvmc-adaptor" );
2345 #else
2346     i_requested_adaptor = config_GetInt( p_vout, "xvideo-adaptor" );
2347 #endif
2348     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
2349     {
2350         XvImageFormatValues *p_formats;
2351         int i_format, i_num_formats;
2352         int i_port;
2353
2354         /* If we requested an adaptor and it's not this one, we aren't
2355          * interested */
2356         if( i_requested_adaptor != -1 && ((int)i_adaptor != i_requested_adaptor) )
2357         {
2358             continue;
2359         }
2360
2361         /* If the adaptor doesn't have the required properties, skip it */
2362         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
2363             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
2364         {
2365             continue;
2366         }
2367
2368         /* Check that adaptor supports our requested format... */
2369         p_formats = XvListImageFormats( p_vout->p_sys->p_display,
2370                                         p_adaptor[i_adaptor].base_id,
2371                                         &i_num_formats );
2372
2373         for( i_format = 0;
2374              i_format < i_num_formats && ( i_selected_port == -1 );
2375              i_format++ )
2376         {
2377             XvAttribute     *p_attr;
2378             int             i_attr, i_num_attributes;
2379
2380             /* If this is not the format we want, or at least a
2381              * similar one, forget it */
2382             if( !vout_ChromaCmp( p_formats[ i_format ].id, i_chroma ) )
2383             {
2384                 continue;
2385             }
2386
2387             /* Look for the first available port supporting this format */
2388             for( i_port = p_adaptor[i_adaptor].base_id;
2389                  ( i_port < (int)(p_adaptor[i_adaptor].base_id
2390                                    + p_adaptor[i_adaptor].num_ports) )
2391                    && ( i_selected_port == -1 );
2392                  i_port++ )
2393             {
2394                 if( XvGrabPort( p_vout->p_sys->p_display, i_port, CurrentTime )
2395                      == Success )
2396                 {
2397                     i_selected_port = i_port;
2398                     *pi_newchroma = p_formats[ i_format ].id;
2399                 }
2400             }
2401
2402             /* If no free port was found, forget it */
2403             if( i_selected_port == -1 )
2404             {
2405                 continue;
2406             }
2407
2408             /* If we found a port, print information about it */
2409             msg_Dbg( p_vout, "adaptor %i, port %i, format 0x%x (%4.4s) %s",
2410                      i_adaptor, i_selected_port, p_formats[ i_format ].id,
2411                      (char *)&p_formats[ i_format ].id,
2412                      ( p_formats[ i_format ].format == XvPacked ) ?
2413                          "packed" : "planar" );
2414
2415             /* Make sure XV_AUTOPAINT_COLORKEY is set */
2416             p_attr = XvQueryPortAttributes( p_vout->p_sys->p_display,
2417                                             i_selected_port,
2418                                             &i_num_attributes );
2419
2420             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
2421             {
2422                 if( !strcmp( p_attr[i_attr].name, "XV_AUTOPAINT_COLORKEY" ) )
2423                 {
2424                     const Atom autopaint =
2425                         XInternAtom( p_vout->p_sys->p_display,
2426                                      "XV_AUTOPAINT_COLORKEY", False );
2427                     XvSetPortAttribute( p_vout->p_sys->p_display,
2428                                         i_selected_port, autopaint, 1 );
2429                     break;
2430                 }
2431             }
2432
2433             if( p_attr != NULL )
2434             {
2435                 XFree( p_attr );
2436             }
2437         }
2438
2439         if( p_formats != NULL )
2440         {
2441             XFree( p_formats );
2442         }
2443
2444     }
2445
2446     if( i_num_adaptors > 0 )
2447     {
2448         XvFreeAdaptorInfo( p_adaptor );
2449     }
2450
2451     if( i_selected_port == -1 )
2452     {
2453         int i_chroma_tmp = X112VLC_FOURCC( i_chroma );
2454         if( i_requested_adaptor == -1 )
2455         {
2456             msg_Warn( p_vout, "no free XVideo port found for format "
2457                       "0x%.8x (%4.4s)", i_chroma_tmp, (char*)&i_chroma_tmp );
2458         }
2459         else
2460         {
2461             msg_Warn( p_vout, "XVideo adaptor %i does not have a free "
2462                       "XVideo port for format 0x%.8x (%4.4s)",
2463                       i_requested_adaptor, i_chroma_tmp, (char*)&i_chroma_tmp );
2464         }
2465     }
2466
2467     return i_selected_port;
2468 }
2469
2470 /*****************************************************************************
2471  * XVideoReleasePort: release YUV12 port
2472  *****************************************************************************/
2473 static void XVideoReleasePort( vout_thread_t *p_vout, int i_port )
2474 {
2475     XvUngrabPort( p_vout->p_sys->p_display, i_port, CurrentTime );
2476 }
2477 #endif
2478
2479 /*****************************************************************************
2480  * InitDisplay: open and initialize X11 device
2481  *****************************************************************************
2482  * Create a window according to video output given size, and set other
2483  * properties according to the display properties.
2484  *****************************************************************************/
2485 static int InitDisplay( vout_thread_t *p_vout )
2486 {
2487 #ifdef MODULE_NAME_IS_x11
2488     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
2489     XVisualInfo *               p_xvisual;            /* visuals information */
2490     XVisualInfo                 xvisual_template;         /* visual template */
2491     int                         i_count, i;                    /* array size */
2492 #endif
2493
2494 #ifdef HAVE_SYS_SHM_H
2495     p_vout->p_sys->b_shm = 0;
2496
2497     if( config_GetInt( p_vout, MODULE_STRING "-shm" ) )
2498     {
2499 #   ifdef __APPLE__
2500         /* FIXME: As of 2001-03-16, XFree4 for MacOS X does not support Xshm */
2501 #   else
2502         p_vout->p_sys->b_shm =
2503                   ( XShmQueryExtension( p_vout->p_sys->p_display ) == True );
2504 #   endif
2505
2506         if( !p_vout->p_sys->b_shm )
2507         {
2508             msg_Warn( p_vout, "XShm video extension is unavailable" );
2509         }
2510     }
2511     else
2512     {
2513         msg_Dbg( p_vout, "disabling XShm video extension" );
2514     }
2515
2516 #else
2517     msg_Warn( p_vout, "XShm video extension is unavailable" );
2518
2519 #endif
2520
2521 #ifdef MODULE_NAME_IS_xvideo
2522     /* XXX The brightness and contrast values should be read from environment
2523      * XXX variables... */
2524 #if 0
2525     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
2526     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
2527 #endif
2528 #endif
2529
2530 #ifdef MODULE_NAME_IS_x11
2531     /* Initialize structure */
2532     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
2533
2534     /* Get screen depth */
2535     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
2536                                                    p_vout->p_sys->i_screen );
2537     switch( p_vout->p_sys->i_screen_depth )
2538     {
2539     case 8:
2540         /*
2541          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
2542          */
2543         xvisual_template.screen =   p_vout->p_sys->i_screen;
2544         xvisual_template.class =    DirectColor;
2545         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2546                                     VisualScreenMask | VisualClassMask,
2547                                     &xvisual_template, &i_count );
2548         if( p_xvisual == NULL )
2549         {
2550             msg_Err( p_vout, "no PseudoColor visual available" );
2551             return VLC_EGENERIC;
2552         }
2553         p_vout->p_sys->i_bytes_per_pixel = 1;
2554         p_vout->output.pf_setpalette = SetPalette;
2555         break;
2556     case 15:
2557     case 16:
2558     case 24:
2559     default:
2560         /*
2561          * Screen depth is higher than 8bpp. TrueColor visual is used.
2562          */
2563         xvisual_template.screen =   p_vout->p_sys->i_screen;
2564         xvisual_template.class =    TrueColor;
2565 /* In some cases, we get a truecolor class adaptor that has a different
2566    color depth. So try to get a real true color one first */
2567         xvisual_template.depth =    p_vout->p_sys->i_screen_depth;
2568
2569         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2570                                     VisualScreenMask | VisualClassMask |
2571                                     VisualDepthMask,
2572                                     &xvisual_template, &i_count );
2573         if( p_xvisual == NULL )
2574         {
2575             msg_Warn( p_vout, "No screen matching the required color depth" );
2576             p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2577                                     VisualScreenMask | VisualClassMask,
2578                                     &xvisual_template, &i_count );
2579             if( p_xvisual == NULL )
2580             {
2581
2582                 msg_Err( p_vout, "no TrueColor visual available" );
2583                 return VLC_EGENERIC;
2584             }
2585         }
2586
2587         p_vout->output.i_rmask = p_xvisual->red_mask;
2588         p_vout->output.i_gmask = p_xvisual->green_mask;
2589         p_vout->output.i_bmask = p_xvisual->blue_mask;
2590
2591         /* There is no difference yet between 3 and 4 Bpp. The only way
2592          * to find the actual number of bytes per pixel is to list supported
2593          * pixmap formats. */
2594         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
2595         p_vout->p_sys->i_bytes_per_pixel = 0;
2596
2597         for( i = 0; i < i_count; i++ )
2598         {
2599             /* Under XFree4.0, the list contains pixmap formats available
2600              * through all video depths ; so we have to check against current
2601              * depth. */
2602             if( p_formats[i].depth == (int)p_vout->p_sys->i_screen_depth )
2603             {
2604                 if( p_formats[i].bits_per_pixel / 8
2605                         > (int)p_vout->p_sys->i_bytes_per_pixel )
2606                 {
2607                     p_vout->p_sys->i_bytes_per_pixel =
2608                         p_formats[i].bits_per_pixel / 8;
2609                 }
2610             }
2611         }
2612         if( p_formats ) XFree( p_formats );
2613
2614         break;
2615     }
2616     p_vout->p_sys->p_visual = p_xvisual->visual;
2617     XFree( p_xvisual );
2618 #endif
2619
2620     return VLC_SUCCESS;
2621 }
2622
2623 #ifdef HAVE_SYS_SHM_H
2624 /*****************************************************************************
2625  * CreateShmImage: create an XImage or XvImage using shared memory extension
2626  *****************************************************************************
2627  * Prepare an XImage or XvImage for display function.
2628  * The order of the operations respects the recommandations of the mit-shm
2629  * document by J.Corbet and K.Packard. Most of the parameters were copied from
2630  * there. See http://ftp.xfree86.org/pub/XFree86/4.0/doc/mit-shm.TXT
2631  *****************************************************************************/
2632 static IMAGE_TYPE * CreateShmImage( vout_thread_t *p_vout,
2633                                     Display* p_display, EXTRA_ARGS_SHM,
2634                                     int i_width, int i_height )
2635 {
2636     IMAGE_TYPE *p_image;
2637     Status result;
2638
2639     /* Create XImage / XvImage */
2640 #ifdef MODULE_NAME_IS_xvideo
2641
2642     /* Make sure the buffer is aligned to multiple of 16 */
2643     i_height = ( i_height + 15 ) >> 4 << 4;
2644     i_width = ( i_width + 15 ) >> 4 << 4;
2645
2646     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2647                                 i_width, i_height, p_shm );
2648 #elif defined(MODULE_NAME_IS_xvmc)
2649     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2650                                 i_width, i_height, p_shm );
2651 #else
2652     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2653                                p_shm, i_width, i_height );
2654 #endif
2655     if( p_image == NULL )
2656     {
2657         msg_Err( p_vout, "image creation failed" );
2658         return NULL;
2659     }
2660
2661     /* Allocate shared memory segment - 0776 set the access permission
2662      * rights (like umask), they are not yet supported by all X servers */
2663     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE(p_image), IPC_CREAT | 0776 );
2664     if( p_shm->shmid < 0 )
2665     {
2666         msg_Err( p_vout, "cannot allocate shared image data (%s)",
2667                          strerror( errno ) );
2668         IMAGE_FREE( p_image );
2669         return NULL;
2670     }
2671
2672     /* Attach shared memory segment to process (read/write) */
2673     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
2674     if(! p_shm->shmaddr )
2675     {
2676         msg_Err( p_vout, "cannot attach shared memory (%s)",
2677                          strerror(errno));
2678         IMAGE_FREE( p_image );
2679         shmctl( p_shm->shmid, IPC_RMID, 0 );
2680         return NULL;
2681     }
2682
2683     /* Read-only data. We won't be using XShmGetImage */
2684     p_shm->readOnly = True;
2685
2686     /* Attach shared memory segment to X server */
2687     XSynchronize( p_display, True );
2688     b_shm = VLC_TRUE;
2689     result = XShmAttach( p_display, p_shm );
2690     if( result == False || !b_shm )
2691     {
2692         msg_Err( p_vout, "cannot attach shared memory to X server" );
2693         IMAGE_FREE( p_image );
2694         shmctl( p_shm->shmid, IPC_RMID, 0 );
2695         shmdt( p_shm->shmaddr );
2696         return NULL;
2697     }
2698     XSynchronize( p_display, False );
2699
2700     /* Send image to X server. This instruction is required, since having
2701      * built a Shm XImage and not using it causes an error on XCloseDisplay,
2702      * and remember NOT to use XFlush ! */
2703     XSync( p_display, False );
2704
2705 #if 0
2706     /* Mark the shm segment to be removed when there are no more
2707      * attachements, so it is automatic on process exit or after shmdt */
2708     shmctl( p_shm->shmid, IPC_RMID, 0 );
2709 #endif
2710
2711     return p_image;
2712 }
2713 #endif
2714
2715 /*****************************************************************************
2716  * CreateImage: create an XImage or XvImage
2717  *****************************************************************************
2718  * Create a simple image used as a buffer.
2719  *****************************************************************************/
2720 static IMAGE_TYPE * CreateImage( vout_thread_t *p_vout,
2721                                  Display *p_display, EXTRA_ARGS,
2722                                  int i_width, int i_height )
2723 {
2724     byte_t *    p_data;                           /* image data storage zone */
2725     IMAGE_TYPE *p_image;
2726 #ifdef MODULE_NAME_IS_x11
2727     int         i_quantum;                     /* XImage quantum (see below) */
2728     int         i_bytes_per_line;
2729 #endif
2730
2731     /* Allocate memory for image */
2732 #ifdef MODULE_NAME_IS_xvideo
2733
2734     /* Make sure the buffer is aligned to multiple of 16 */
2735     i_height = ( i_height + 15 ) >> 4 << 4;
2736     i_width = ( i_width + 15 ) >> 4 << 4;
2737
2738     p_data = (byte_t *) malloc( i_width * i_height * i_bits_per_pixel / 8 );
2739 #elif defined(MODULE_NAME_IS_x11)
2740     i_bytes_per_line = i_width * i_bytes_per_pixel;
2741     p_data = (byte_t *) malloc( i_bytes_per_line * i_height );
2742 #endif
2743     if( !p_data )
2744     {
2745         msg_Err( p_vout, "out of memory" );
2746         return NULL;
2747     }
2748
2749 #ifdef MODULE_NAME_IS_x11
2750     /* Optimize the quantum of a scanline regarding its size - the quantum is
2751        a diviser of the number of bits between the start of two scanlines. */
2752     if( i_bytes_per_line & 0xf )
2753     {
2754         i_quantum = 0x8;
2755     }
2756     else if( i_bytes_per_line & 0x10 )
2757     {
2758         i_quantum = 0x10;
2759     }
2760     else
2761     {
2762         i_quantum = 0x20;
2763     }
2764 #endif
2765
2766     /* Create XImage. p_data will be automatically freed */
2767 #ifdef MODULE_NAME_IS_xvideo
2768     p_image = XvCreateImage( p_display, i_xvport, i_chroma,
2769                              (char *)p_data, i_width, i_height );
2770 #elif defined(MODULE_NAME_IS_x11)
2771     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2772                             (char *)p_data, i_width, i_height, i_quantum, 0 );
2773 #endif
2774     if( p_image == NULL )
2775     {
2776         msg_Err( p_vout, "XCreateImage() failed" );
2777         free( p_data );
2778         return NULL;
2779     }
2780
2781     return p_image;
2782 }
2783
2784 /*****************************************************************************
2785  * X11ErrorHandler: replace error handler so we can intercept some of them
2786  *****************************************************************************/
2787 static int X11ErrorHandler( Display * display, XErrorEvent * event )
2788 {
2789     /* Ingnore errors on XSetInputFocus()
2790      * (they happen when a window is not yet mapped) */
2791     if( event->request_code == X_SetInputFocus )
2792     {
2793         fprintf(stderr, "XSetInputFocus failed\n");
2794         return 0;
2795     }
2796
2797     if( event->request_code == 150 /* MIT-SHM */ &&
2798         event->minor_code == X_ShmAttach )
2799     {
2800         fprintf(stderr, "XShmAttach failed\n");
2801         b_shm = VLC_FALSE;
2802         return 0;
2803     }
2804
2805     XSetErrorHandler(NULL);
2806     return (XSetErrorHandler(X11ErrorHandler))( display, event );
2807 }
2808
2809 #ifdef MODULE_NAME_IS_x11
2810 /*****************************************************************************
2811  * SetPalette: sets an 8 bpp palette
2812  *****************************************************************************
2813  * This function sets the palette given as an argument. It does not return
2814  * anything, but could later send information on which colors it was unable
2815  * to set.
2816  *****************************************************************************/
2817 static void SetPalette( vout_thread_t *p_vout,
2818                         uint16_t *red, uint16_t *green, uint16_t *blue )
2819 {
2820     int i;
2821     XColor p_colors[255];
2822
2823     /* allocate palette */
2824     for( i = 0; i < 255; i++ )
2825     {
2826         /* kludge: colors are indexed reversely because color 255 seems
2827          * to be reserved for black even if we try to set it to white */
2828         p_colors[ i ].pixel = 255 - i;
2829         p_colors[ i ].pad   = 0;
2830         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
2831         p_colors[ i ].red   = red[ 255 - i ];
2832         p_colors[ i ].blue  = blue[ 255 - i ];
2833         p_colors[ i ].green = green[ 255 - i ];
2834     }
2835
2836     XStoreColors( p_vout->p_sys->p_display,
2837                   p_vout->p_sys->colormap, p_colors, 255 );
2838 }
2839 #endif
2840
2841 /*****************************************************************************
2842  * Control: control facility for the vout
2843  *****************************************************************************/
2844 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
2845 {
2846     vlc_bool_t b_arg;
2847     unsigned int i_width, i_height;
2848     unsigned int *pi_width, *pi_height;
2849     Drawable d = 0;
2850
2851     switch( i_query )
2852     {
2853         case VOUT_GET_SIZE:
2854             if( p_vout->p_sys->p_win->owner_window )
2855                 return vout_ControlWindow( p_vout,
2856                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2857
2858             pi_width  = va_arg( args, unsigned int * );
2859             pi_height = va_arg( args, unsigned int * );
2860
2861             vlc_mutex_lock( &p_vout->p_sys->lock );
2862             *pi_width  = p_vout->p_sys->p_win->i_width;
2863             *pi_height = p_vout->p_sys->p_win->i_height;
2864             vlc_mutex_unlock( &p_vout->p_sys->lock );
2865             return VLC_SUCCESS;
2866
2867         case VOUT_SET_SIZE:
2868             if( p_vout->p_sys->p_win->owner_window )
2869                 return vout_ControlWindow( p_vout,
2870                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2871
2872             vlc_mutex_lock( &p_vout->p_sys->lock );
2873
2874             i_width  = va_arg( args, unsigned int );
2875             i_height = va_arg( args, unsigned int );
2876             if( !i_width ) i_width = p_vout->i_window_width;
2877             if( !i_height ) i_height = p_vout->i_window_height;
2878
2879 #ifdef MODULE_NAME_IS_xvmc
2880             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
2881 #endif
2882             /* Update dimensions */
2883             XResizeWindow( p_vout->p_sys->p_display,
2884                            p_vout->p_sys->p_win->base_window,
2885                            i_width, i_height );
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 VLC_SUCCESS;
2891
2892        case VOUT_CLOSE:
2893             vlc_mutex_lock( &p_vout->p_sys->lock );
2894             XUnmapWindow( p_vout->p_sys->p_display,
2895                           p_vout->p_sys->original_window.base_window );
2896             vlc_mutex_unlock( &p_vout->p_sys->lock );
2897             /* Fall through */
2898
2899        case VOUT_REPARENT:
2900             vlc_mutex_lock( &p_vout->p_sys->lock );
2901             if( i_query == VOUT_REPARENT ) d = (Drawable)va_arg( args, int );
2902             if( !d )
2903 #ifdef MODULE_NAME_IS_xvmc
2904             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
2905 #endif
2906             XReparentWindow( p_vout->p_sys->p_display,
2907                              p_vout->p_sys->original_window.base_window,
2908                              DefaultRootWindow( p_vout->p_sys->p_display ),
2909                              0, 0 );
2910             else
2911             XReparentWindow( p_vout->p_sys->p_display,
2912                              p_vout->p_sys->original_window.base_window,
2913                              d, 0, 0);
2914             XSync( p_vout->p_sys->p_display, False );
2915             p_vout->p_sys->original_window.owner_window = 0;
2916 #ifdef MODULE_NAME_IS_xvmc
2917             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
2918 #endif
2919             vlc_mutex_unlock( &p_vout->p_sys->lock );
2920             return vout_vaControlDefault( p_vout, i_query, args );
2921
2922         case VOUT_SET_STAY_ON_TOP:
2923             if( p_vout->p_sys->p_win->owner_window )
2924                 return vout_ControlWindow( p_vout,
2925                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
2926
2927             b_arg = va_arg( args, vlc_bool_t );
2928             vlc_mutex_lock( &p_vout->p_sys->lock );
2929 #ifdef MODULE_NAME_IS_xvmc
2930             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
2931 #endif
2932             WindowOnTop( p_vout, b_arg );
2933 #ifdef MODULE_NAME_IS_xvmc
2934             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
2935 #endif
2936             vlc_mutex_unlock( &p_vout->p_sys->lock );
2937             return VLC_SUCCESS;
2938
2939        default:
2940             return vout_vaControlDefault( p_vout, i_query, args );
2941     }
2942 }
2943
2944 /*****************************************************************************
2945  * TestNetWMSupport: tests for Extended Window Manager Hints support
2946  *****************************************************************************/
2947 static void TestNetWMSupport( vout_thread_t *p_vout )
2948 {
2949     int i_ret, i_format;
2950     unsigned long i, i_items, i_bytesafter;
2951     Atom net_wm_supported;
2952     union { Atom *p_atom; unsigned char *p_char; } p_args;
2953
2954     p_args.p_atom = NULL;
2955
2956     p_vout->p_sys->b_net_wm_state_fullscreen = VLC_FALSE;
2957     p_vout->p_sys->b_net_wm_state_above = VLC_FALSE;
2958     p_vout->p_sys->b_net_wm_state_below = VLC_FALSE;
2959     p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_FALSE;
2960
2961     net_wm_supported =
2962         XInternAtom( p_vout->p_sys->p_display, "_NET_SUPPORTED", False );
2963
2964     i_ret = XGetWindowProperty( p_vout->p_sys->p_display,
2965                                 DefaultRootWindow( p_vout->p_sys->p_display ),
2966                                 net_wm_supported,
2967                                 0, 16384, False, AnyPropertyType,
2968                                 &net_wm_supported,
2969                                 &i_format, &i_items, &i_bytesafter,
2970                                 (unsigned char **)&p_args );
2971
2972     if( i_ret != Success || i_items == 0 ) return;
2973
2974     msg_Dbg( p_vout, "Window manager supports NetWM" );
2975
2976     p_vout->p_sys->net_wm_state =
2977         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE", False );
2978     p_vout->p_sys->net_wm_state_fullscreen =
2979         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_FULLSCREEN",
2980                      False );
2981     p_vout->p_sys->net_wm_state_above =
2982         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_ABOVE", False );
2983     p_vout->p_sys->net_wm_state_below =
2984         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_BELOW", False );
2985     p_vout->p_sys->net_wm_state_stays_on_top =
2986         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_STAYS_ON_TOP",
2987                      False );
2988
2989     for( i = 0; i < i_items; i++ )
2990     {
2991         if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_fullscreen )
2992         {
2993             msg_Dbg( p_vout,
2994                      "Window manager supports _NET_WM_STATE_FULLSCREEN" );
2995             p_vout->p_sys->b_net_wm_state_fullscreen = VLC_TRUE;
2996         }
2997         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_above )
2998         {
2999             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_ABOVE" );
3000             p_vout->p_sys->b_net_wm_state_above = VLC_TRUE;
3001         }
3002         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_below )
3003         {
3004             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_BELOW" );
3005             p_vout->p_sys->b_net_wm_state_below = VLC_TRUE;
3006         }
3007         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_stays_on_top )
3008         {
3009             msg_Dbg( p_vout,
3010                      "Window manager supports _NET_WM_STATE_STAYS_ON_TOP" );
3011             p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_TRUE;
3012         }
3013     }
3014
3015     XFree( p_args.p_atom );
3016 }
3017
3018 /*****************************************************************************
3019  * Key events handling
3020  *****************************************************************************/
3021 static struct
3022 {
3023     int i_x11key;
3024     int i_vlckey;
3025
3026 } x11keys_to_vlckeys[] =
3027 {
3028     { XK_F1, KEY_F1 }, { XK_F2, KEY_F2 }, { XK_F3, KEY_F3 }, { XK_F4, KEY_F4 },
3029     { XK_F5, KEY_F5 }, { XK_F6, KEY_F6 }, { XK_F7, KEY_F7 }, { XK_F8, KEY_F8 },
3030     { XK_F9, KEY_F9 }, { XK_F10, KEY_F10 }, { XK_F11, KEY_F11 },
3031     { XK_F12, KEY_F12 },
3032
3033     { XK_Return, KEY_ENTER },
3034     { XK_KP_Enter, KEY_ENTER },
3035     { XK_space, KEY_SPACE },
3036     { XK_Escape, KEY_ESC },
3037
3038     { XK_Menu, KEY_MENU },
3039     { XK_Left, KEY_LEFT },
3040     { XK_Right, KEY_RIGHT },
3041     { XK_Up, KEY_UP },
3042     { XK_Down, KEY_DOWN },
3043
3044     { XK_Home, KEY_HOME },
3045     { XK_End, KEY_END },
3046     { XK_Page_Up, KEY_PAGEUP },
3047     { XK_Page_Down, KEY_PAGEDOWN },
3048
3049     { XK_Insert, KEY_INSERT },
3050     { XK_Delete, KEY_DELETE },
3051
3052     { 0, 0 }
3053 };
3054
3055 static int ConvertKey( int i_key )
3056 {
3057     int i;
3058
3059     for( i = 0; x11keys_to_vlckeys[i].i_x11key != 0; i++ )
3060     {
3061         if( x11keys_to_vlckeys[i].i_x11key == i_key )
3062         {
3063             return x11keys_to_vlckeys[i].i_vlckey;
3064         }
3065     }
3066
3067     return 0;
3068 }
3069
3070 /*****************************************************************************
3071  * WindowOnTop: Switches the "always on top" state of the video window.
3072  *****************************************************************************/
3073 static int WindowOnTop( vout_thread_t *p_vout, vlc_bool_t b_on_top )
3074 {
3075     if( p_vout->p_sys->b_net_wm_state_stays_on_top )
3076     {
3077         XClientMessageEvent event;
3078
3079         memset( &event, 0, sizeof( XClientMessageEvent ) );
3080
3081         event.type = ClientMessage;
3082         event.message_type = p_vout->p_sys->net_wm_state;
3083         event.display = p_vout->p_sys->p_display;
3084         event.window = p_vout->p_sys->p_win->base_window;
3085         event.format = 32;
3086         event.data.l[ 0 ] = b_on_top; /* set property */
3087         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_stays_on_top;
3088
3089         XSendEvent( p_vout->p_sys->p_display,
3090                     DefaultRootWindow( p_vout->p_sys->p_display ),
3091                     False, SubstructureRedirectMask,
3092                     (XEvent*)&event );
3093     }
3094
3095     /* use _NET_WM_STATE_ABOVE if window manager
3096      * doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
3097     else if( p_vout->p_sys->b_net_wm_state_above )
3098     {
3099         XClientMessageEvent event;
3100
3101         memset( &event, 0, sizeof( XClientMessageEvent ) );
3102
3103         event.type = ClientMessage;
3104         event.message_type = p_vout->p_sys->net_wm_state;
3105         event.display = p_vout->p_sys->p_display;
3106         event.window = p_vout->p_sys->p_win->base_window;
3107         event.format = 32;
3108         event.data.l[ 0 ] = b_on_top; /* set property */
3109         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_above;
3110
3111         XSendEvent( p_vout->p_sys->p_display,
3112                     DefaultRootWindow( p_vout->p_sys->p_display ),
3113                     False, SubstructureRedirectMask,
3114                     (XEvent*)&event );
3115     }
3116
3117     return VLC_SUCCESS;
3118 }