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