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