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