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