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