]> git.sesse.net Git - vlc/blob - modules/video_output/x11/xcommon.c
Do not touch the always-on-top when going fullscreen
[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/vlc.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, vlc_fourcc_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     {
210         msg_Err( p_vout, "out of memory" );
211         return VLC_ENOMEM;
212     }
213
214     vlc_mutex_init( &p_vout->p_sys->lock );
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.i_chroma );
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.i_chroma );
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.i_chroma );
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     switch( p_vout->output.i_chroma )
828     {
829         case VLC_FOURCC('R','V','1','6'):
830 #if defined( WORDS_BIGENDIAN )
831             p_vout->output.i_rmask = 0xf800;
832             p_vout->output.i_gmask = 0x07e0;
833             p_vout->output.i_bmask = 0x001f;
834 #else
835             p_vout->output.i_rmask = 0x001f;
836             p_vout->output.i_gmask = 0x07e0;
837             p_vout->output.i_bmask = 0xf800;
838 #endif
839             break;
840         case VLC_FOURCC('R','V','1','5'):
841 #if defined( WORDS_BIGENDIAN )
842             p_vout->output.i_rmask = 0x7c00;
843             p_vout->output.i_gmask = 0x03e0;
844             p_vout->output.i_bmask = 0x001f;
845 #else
846             p_vout->output.i_rmask = 0x001f;
847             p_vout->output.i_gmask = 0x03e0;
848             p_vout->output.i_bmask = 0x7c00;
849 #endif
850             break;
851     }
852
853 #elif defined(MODULE_NAME_IS_x11)
854     /* Initialize the output structure: RGB with square pixels, whatever
855      * the input format is, since it's the only format we know */
856     switch( p_vout->p_sys->i_screen_depth )
857     {
858         case 8: /* FIXME: set the palette */
859             p_vout->output.i_chroma = VLC_FOURCC('R','G','B','2'); break;
860         case 15:
861             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','5'); break;
862         case 16:
863             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','6'); break;
864         case 24:
865         case 32:
866             p_vout->output.i_chroma = VLC_FOURCC('R','V','3','2'); break;
867         default:
868             msg_Err( p_vout, "unknown screen depth %i",
869                      p_vout->p_sys->i_screen_depth );
870             return VLC_SUCCESS;
871     }
872
873 #ifdef HAVE_XSP
874     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width  / p_vout->p_sys->i_hw_scale,
875                        p_vout->p_sys->p_win->i_height  / p_vout->p_sys->i_hw_scale,
876                        &i_index, &i_index,
877                        &p_vout->fmt_out.i_visible_width,
878                        &p_vout->fmt_out.i_visible_height );
879 #else
880     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
881                        p_vout->p_sys->p_win->i_height,
882                        &i_index, &i_index,
883                        &p_vout->fmt_out.i_visible_width,
884                        &p_vout->fmt_out.i_visible_height );
885 #endif
886
887     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
888
889     p_vout->output.i_width = p_vout->fmt_out.i_width =
890         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_width /
891         p_vout->fmt_in.i_visible_width;
892     p_vout->output.i_height = p_vout->fmt_out.i_height =
893         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_height /
894         p_vout->fmt_in.i_visible_height;
895     p_vout->fmt_out.i_x_offset =
896         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_x_offset /
897         p_vout->fmt_in.i_visible_width;
898     p_vout->fmt_out.i_y_offset =
899         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_y_offset /
900         p_vout->fmt_in.i_visible_height;
901
902     p_vout->fmt_out.i_sar_num = p_vout->fmt_out.i_sar_den = 1;
903     p_vout->output.i_aspect = p_vout->fmt_out.i_aspect =
904         p_vout->fmt_out.i_width * VOUT_ASPECT_FACTOR /p_vout->fmt_out.i_height;
905
906     msg_Dbg( p_vout, "x11 image size %ix%i (%i,%i,%ix%i)",
907              p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
908              p_vout->fmt_out.i_x_offset, p_vout->fmt_out.i_y_offset,
909              p_vout->fmt_out.i_visible_width,
910              p_vout->fmt_out.i_visible_height );
911 #endif
912
913     /* Try to initialize up to MAX_DIRECTBUFFERS direct buffers */
914     while( I_OUTPUTPICTURES < MAX_DIRECTBUFFERS )
915     {
916         p_pic = NULL;
917
918         /* Find an empty picture slot */
919         for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
920         {
921           if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
922             {
923                 p_pic = p_vout->p_picture + i_index;
924                 break;
925             }
926         }
927
928         /* Allocate the picture */
929         if( p_pic == NULL || NewPicture( p_vout, p_pic ) )
930         {
931             break;
932         }
933
934         p_pic->i_status = DESTROYED_PICTURE;
935         p_pic->i_type   = DIRECT_PICTURE;
936
937         PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
938
939         I_OUTPUTPICTURES++;
940     }
941
942     if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
943     {
944         /* U and V inverted compared to I420
945          * Fixme: this should be handled by the vout core */
946         p_vout->output.i_chroma = VLC_FOURCC('I','4','2','0');
947         p_vout->fmt_out.i_chroma = VLC_FOURCC('I','4','2','0');
948     }
949
950     return VLC_SUCCESS;
951 }
952
953 /*****************************************************************************
954  * DisplayVideo: displays previously rendered output
955  *****************************************************************************
956  * This function sends the currently rendered image to X11 server.
957  * (The Xv extension takes care of "double-buffering".)
958  *****************************************************************************/
959 static void DisplayVideo( vout_thread_t *p_vout, picture_t *p_pic )
960 {
961     unsigned int i_width, i_height, i_x, i_y;
962
963     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
964                        p_vout->p_sys->p_win->i_height,
965                        &i_x, &i_y, &i_width, &i_height );
966
967     vlc_mutex_lock( &p_vout->p_sys->lock );
968
969 #ifdef MODULE_NAME_IS_xvmc
970     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
971
972     vlc_xxmc_t *xxmc = &p_pic->p_sys->xxmc_data;
973     if( !xxmc->decoded ||
974         !xxmc_xvmc_surface_valid( p_vout, p_pic->p_sys->xvmc_surf ) )
975     {
976       msg_Dbg( p_vout, "DisplayVideo decoded=%d\tsurfacevalid=%d",
977                xxmc->decoded,
978                xxmc_xvmc_surface_valid( p_vout, p_pic->p_sys->xvmc_surf ) );
979       vlc_mutex_unlock( &p_vout->p_sys->lock );
980       xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
981       return;
982     }
983
984     int src_width = p_vout->output.i_width;
985     int src_height = p_vout->output.i_height;
986     int src_x, src_y;
987
988     if( p_vout->p_sys->xvmc_crop_style == 1 )
989     {
990         src_x = 20;
991         src_y = 20;
992         src_width -= 40;
993         src_height -= 40;
994     }
995     else if( p_vout->p_sys->xvmc_crop_style == 2 )
996     {
997         src_x = 20;
998         src_y = 40;
999         src_width -= 40;
1000         src_height -= 80;
1001     }
1002     else if( p_vout->p_sys->xvmc_crop_style == 3 )
1003     {
1004         src_x = 40;
1005         src_y = 20;
1006         src_width -= 80;
1007         src_height -= 40;
1008     }
1009     else
1010     {
1011         src_x = 0;
1012         src_y = 0;
1013     }
1014
1015     int first_field;
1016     if( p_vout->p_sys->xvmc_deinterlace_method > 0 )
1017     {   /* BOB DEINTERLACE */
1018         if( (p_pic->p_sys->nb_display == 0) ||
1019             (p_vout->p_sys->xvmc_deinterlace_method == 1) )
1020         {
1021             first_field = (p_pic->b_top_field_first) ?
1022                                 XVMC_BOTTOM_FIELD : XVMC_TOP_FIELD;
1023         }
1024         else
1025         {
1026             first_field = (p_pic->b_top_field_first) ?
1027                                 XVMC_TOP_FIELD : XVMC_BOTTOM_FIELD;
1028         }
1029     }
1030     else
1031     {
1032         first_field = XVMC_FRAME_PICTURE;
1033      }
1034
1035     XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
1036     XvMCFlushSurface( p_vout->p_sys->p_display, p_pic->p_sys->xvmc_surf );
1037     /* XvMCSyncSurface(p_vout->p_sys->p_display, p_picture->p_sys->xvmc_surf); */
1038     XvMCPutSurface( p_vout->p_sys->p_display,
1039                     p_pic->p_sys->xvmc_surf,
1040                     p_vout->p_sys->p_win->video_window,
1041                     src_x,
1042                     src_y,
1043                     src_width,
1044                     src_height,
1045                     0 /*dest_x*/,
1046                     0 /*dest_y*/,
1047                     i_width,
1048                     i_height,
1049                     first_field);
1050
1051     XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
1052     if( p_vout->p_sys->xvmc_deinterlace_method == 2 )
1053     {   /* BOB DEINTERLACE */
1054         if( p_pic->p_sys->nb_display == 0 )/* && ((t2-t1) < 15000)) */
1055         {
1056             mtime_t last_date = p_pic->date;
1057
1058             vlc_mutex_lock( &p_vout->picture_lock );
1059             if( !p_vout->p_sys->last_date )
1060             {
1061                 p_pic->date += 20000;
1062             }
1063             else
1064             {
1065                 p_pic->date = ((3 * p_pic->date -
1066                                     p_vout->p_sys->last_date) / 2 );
1067             }
1068             p_vout->p_sys->last_date = last_date;
1069             p_pic->b_force = 1;
1070             p_pic->p_sys->nb_display = 1;
1071             vlc_mutex_unlock( &p_vout->picture_lock );
1072         }
1073         else
1074         {
1075             p_pic->p_sys->nb_display = 0;
1076             p_pic->b_force = 0;
1077         }
1078     }
1079     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1080 #endif
1081
1082 #ifdef HAVE_SYS_SHM_H
1083     if( p_vout->p_sys->i_shm_opcode )
1084     {
1085         /* Display rendered image using shared memory extension */
1086 #   if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1087         XvShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
1088                        p_vout->p_sys->p_win->video_window,
1089                        p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1090                        p_vout->fmt_out.i_x_offset,
1091                        p_vout->fmt_out.i_y_offset,
1092                        p_vout->fmt_out.i_visible_width,
1093                        p_vout->fmt_out.i_visible_height,
1094                        0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height,
1095                        False /* Don't put True here or you'll waste your CPU */ );
1096 #   else
1097         XShmPutImage( p_vout->p_sys->p_display,
1098                       p_vout->p_sys->p_win->video_window,
1099                       p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1100                       p_vout->fmt_out.i_x_offset,
1101                       p_vout->fmt_out.i_y_offset,
1102                       0 /*dest_x*/, 0 /*dest_y*/,
1103                       p_vout->fmt_out.i_visible_width,
1104                       p_vout->fmt_out.i_visible_height,
1105                       False /* Don't put True here ! */ );
1106 #   endif
1107     }
1108     else
1109 #endif /* HAVE_SYS_SHM_H */
1110     {
1111         /* Use standard XPutImage -- this is gonna be slow ! */
1112 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1113         XvPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
1114                     p_vout->p_sys->p_win->video_window,
1115                     p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1116                     p_vout->fmt_out.i_x_offset,
1117                     p_vout->fmt_out.i_y_offset,
1118                     p_vout->fmt_out.i_visible_width,
1119                     p_vout->fmt_out.i_visible_height,
1120                     0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height );
1121 #else
1122         XPutImage( p_vout->p_sys->p_display,
1123                    p_vout->p_sys->p_win->video_window,
1124                    p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1125                    p_vout->fmt_out.i_x_offset,
1126                    p_vout->fmt_out.i_y_offset,
1127                    0 /*dest_x*/, 0 /*dest_y*/,
1128                    p_vout->fmt_out.i_visible_width,
1129                    p_vout->fmt_out.i_visible_height );
1130 #endif
1131     }
1132
1133     /* Make sure the command is sent now - do NOT use XFlush !*/
1134     XSync( p_vout->p_sys->p_display, False );
1135
1136     vlc_mutex_unlock( &p_vout->p_sys->lock );
1137 }
1138
1139 /*****************************************************************************
1140  * ManageVideo: handle X11 events
1141  *****************************************************************************
1142  * This function should be called regularly by video output thread. It manages
1143  * X11 events and allows window resizing. It returns a non null value on
1144  * error.
1145  *****************************************************************************/
1146 static int ManageVideo( vout_thread_t *p_vout )
1147 {
1148     XEvent      xevent;                                         /* X11 event */
1149     vlc_value_t val;
1150
1151     vlc_mutex_lock( &p_vout->p_sys->lock );
1152
1153 #ifdef MODULE_NAME_IS_xvmc
1154     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
1155 #endif
1156
1157     /* Handle events from the owner window */
1158     if( p_vout->p_sys->p_win->owner_window )
1159     {
1160         while( XCheckWindowEvent( p_vout->p_sys->p_display,
1161                                   p_vout->p_sys->p_win->owner_window,
1162                                   StructureNotifyMask, &xevent ) == True )
1163         {
1164             /* ConfigureNotify event: prepare  */
1165             if( xevent.type == ConfigureNotify )
1166             {
1167                 /* Update dimensions */
1168                 XResizeWindow( p_vout->p_sys->p_display,
1169                                p_vout->p_sys->p_win->base_window,
1170                                xevent.xconfigure.width,
1171                                xevent.xconfigure.height );
1172             }
1173         }
1174     }
1175
1176     /* Handle X11 events: ConfigureNotify events are parsed to know if the
1177      * output window's size changed, MapNotify and UnmapNotify to know if the
1178      * window is mapped (and if the display is useful), and ClientMessages
1179      * to intercept window destruction requests */
1180
1181     while( XCheckWindowEvent( p_vout->p_sys->p_display,
1182                               p_vout->p_sys->p_win->base_window,
1183                               StructureNotifyMask | KeyPressMask |
1184                               ButtonPressMask | ButtonReleaseMask |
1185                               PointerMotionMask | Button1MotionMask , &xevent )
1186            == True )
1187     {
1188         /* ConfigureNotify event: prepare  */
1189         if( xevent.type == ConfigureNotify )
1190         {
1191             if( (unsigned int)xevent.xconfigure.width
1192                    != p_vout->p_sys->p_win->i_width
1193               || (unsigned int)xevent.xconfigure.height
1194                     != p_vout->p_sys->p_win->i_height )
1195             {
1196                 /* Update dimensions */
1197                 p_vout->i_changes |= VOUT_SIZE_CHANGE;
1198                 p_vout->p_sys->p_win->i_width = xevent.xconfigure.width;
1199                 p_vout->p_sys->p_win->i_height = xevent.xconfigure.height;
1200             }
1201         }
1202         /* Keyboard event */
1203         else if( xevent.type == KeyPress )
1204         {
1205             unsigned int state = xevent.xkey.state;
1206             KeySym x_key_symbol;
1207             char i_key;                                   /* ISO Latin-1 key */
1208
1209             /* We may have keys like F1 trough F12, ESC ... */
1210             x_key_symbol = XKeycodeToKeysym( p_vout->p_sys->p_display,
1211                                              xevent.xkey.keycode, 0 );
1212             val.i_int = ConvertKey( (int)x_key_symbol );
1213
1214             xevent.xkey.state &= ~ShiftMask;
1215             xevent.xkey.state &= ~ControlMask;
1216             xevent.xkey.state &= ~Mod1Mask;
1217
1218             if( !val.i_int &&
1219                 XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
1220             {
1221                 /* "Normal Keys"
1222                  * The reason why I use this instead of XK_0 is that
1223                  * with XLookupString, we don't have to care about
1224                  * keymaps. */
1225                 val.i_int = i_key;
1226             }
1227
1228             if( val.i_int )
1229             {
1230                 if( state & ShiftMask )
1231                 {
1232                     val.i_int |= KEY_MODIFIER_SHIFT;
1233                 }
1234                 if( state & ControlMask )
1235                 {
1236                     val.i_int |= KEY_MODIFIER_CTRL;
1237                 }
1238                 if( state & Mod1Mask )
1239                 {
1240                     val.i_int |= KEY_MODIFIER_ALT;
1241                 }
1242                 var_Set( p_vout->p_libvlc, "key-pressed", val );
1243             }
1244         }
1245         /* Mouse click */
1246         else if( xevent.type == ButtonPress )
1247         {
1248             switch( ((XButtonEvent *)&xevent)->button )
1249             {
1250                 case Button1:
1251                     var_Get( p_vout, "mouse-button-down", &val );
1252                     val.i_int |= 1;
1253                     var_Set( p_vout, "mouse-button-down", val );
1254
1255                     /* detect double-clicks */
1256                     if( ( ((XButtonEvent *)&xevent)->time -
1257                           p_vout->p_sys->i_time_button_last_pressed ) < 300 )
1258                     {
1259                         p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
1260                     }
1261
1262                     p_vout->p_sys->i_time_button_last_pressed =
1263                         ((XButtonEvent *)&xevent)->time;
1264                     break;
1265                 case Button2:
1266                     var_Get( p_vout, "mouse-button-down", &val );
1267                     val.i_int |= 2;
1268                     var_Set( p_vout, "mouse-button-down", val );
1269                     break;
1270
1271                 case Button3:
1272                     var_Get( p_vout, "mouse-button-down", &val );
1273                     val.i_int |= 4;
1274                     var_Set( p_vout, "mouse-button-down", val );
1275                     break;
1276
1277                 case Button4:
1278                     var_Get( p_vout, "mouse-button-down", &val );
1279                     val.i_int |= 8;
1280                     var_Set( p_vout, "mouse-button-down", val );
1281                     break;
1282
1283                 case Button5:
1284                     var_Get( p_vout, "mouse-button-down", &val );
1285                     val.i_int |= 16;
1286                     var_Set( p_vout, "mouse-button-down", val );
1287                     break;
1288             }
1289         }
1290         /* Mouse release */
1291         else if( xevent.type == ButtonRelease )
1292         {
1293             switch( ((XButtonEvent *)&xevent)->button )
1294             {
1295                 case Button1:
1296                     var_Get( p_vout, "mouse-button-down", &val );
1297                     val.i_int &= ~1;
1298                     var_Set( p_vout, "mouse-button-down", val );
1299
1300                     val.b_bool = true;
1301                     var_Set( p_vout, "mouse-clicked", val );
1302                     break;
1303
1304                 case Button2:
1305                     {
1306                         playlist_t *p_playlist;
1307
1308                         var_Get( p_vout, "mouse-button-down", &val );
1309                         val.i_int &= ~2;
1310                         var_Set( p_vout, "mouse-button-down", val );
1311
1312                         p_playlist = vlc_object_find( p_vout,
1313                                                       VLC_OBJECT_PLAYLIST,
1314                                                       FIND_ANYWHERE );
1315                         if( p_playlist != NULL )
1316                         {
1317                             vlc_value_t val;
1318                             var_Get( p_playlist, "intf-show", &val );
1319                             val.b_bool = !val.b_bool;
1320                             var_Set( p_playlist, "intf-show", val );
1321                             vlc_object_release( p_playlist );
1322                         }
1323                     }
1324                     break;
1325
1326                 case Button3:
1327                     {
1328                         intf_thread_t *p_intf;
1329                         playlist_t *p_playlist;
1330
1331                         var_Get( p_vout, "mouse-button-down", &val );
1332                         val.i_int &= ~4;
1333                         var_Set( p_vout, "mouse-button-down", val );
1334                         p_intf = vlc_object_find( p_vout, VLC_OBJECT_INTF,
1335                                                           FIND_ANYWHERE );
1336                         if( p_intf )
1337                         {
1338                             p_intf->b_menu_change = 1;
1339                             vlc_object_release( p_intf );
1340                         }
1341
1342                         p_playlist = vlc_object_find( p_vout,
1343                                                       VLC_OBJECT_PLAYLIST,
1344                                                       FIND_ANYWHERE );
1345                         if( p_playlist != NULL )
1346                         {
1347                             vlc_value_t val; val.b_bool = true;
1348                             var_Set( p_playlist, "intf-popupmenu", val );
1349                             vlc_object_release( p_playlist );
1350                         }
1351                     }
1352                     break;
1353
1354                 case Button4:
1355                     var_Get( p_vout, "mouse-button-down", &val );
1356                     val.i_int &= ~8;
1357                     var_Set( p_vout, "mouse-button-down", val );
1358                     break;
1359
1360                 case Button5:
1361                     var_Get( p_vout, "mouse-button-down", &val );
1362                     val.i_int &= ~16;
1363                     var_Set( p_vout, "mouse-button-down", val );
1364                     break;
1365
1366             }
1367         }
1368         /* Mouse move */
1369         else if( xevent.type == MotionNotify )
1370         {
1371             unsigned int i_width, i_height, i_x, i_y;
1372             vlc_value_t val;
1373
1374             /* somewhat different use for vout_PlacePicture:
1375              * here the values are needed to give to mouse coordinates
1376              * in the original picture space */
1377             vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
1378                                p_vout->p_sys->p_win->i_height,
1379                                &i_x, &i_y, &i_width, &i_height );
1380
1381             /* Compute the x coordinate and check if the value is
1382                in [0,p_vout->fmt_in.i_visible_width] */
1383             val.i_int = ( xevent.xmotion.x - i_x ) *
1384                 p_vout->fmt_in.i_visible_width / i_width +
1385                 p_vout->fmt_in.i_x_offset;
1386
1387             if( (int)(xevent.xmotion.x - i_x) < 0 )
1388                 val.i_int = 0;
1389             else if( (unsigned int)val.i_int > p_vout->fmt_in.i_visible_width )
1390                 val.i_int = p_vout->fmt_in.i_visible_width;
1391
1392             var_Set( p_vout, "mouse-x", val );
1393
1394             /* compute the y coordinate and check if the value is
1395                in [0,p_vout->fmt_in.i_visible_height] */
1396             val.i_int = ( xevent.xmotion.y - i_y ) *
1397                 p_vout->fmt_in.i_visible_height / i_height +
1398                 p_vout->fmt_in.i_y_offset;
1399
1400             if( (int)(xevent.xmotion.y - i_y) < 0 )
1401                 val.i_int = 0;
1402             else if( (unsigned int)val.i_int > p_vout->fmt_in.i_visible_height )
1403                 val.i_int = p_vout->fmt_in.i_visible_height;
1404
1405             var_Set( p_vout, "mouse-y", val );
1406
1407             val.b_bool = true;
1408             var_Set( p_vout, "mouse-moved", val );
1409
1410             p_vout->p_sys->i_time_mouse_last_moved = mdate();
1411             if( ! p_vout->p_sys->b_mouse_pointer_visible )
1412             {
1413                 ToggleCursor( p_vout );
1414             }
1415         }
1416         else if( xevent.type == ReparentNotify /* XXX: why do we get this? */
1417                   || xevent.type == MapNotify
1418                   || xevent.type == UnmapNotify )
1419         {
1420             /* Ignore these events */
1421         }
1422         else /* Other events */
1423         {
1424             msg_Warn( p_vout, "unhandled event %d received", xevent.type );
1425         }
1426     }
1427
1428     /* Handle events for video output sub-window */
1429     while( XCheckWindowEvent( p_vout->p_sys->p_display,
1430                               p_vout->p_sys->p_win->video_window,
1431                               ExposureMask, &xevent ) == True )
1432     {
1433         /* Window exposed (only handled if stream playback is paused) */
1434         if( xevent.type == Expose )
1435         {
1436             if( ((XExposeEvent *)&xevent)->count == 0 )
1437             {
1438                 /* (if this is the last a collection of expose events...) */
1439
1440 #if defined(MODULE_NAME_IS_xvideo)
1441                 x11_window_t *p_win = p_vout->p_sys->p_win;
1442
1443                 /* Paint the colour key if needed */
1444                 if( p_vout->p_sys->b_paint_colourkey &&
1445                     xevent.xexpose.window == p_win->video_window )
1446                 {
1447                     XSetForeground( p_vout->p_sys->p_display,
1448                                     p_win->gc, p_vout->p_sys->i_colourkey );
1449                     XFillRectangle( p_vout->p_sys->p_display,
1450                                     p_win->video_window, p_win->gc, 0, 0,
1451                                     p_win->i_width, p_win->i_height );
1452                 }
1453 #endif 
1454
1455 #if 0
1456                 if( p_vout->p_libvlc->p_input_bank->pp_input[0] != NULL )
1457                 {
1458                     if( PAUSE_S == p_vout->p_libvlc->p_input_bank->pp_input[0]
1459                                                    ->stream.control.i_status )
1460                     {
1461                         /* XVideoDisplay( p_vout )*/;
1462                     }
1463                 }
1464 #endif
1465             }
1466         }
1467     }
1468
1469     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
1470      * are handled - according to the man pages, the format is always 32
1471      * in this case */
1472     while( XCheckTypedEvent( p_vout->p_sys->p_display,
1473                              ClientMessage, &xevent ) )
1474     {
1475         if( (xevent.xclient.message_type == p_vout->p_sys->p_win->wm_protocols)
1476                && ((Atom)xevent.xclient.data.l[0]
1477                      == p_vout->p_sys->p_win->wm_delete_window ) )
1478         {
1479             /* the user wants to close the window */
1480             playlist_t * p_playlist =
1481                 (playlist_t *)vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
1482                                                FIND_ANYWHERE );
1483             if( p_playlist != NULL )
1484             {
1485                 playlist_Stop( p_playlist );
1486                 vlc_object_release( p_playlist );
1487             }
1488         }
1489     }
1490
1491     /*
1492      * Fullscreen Change
1493      */
1494     if ( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
1495     {
1496         /* Update the object variable and trigger callback */
1497         var_SetBool( p_vout, "fullscreen", !p_vout->b_fullscreen );
1498
1499         ToggleFullScreen( p_vout );
1500         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
1501     }
1502
1503     if( p_vout->i_changes & VOUT_CROP_CHANGE ||
1504         p_vout->i_changes & VOUT_ASPECT_CHANGE )
1505     {
1506         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
1507         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
1508
1509         p_vout->fmt_out.i_x_offset = p_vout->fmt_in.i_x_offset;
1510         p_vout->fmt_out.i_y_offset = p_vout->fmt_in.i_y_offset;
1511         p_vout->fmt_out.i_visible_width = p_vout->fmt_in.i_visible_width;
1512         p_vout->fmt_out.i_visible_height = p_vout->fmt_in.i_visible_height;
1513         p_vout->fmt_out.i_aspect = p_vout->fmt_in.i_aspect;
1514         p_vout->fmt_out.i_sar_num = p_vout->fmt_in.i_sar_num;
1515         p_vout->fmt_out.i_sar_den = p_vout->fmt_in.i_sar_den;
1516         p_vout->output.i_aspect = p_vout->fmt_in.i_aspect;
1517
1518         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1519     }
1520
1521     /*
1522      * Size change
1523      *
1524      * (Needs to be placed after VOUT_FULLSREEN_CHANGE because we can activate
1525      *  the size flag inside the fullscreen routine)
1526      */
1527     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
1528     {
1529         unsigned int i_width, i_height, i_x, i_y;
1530
1531         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
1532
1533 #ifdef MODULE_NAME_IS_x11
1534         /* We need to signal the vout thread about the size change because it
1535          * is doing the rescaling */
1536         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1537 #endif
1538
1539         vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
1540                            p_vout->p_sys->p_win->i_height,
1541                            &i_x, &i_y, &i_width, &i_height );
1542
1543         XMoveResizeWindow( p_vout->p_sys->p_display,
1544                            p_vout->p_sys->p_win->video_window,
1545                            i_x, i_y, i_width, i_height );
1546     }
1547
1548     /* Autohide Cursour */
1549     if( mdate() - p_vout->p_sys->i_time_mouse_last_moved >
1550         p_vout->p_sys->i_mouse_hide_timeout )
1551     {
1552         /* Hide the mouse automatically */
1553         if( p_vout->p_sys->b_mouse_pointer_visible )
1554         {
1555             ToggleCursor( p_vout );
1556         }
1557     }
1558
1559 #ifdef MODULE_NAME_IS_xvmc
1560     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1561 #endif
1562
1563 #ifdef HAVE_OSSO
1564     if ( p_vout->p_sys->p_octx != NULL ) {
1565         if ( p_vout->p_sys->i_backlight_on_counter == i_backlight_on_interval ) {
1566             if ( osso_display_blanking_pause( p_vout->p_sys->p_octx ) != OSSO_OK ) {
1567                 msg_Err( p_vout, "Could not disable backlight blanking" );
1568         } else {
1569                 msg_Dbg( p_vout, "Backlight blanking disabled" );
1570             }
1571             p_vout->p_sys->i_backlight_on_counter = 0;
1572         } else {
1573             p_vout->p_sys->i_backlight_on_counter ++;
1574         }
1575     }
1576 #endif
1577
1578     vlc_mutex_unlock( &p_vout->p_sys->lock );
1579     return 0;
1580 }
1581
1582 /*****************************************************************************
1583  * EndVideo: terminate X11 video thread output method
1584  *****************************************************************************
1585  * Destroy the X11 XImages created by Init. It is called at the end of
1586  * the thread, but also each time the window is resized.
1587  *****************************************************************************/
1588 static void EndVideo( vout_thread_t *p_vout )
1589 {
1590     int i_index;
1591
1592     /* Free the direct buffers we allocated */
1593     for( i_index = I_OUTPUTPICTURES ; i_index ; )
1594     {
1595         i_index--;
1596         FreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
1597     }
1598 }
1599
1600 /* following functions are local */
1601
1602 /*****************************************************************************
1603  * CreateWindow: open and set-up X11 main window
1604  *****************************************************************************/
1605 static int CreateWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1606 {
1607     XSizeHints              xsize_hints;
1608     XSetWindowAttributes    xwindow_attributes;
1609     XGCValues               xgcvalues;
1610     XEvent                  xevent;
1611
1612     bool              b_expose = false;
1613     bool              b_configure_notify = false;
1614     bool              b_map_notify = false;
1615     vlc_value_t             val;
1616
1617     /* Prepare window manager hints and properties */
1618     p_win->wm_protocols =
1619              XInternAtom( p_vout->p_sys->p_display, "WM_PROTOCOLS", True );
1620     p_win->wm_delete_window =
1621              XInternAtom( p_vout->p_sys->p_display, "WM_DELETE_WINDOW", True );
1622
1623     /* Never have a 0-pixel-wide window */
1624     xsize_hints.min_width = 2;
1625     xsize_hints.min_height = 1;
1626
1627     /* Prepare window attributes */
1628     xwindow_attributes.backing_store = Always;       /* save the hidden part */
1629     xwindow_attributes.background_pixel = BlackPixel(p_vout->p_sys->p_display,
1630                                                      p_vout->p_sys->i_screen);
1631     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
1632
1633     if( !p_vout->b_fullscreen )
1634     {
1635         p_win->owner_window = (Window)
1636             vout_RequestWindow( p_vout, &p_win->i_x, &p_win->i_y,
1637                                 &p_win->i_width, &p_win->i_height );
1638
1639         xsize_hints.base_width  = xsize_hints.width = p_win->i_width;
1640         xsize_hints.base_height = xsize_hints.height = p_win->i_height;
1641         xsize_hints.flags       = PSize | PMinSize;
1642
1643         if( p_win->i_x >=0 || p_win->i_y >= 0 )
1644         {
1645             xsize_hints.x = p_win->i_x;
1646             xsize_hints.y = p_win->i_y;
1647             xsize_hints.flags |= PPosition;
1648         }
1649     }
1650     else
1651     {
1652         /* Fullscreen window size and position */
1653         p_win->owner_window = 0;
1654         p_win->i_x = p_win->i_y = 0;
1655         p_win->i_width =
1656             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1657         p_win->i_height =
1658             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1659     }
1660
1661     if( !p_win->owner_window )
1662     {
1663         /* Create the window and set hints - the window must receive
1664          * ConfigureNotify events, and until it is displayed, Expose and
1665          * MapNotify events. */
1666
1667         p_win->base_window =
1668             XCreateWindow( p_vout->p_sys->p_display,
1669                            DefaultRootWindow( p_vout->p_sys->p_display ),
1670                            p_win->i_x, p_win->i_y,
1671                            p_win->i_width, p_win->i_height,
1672                            0,
1673                            0, InputOutput, 0,
1674                            CWBackingStore | CWBackPixel | CWEventMask,
1675                            &xwindow_attributes );
1676
1677         var_Get( p_vout, "video-title", &val );
1678         if( !val.psz_string || !*val.psz_string )
1679         {
1680             XStoreName( p_vout->p_sys->p_display, p_win->base_window,
1681 #ifdef MODULE_NAME_IS_x11
1682                         VOUT_TITLE " (X11 output)"
1683 #elif defined(MODULE_NAME_IS_glx)
1684                         VOUT_TITLE " (GLX output)"
1685 #else
1686                         VOUT_TITLE " (XVideo output)"
1687 #endif
1688               );
1689         }
1690         else
1691         {
1692             XStoreName( p_vout->p_sys->p_display,
1693                         p_win->base_window, val.psz_string );
1694         }
1695         free( val.psz_string );
1696
1697         if( !p_vout->b_fullscreen )
1698         {
1699             const char *argv[] = { "vlc", NULL };
1700
1701             /* Set window manager hints and properties: size hints, command,
1702              * window's name, and accepted protocols */
1703             XSetWMNormalHints( p_vout->p_sys->p_display,
1704                                p_win->base_window, &xsize_hints );
1705             XSetCommand( p_vout->p_sys->p_display, p_win->base_window,
1706                          (char**)argv, 1 );
1707
1708             if( !var_GetBool( p_vout, "video-deco") )
1709             {
1710                 Atom prop;
1711                 mwmhints_t mwmhints;
1712
1713                 mwmhints.flags = MWM_HINTS_DECORATIONS;
1714                 mwmhints.decorations = False;
1715
1716                 prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1717                                     False );
1718
1719                 XChangeProperty( p_vout->p_sys->p_display,
1720                                  p_win->base_window,
1721                                  prop, prop, 32, PropModeReplace,
1722                                  (unsigned char *)&mwmhints,
1723                                  PROP_MWM_HINTS_ELEMENTS );
1724             }
1725         }
1726     }
1727     else
1728     {
1729         Window dummy1;
1730         int dummy2, dummy3;
1731         unsigned int dummy4, dummy5;
1732
1733         /* Select events we are interested in. */
1734         XSelectInput( p_vout->p_sys->p_display, p_win->owner_window,
1735                       StructureNotifyMask );
1736
1737         /* Get the parent window's geometry information */
1738         XGetGeometry( p_vout->p_sys->p_display, p_win->owner_window,
1739                       &dummy1, &dummy2, &dummy3,
1740                       &p_win->i_width,
1741                       &p_win->i_height,
1742                       &dummy4, &dummy5 );
1743
1744         /* We are already configured */
1745         b_configure_notify = true;
1746
1747         /* From man XSelectInput: only one client at a time can select a
1748          * ButtonPress event, so we need to open a new window anyway. */
1749         p_win->base_window =
1750             XCreateWindow( p_vout->p_sys->p_display,
1751                            p_win->owner_window,
1752                            0, 0,
1753                            p_win->i_width, p_win->i_height,
1754                            0,
1755                            0, CopyFromParent, 0,
1756                            CWBackingStore | CWBackPixel | CWEventMask,
1757                            &xwindow_attributes );
1758     }
1759
1760     if( (p_win->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1761         || (p_win->wm_delete_window == None)
1762         || !XSetWMProtocols( p_vout->p_sys->p_display, p_win->base_window,
1763                              &p_win->wm_delete_window, 1 ) )
1764     {
1765         /* WM_DELETE_WINDOW is not supported by window manager */
1766         msg_Warn( p_vout, "missing or bad window manager" );
1767     }
1768
1769     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1770      * event when using functions like XCopyArea */
1771     xgcvalues.graphics_exposures = False;
1772     p_win->gc = XCreateGC( p_vout->p_sys->p_display,
1773                            p_win->base_window,
1774                            GCGraphicsExposures, &xgcvalues );
1775
1776     /* Send orders to server, and wait until window is displayed - three
1777      * events must be received: a MapNotify event, an Expose event allowing
1778      * drawing in the window, and a ConfigureNotify to get the window
1779      * dimensions. Once those events have been received, only
1780      * ConfigureNotify events need to be received. */
1781     XMapWindow( p_vout->p_sys->p_display, p_win->base_window );
1782     do
1783     {
1784         XWindowEvent( p_vout->p_sys->p_display, p_win->base_window,
1785                       SubstructureNotifyMask | StructureNotifyMask |
1786                       ExposureMask, &xevent);
1787         if( (xevent.type == Expose)
1788             && (xevent.xexpose.window == p_win->base_window) )
1789         {
1790             b_expose = true;
1791             /* ConfigureNotify isn't sent if there isn't a window manager.
1792              * Expose should be the last event to be received so it should
1793              * be fine to assume we won't receive it anymore. */
1794             b_configure_notify = true;
1795         }
1796         else if( (xevent.type == MapNotify)
1797                  && (xevent.xmap.window == p_win->base_window) )
1798         {
1799             b_map_notify = true;
1800         }
1801         else if( (xevent.type == ConfigureNotify)
1802                  && (xevent.xconfigure.window == p_win->base_window) )
1803         {
1804             b_configure_notify = true;
1805             p_win->i_width = xevent.xconfigure.width;
1806             p_win->i_height = xevent.xconfigure.height;
1807         }
1808     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1809
1810     XSelectInput( p_vout->p_sys->p_display, p_win->base_window,
1811                   StructureNotifyMask | KeyPressMask |
1812                   ButtonPressMask | ButtonReleaseMask |
1813                   PointerMotionMask );
1814
1815 #ifdef MODULE_NAME_IS_x11
1816     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1817     {
1818         /* Allocate a new palette */
1819         p_vout->p_sys->colormap =
1820             XCreateColormap( p_vout->p_sys->p_display,
1821                              DefaultRootWindow( p_vout->p_sys->p_display ),
1822                              DefaultVisual( p_vout->p_sys->p_display,
1823                                             p_vout->p_sys->i_screen ),
1824                              AllocAll );
1825
1826         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1827         XChangeWindowAttributes( p_vout->p_sys->p_display, p_win->base_window,
1828                                  CWColormap, &xwindow_attributes );
1829     }
1830 #endif
1831
1832     /* Create video output sub-window. */
1833     p_win->video_window =  XCreateSimpleWindow(
1834                                       p_vout->p_sys->p_display,
1835                                       p_win->base_window, 0, 0,
1836                                       p_win->i_width, p_win->i_height,
1837                                       0,
1838                                       BlackPixel( p_vout->p_sys->p_display,
1839                                                   p_vout->p_sys->i_screen ),
1840                                       WhitePixel( p_vout->p_sys->p_display,
1841                                                   p_vout->p_sys->i_screen ) );
1842
1843     XSetWindowBackground( p_vout->p_sys->p_display, p_win->video_window,
1844                           BlackPixel( p_vout->p_sys->p_display,
1845                                       p_vout->p_sys->i_screen ) );
1846
1847     XMapWindow( p_vout->p_sys->p_display, p_win->video_window );
1848     XSelectInput( p_vout->p_sys->p_display, p_win->video_window,
1849                   ExposureMask );
1850
1851     /* make sure the video window will be centered in the next ManageVideo() */
1852     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1853
1854     /* If the cursor was formerly blank than blank it again */
1855     if( !p_vout->p_sys->b_mouse_pointer_visible )
1856     {
1857         ToggleCursor( p_vout );
1858         ToggleCursor( p_vout );
1859     }
1860
1861     /* Do NOT use XFlush here ! */
1862     XSync( p_vout->p_sys->p_display, False );
1863
1864     /* At this stage, the window is open, displayed, and ready to
1865      * receive data */
1866     p_vout->p_sys->p_win = p_win;
1867
1868     return VLC_SUCCESS;
1869 }
1870
1871 /*****************************************************************************
1872  * DestroyWindow: destroy the window
1873  *****************************************************************************
1874  *
1875  *****************************************************************************/
1876 static void DestroyWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1877 {
1878     /* Do NOT use XFlush here ! */
1879     XSync( p_vout->p_sys->p_display, False );
1880
1881     if( p_win->video_window != None )
1882         XDestroyWindow( p_vout->p_sys->p_display, p_win->video_window );
1883
1884     XFreeGC( p_vout->p_sys->p_display, p_win->gc );
1885
1886     XUnmapWindow( p_vout->p_sys->p_display, p_win->base_window );
1887     XDestroyWindow( p_vout->p_sys->p_display, p_win->base_window );
1888
1889     if( p_win->owner_window )
1890         vout_ReleaseWindow( p_vout, (void *)p_win->owner_window );
1891 }
1892
1893 /*****************************************************************************
1894  * NewPicture: allocate a picture
1895  *****************************************************************************
1896  * Returns 0 on success, -1 otherwise
1897  *****************************************************************************/
1898 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1899 {
1900 #ifndef MODULE_NAME_IS_glx
1901
1902 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1903     int i_plane;
1904 #endif
1905
1906     /* We know the chroma, allocate a buffer which will be used
1907      * directly by the decoder */
1908     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1909
1910     if( p_pic->p_sys == NULL )
1911     {
1912         return -1;
1913     }
1914
1915 #ifdef MODULE_NAME_IS_xvmc
1916     p_pic->p_sys->p_vout = p_vout;
1917     p_pic->p_sys->xvmc_surf = NULL;
1918     p_pic->p_sys->xxmc_data.decoded = 0;
1919     p_pic->p_sys->xxmc_data.proc_xxmc_update_frame = xxmc_do_update_frame;
1920     //    p_pic->p_accel_data = &p_pic->p_sys->xxmc_data;
1921     p_pic->p_sys->nb_display = 0;
1922 #endif
1923
1924     /* Fill in picture_t fields */
1925     vout_InitPicture( VLC_OBJECT(p_vout), p_pic, p_vout->output.i_chroma,
1926                       p_vout->output.i_width, p_vout->output.i_height,
1927                       p_vout->output.i_aspect );
1928
1929 #ifdef HAVE_SYS_SHM_H
1930     if( p_vout->p_sys->i_shm_opcode )
1931     {
1932         /* Create image using XShm extension */
1933         p_pic->p_sys->p_image =
1934             CreateShmImage( p_vout, p_vout->p_sys->p_display,
1935 #   if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1936                             p_vout->p_sys->i_xvport,
1937                             VLC2X11_FOURCC(p_vout->output.i_chroma),
1938 #   else
1939                             p_vout->p_sys->p_visual,
1940                             p_vout->p_sys->i_screen_depth,
1941 #   endif
1942                             &p_pic->p_sys->shminfo,
1943                             p_vout->output.i_width, p_vout->output.i_height );
1944     }
1945
1946     if( !p_vout->p_sys->i_shm_opcode || !p_pic->p_sys->p_image )
1947 #endif /* HAVE_SYS_SHM_H */
1948     {
1949         /* Create image without XShm extension */
1950         p_pic->p_sys->p_image =
1951             CreateImage( p_vout, p_vout->p_sys->p_display,
1952 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1953                          p_vout->p_sys->i_xvport,
1954                          VLC2X11_FOURCC(p_vout->output.i_chroma),
1955                          p_pic->format.i_bits_per_pixel,
1956 #else
1957                          p_vout->p_sys->p_visual,
1958                          p_vout->p_sys->i_screen_depth,
1959                          p_vout->p_sys->i_bytes_per_pixel,
1960 #endif
1961                          p_vout->output.i_width, p_vout->output.i_height );
1962
1963 #ifdef HAVE_SYS_SHM_H
1964         if( p_pic->p_sys->p_image && p_vout->p_sys->i_shm_opcode )
1965         {
1966             msg_Warn( p_vout, "couldn't create SHM image, disabling SHM" );
1967             p_vout->p_sys->i_shm_opcode = 0;
1968         }
1969 #endif /* HAVE_SYS_SHM_H */
1970     }
1971
1972     if( p_pic->p_sys->p_image == NULL )
1973     {
1974         free( p_pic->p_sys );
1975         return -1;
1976     }
1977
1978     switch( p_vout->output.i_chroma )
1979     {
1980 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1981         case VLC_FOURCC('I','4','2','0'):
1982         case VLC_FOURCC('Y','V','1','2'):
1983         case VLC_FOURCC('Y','2','1','1'):
1984         case VLC_FOURCC('Y','U','Y','2'):
1985         case VLC_FOURCC('U','Y','V','Y'):
1986         case VLC_FOURCC('R','V','1','5'):
1987         case VLC_FOURCC('R','V','1','6'):
1988         case VLC_FOURCC('R','V','2','4'): /* Fixme: pixel pitch == 4 ? */
1989         case VLC_FOURCC('R','V','3','2'):
1990
1991             for( i_plane = 0; i_plane < p_pic->p_sys->p_image->num_planes;
1992                  i_plane++ )
1993             {
1994                 p_pic->p[i_plane].p_pixels = (uint8_t*)p_pic->p_sys->p_image->data
1995                     + p_pic->p_sys->p_image->offsets[i_plane];
1996                 p_pic->p[i_plane].i_pitch =
1997                     p_pic->p_sys->p_image->pitches[i_plane];
1998             }
1999             if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
2000             {
2001                 /* U and V inverted compared to I420
2002                  * Fixme: this should be handled by the vout core */
2003                 p_pic->U_PIXELS = (uint8_t*)p_pic->p_sys->p_image->data
2004                     + p_pic->p_sys->p_image->offsets[2];
2005                 p_pic->V_PIXELS = (uint8_t*)p_pic->p_sys->p_image->data
2006                     + p_pic->p_sys->p_image->offsets[1];
2007             }
2008             break;
2009
2010 #else
2011         case VLC_FOURCC('R','G','B','2'):
2012         case VLC_FOURCC('R','V','1','6'):
2013         case VLC_FOURCC('R','V','1','5'):
2014         case VLC_FOURCC('R','V','2','4'):
2015         case VLC_FOURCC('R','V','3','2'):
2016
2017             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
2018             p_pic->p->i_visible_lines = p_pic->p_sys->p_image->height;
2019             p_pic->p->p_pixels = (uint8_t*)p_pic->p_sys->p_image->data
2020                                   + p_pic->p_sys->p_image->xoffset;
2021             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
2022
2023             /* p_pic->p->i_pixel_pitch = 4 for RV24 but this should be set
2024              * properly by vout_InitPicture() */
2025             p_pic->p->i_visible_pitch = p_pic->p->i_pixel_pitch
2026                                          * p_pic->p_sys->p_image->width;
2027             break;
2028 #endif
2029
2030         default:
2031             /* Unknown chroma, tell the guy to get lost */
2032             IMAGE_FREE( p_pic->p_sys->p_image );
2033             free( p_pic->p_sys );
2034             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
2035                      p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
2036             p_pic->i_planes = 0;
2037             return -1;
2038     }
2039 #else
2040
2041     VLC_UNUSED(p_vout); VLC_UNUSED(p_pic);
2042
2043 #endif /* !MODULE_NAME_IS_glx */
2044
2045     return 0;
2046 }
2047
2048 /*****************************************************************************
2049  * FreePicture: destroy a picture allocated with NewPicture
2050  *****************************************************************************
2051  * Destroy XImage AND associated data. If using Shm, detach shared memory
2052  * segment from server and process, then free it. The XDestroyImage manpage
2053  * says that both the image structure _and_ the data pointed to by the
2054  * image structure are freed, so no need to free p_image->data.
2055  *****************************************************************************/
2056 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
2057 {
2058     /* The order of operations is correct */
2059 #ifdef HAVE_SYS_SHM_H
2060     if( p_vout->p_sys->i_shm_opcode )
2061     {
2062         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
2063         IMAGE_FREE( p_pic->p_sys->p_image );
2064
2065         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
2066         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
2067         {
2068             msg_Err( p_vout, "cannot detach shared memory (%m)" );
2069         }
2070     }
2071     else
2072 #endif
2073     {
2074         IMAGE_FREE( p_pic->p_sys->p_image );
2075     }
2076
2077 #ifdef MODULE_NAME_IS_xvmc
2078     if( p_pic->p_sys->xvmc_surf != NULL )
2079     {
2080         xxmc_xvmc_free_surface(p_vout , p_pic->p_sys->xvmc_surf);
2081         p_pic->p_sys->xvmc_surf = NULL;
2082     }
2083 #endif
2084
2085     /* Do NOT use XFlush here ! */
2086     XSync( p_vout->p_sys->p_display, False );
2087
2088     free( p_pic->p_sys );
2089 }
2090
2091 /*****************************************************************************
2092  * ToggleFullScreen: Enable or disable full screen mode
2093  *****************************************************************************
2094  * This function will switch between fullscreen and window mode.
2095  *****************************************************************************/
2096 static void ToggleFullScreen ( vout_thread_t *p_vout )
2097 {
2098     Atom prop;
2099     XEvent xevent;
2100     mwmhints_t mwmhints;
2101     XSetWindowAttributes attributes;
2102
2103 #ifdef HAVE_XINERAMA
2104     int i_d1, i_d2;
2105 #endif
2106
2107     p_vout->b_fullscreen = !p_vout->b_fullscreen;
2108
2109     if( p_vout->b_fullscreen )
2110     {
2111         msg_Dbg( p_vout, "entering fullscreen mode" );
2112
2113         p_vout->p_sys->b_altfullscreen =
2114             config_GetInt( p_vout, MODULE_STRING "-altfullscreen" );
2115
2116         XUnmapWindow( p_vout->p_sys->p_display,
2117                       p_vout->p_sys->p_win->base_window );
2118
2119         p_vout->p_sys->p_win = &p_vout->p_sys->fullscreen_window;
2120
2121         CreateWindow( p_vout, p_vout->p_sys->p_win );
2122         XDestroyWindow( p_vout->p_sys->p_display,
2123                         p_vout->p_sys->fullscreen_window.video_window );
2124         XReparentWindow( p_vout->p_sys->p_display,
2125                          p_vout->p_sys->original_window.video_window,
2126                          p_vout->p_sys->fullscreen_window.base_window, 0, 0 );
2127         p_vout->p_sys->fullscreen_window.video_window =
2128             p_vout->p_sys->original_window.video_window;
2129
2130         /* To my knowledge there are two ways to create a borderless window.
2131          * There's the generic way which is to tell x to bypass the window
2132          * manager, but this creates problems with the focus of other
2133          * applications.
2134          * The other way is to use the motif property "_MOTIF_WM_HINTS" which
2135          * luckily seems to be supported by most window managers. */
2136         if( !p_vout->p_sys->b_altfullscreen )
2137         {
2138             mwmhints.flags = MWM_HINTS_DECORATIONS;
2139             mwmhints.decorations = False;
2140
2141             prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
2142                                 False );
2143             XChangeProperty( p_vout->p_sys->p_display,
2144                              p_vout->p_sys->p_win->base_window,
2145                              prop, prop, 32, PropModeReplace,
2146                              (unsigned char *)&mwmhints,
2147                              PROP_MWM_HINTS_ELEMENTS );
2148         }
2149         else
2150         {
2151             /* brute force way to remove decorations */
2152             attributes.override_redirect = True;
2153             XChangeWindowAttributes( p_vout->p_sys->p_display,
2154                                      p_vout->p_sys->p_win->base_window,
2155                                      CWOverrideRedirect,
2156                                      &attributes);
2157
2158             /* Make sure the change is effective */
2159             XReparentWindow( p_vout->p_sys->p_display,
2160                              p_vout->p_sys->p_win->base_window,
2161                              DefaultRootWindow( p_vout->p_sys->p_display ),
2162                              0, 0 );
2163         }
2164
2165         if( p_vout->p_sys->b_net_wm_state_fullscreen )
2166         {
2167             XClientMessageEvent event;
2168
2169             memset( &event, 0, sizeof( XClientMessageEvent ) );
2170
2171             event.type = ClientMessage;
2172             event.message_type = p_vout->p_sys->net_wm_state;
2173             event.display = p_vout->p_sys->p_display;
2174             event.window = p_vout->p_sys->p_win->base_window;
2175             event.format = 32;
2176             event.data.l[ 0 ] = 1; /* set property */
2177             event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_fullscreen;
2178
2179             XSendEvent( p_vout->p_sys->p_display,
2180                         DefaultRootWindow( p_vout->p_sys->p_display ),
2181                         False, SubstructureRedirectMask,
2182                         (XEvent*)&event );
2183         }
2184
2185         /* Make sure the change is effective */
2186         XReparentWindow( p_vout->p_sys->p_display,
2187                          p_vout->p_sys->p_win->base_window,
2188                          DefaultRootWindow( p_vout->p_sys->p_display ),
2189                          0, 0 );
2190
2191 #ifdef HAVE_XINERAMA
2192         if( XineramaQueryExtension( p_vout->p_sys->p_display, &i_d1, &i_d2 ) &&
2193             XineramaIsActive( p_vout->p_sys->p_display ) )
2194         {
2195             XineramaScreenInfo *screens;   /* infos for xinerama */
2196             int i_num_screens;
2197
2198             msg_Dbg( p_vout, "using XFree Xinerama extension");
2199
2200 #define SCREEN p_vout->p_sys->p_win->i_screen
2201
2202             /* Get Information about Xinerama (num of screens) */
2203             screens = XineramaQueryScreens( p_vout->p_sys->p_display,
2204                                             &i_num_screens );
2205
2206             SCREEN = config_GetInt( p_vout,
2207                                         MODULE_STRING "-xineramascreen" );
2208
2209             /* just check that user has entered a good value */
2210             if( SCREEN >= i_num_screens || SCREEN < 0 )
2211             {
2212                 msg_Dbg( p_vout, "requested screen number invalid (%d/%d)", SCREEN, i_num_screens );
2213                 SCREEN = 0;
2214             }
2215
2216             /* Get the X/Y upper left corner coordinate of the above screen */
2217             p_vout->p_sys->p_win->i_x = screens[SCREEN].x_org;
2218             p_vout->p_sys->p_win->i_y = screens[SCREEN].y_org;
2219
2220             /* Set the Height/width to the screen resolution */
2221             p_vout->p_sys->p_win->i_width = screens[SCREEN].width;
2222             p_vout->p_sys->p_win->i_height = screens[SCREEN].height;
2223
2224             XFree(screens);
2225
2226 #undef SCREEN
2227
2228         }
2229         else
2230 #endif
2231         {
2232             /* The window wasn't necessarily created at the requested size */
2233             p_vout->p_sys->p_win->i_x = p_vout->p_sys->p_win->i_y = 0;
2234
2235 #ifdef HAVE_XF86VIDMODE
2236             XF86VidModeModeLine mode;
2237             int i_dummy;
2238
2239             if( XF86VidModeGetModeLine( p_vout->p_sys->p_display,
2240                                         p_vout->p_sys->i_screen, &i_dummy,
2241                                         &mode ) )
2242             {
2243                 p_vout->p_sys->p_win->i_width = mode.hdisplay;
2244                 p_vout->p_sys->p_win->i_height = mode.vdisplay;
2245
2246                 /* move cursor to the middle of the window to prevent
2247                  * unwanted display move if the display is smaller than the
2248                  * full desktop */
2249                 XWarpPointer( p_vout->p_sys->p_display, None,
2250                               p_vout->p_sys->p_win->base_window, 0, 0, 0, 0,
2251                               mode.hdisplay / 2 , mode.vdisplay / 2 );
2252                 /* force desktop view to upper left corner */
2253                 XF86VidModeSetViewPort( p_vout->p_sys->p_display,
2254                                         p_vout->p_sys->i_screen, 0, 0 );
2255             }
2256             else
2257 #endif
2258             {
2259                 p_vout->p_sys->p_win->i_width =
2260                     DisplayWidth( p_vout->p_sys->p_display,
2261                                 p_vout->p_sys->i_screen );
2262                 p_vout->p_sys->p_win->i_height =
2263                     DisplayHeight( p_vout->p_sys->p_display,
2264                                 p_vout->p_sys->i_screen );
2265             }
2266
2267         }
2268
2269         XMoveResizeWindow( p_vout->p_sys->p_display,
2270                            p_vout->p_sys->p_win->base_window,
2271                            p_vout->p_sys->p_win->i_x,
2272                            p_vout->p_sys->p_win->i_y,
2273                            p_vout->p_sys->p_win->i_width,
2274                            p_vout->p_sys->p_win->i_height );
2275
2276 #ifdef HAVE_XSP
2277         EnablePixelDoubling( p_vout );
2278 #endif
2279
2280         /* Activate the window (give it the focus) */
2281         XClientMessageEvent event;
2282
2283         memset( &event, 0, sizeof( XClientMessageEvent ) );
2284
2285         event.type = ClientMessage;
2286         event.message_type =
2287            XInternAtom( p_vout->p_sys->p_display, "_NET_ACTIVE_WINDOW", False );
2288         event.display = p_vout->p_sys->p_display;
2289         event.window = p_vout->p_sys->p_win->base_window;
2290         event.format = 32;
2291         event.data.l[ 0 ] = 1; /* source indication (1 = from an application */
2292         event.data.l[ 1 ] = 0; /* timestamp */
2293         event.data.l[ 2 ] = 0; /* requestor's currently active window */
2294         /* XXX: window manager would be more likely to obey if we already have
2295          * an active window (and give it to the event), such as an interface */
2296
2297         XSendEvent( p_vout->p_sys->p_display,
2298                     DefaultRootWindow( p_vout->p_sys->p_display ),
2299                     False, SubstructureRedirectMask,
2300                     (XEvent*)&event );
2301     }
2302     else
2303     {
2304         msg_Dbg( p_vout, "leaving fullscreen mode" );
2305
2306 #ifdef HAVE_XSP
2307         DisablePixelDoubling( p_vout );
2308 #endif
2309
2310         XReparentWindow( p_vout->p_sys->p_display,
2311                          p_vout->p_sys->original_window.video_window,
2312                          p_vout->p_sys->original_window.base_window, 0, 0 );
2313
2314         p_vout->p_sys->fullscreen_window.video_window = None;
2315         DestroyWindow( p_vout, &p_vout->p_sys->fullscreen_window );
2316         p_vout->p_sys->p_win = &p_vout->p_sys->original_window;
2317
2318         XMapWindow( p_vout->p_sys->p_display,
2319                     p_vout->p_sys->p_win->base_window );
2320     }
2321
2322     /* Unfortunately, using XSync() here is not enough to ensure the
2323      * window has already been mapped because the XMapWindow() request
2324      * has not necessarily been sent directly to our window (remember,
2325      * the call is first redirected to the window manager) */
2326     do
2327     {
2328         XWindowEvent( p_vout->p_sys->p_display,
2329                       p_vout->p_sys->p_win->base_window,
2330                       StructureNotifyMask, &xevent );
2331     } while( xevent.type != MapNotify );
2332
2333     /* Be careful, this can generate a BadMatch error if the window is not
2334      * already mapped by the server (see above) */
2335     XSetInputFocus(p_vout->p_sys->p_display,
2336                    p_vout->p_sys->p_win->base_window,
2337                    RevertToParent,
2338                    CurrentTime);
2339
2340     /* signal that the size needs to be updated */
2341     p_vout->i_changes |= VOUT_SIZE_CHANGE;
2342 }
2343
2344 /*****************************************************************************
2345  * EnableXScreenSaver: enable screen saver
2346  *****************************************************************************
2347  * This function enables the screen saver on a display after it has been
2348  * disabled by XDisableScreenSaver.
2349  * FIXME: what happens if multiple vlc sessions are running at the same
2350  *        time ???
2351  *****************************************************************************/
2352 static void EnableXScreenSaver( vout_thread_t *p_vout )
2353 {
2354 #ifdef DPMSINFO_IN_DPMS_H
2355     int dummy;
2356 #endif
2357
2358     if( p_vout->p_sys->i_ss_timeout )
2359     {
2360         XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
2361                          p_vout->p_sys->i_ss_interval,
2362                          p_vout->p_sys->i_ss_blanking,
2363                          p_vout->p_sys->i_ss_exposure );
2364     }
2365
2366     /* Restore DPMS settings */
2367 #ifdef DPMSINFO_IN_DPMS_H
2368     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2369     {
2370         if( p_vout->p_sys->b_ss_dpms )
2371         {
2372             DPMSEnable( p_vout->p_sys->p_display );
2373         }
2374     }
2375 #endif
2376 }
2377
2378 /*****************************************************************************
2379  * DisableXScreenSaver: disable screen saver
2380  *****************************************************************************
2381  * See XEnableXScreenSaver
2382  *****************************************************************************/
2383 static void DisableXScreenSaver( vout_thread_t *p_vout )
2384 {
2385 #ifdef DPMSINFO_IN_DPMS_H
2386     int dummy;
2387 #endif
2388
2389     /* Save screen saver information */
2390     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
2391                      &p_vout->p_sys->i_ss_interval,
2392                      &p_vout->p_sys->i_ss_blanking,
2393                      &p_vout->p_sys->i_ss_exposure );
2394
2395     /* Disable screen saver */
2396     if( p_vout->p_sys->i_ss_timeout )
2397     {
2398         XSetScreenSaver( p_vout->p_sys->p_display, 0,
2399                          p_vout->p_sys->i_ss_interval,
2400                          p_vout->p_sys->i_ss_blanking,
2401                          p_vout->p_sys->i_ss_exposure );
2402     }
2403
2404     /* Disable DPMS */
2405 #ifdef DPMSINFO_IN_DPMS_H
2406     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2407     {
2408         CARD16 unused;
2409         /* Save DPMS current state */
2410         DPMSInfo( p_vout->p_sys->p_display, &unused,
2411                   &p_vout->p_sys->b_ss_dpms );
2412         DPMSDisable( p_vout->p_sys->p_display );
2413    }
2414 #endif
2415 }
2416
2417 /*****************************************************************************
2418  * CreateCursor: create a blank mouse pointer
2419  *****************************************************************************/
2420 static void CreateCursor( vout_thread_t *p_vout )
2421 {
2422     XColor cursor_color;
2423
2424     p_vout->p_sys->cursor_pixmap =
2425         XCreatePixmap( p_vout->p_sys->p_display,
2426                        DefaultRootWindow( p_vout->p_sys->p_display ),
2427                        1, 1, 1 );
2428
2429     XParseColor( p_vout->p_sys->p_display,
2430                  XCreateColormap( p_vout->p_sys->p_display,
2431                                   DefaultRootWindow(
2432                                                     p_vout->p_sys->p_display ),
2433                                   DefaultVisual(
2434                                                 p_vout->p_sys->p_display,
2435                                                 p_vout->p_sys->i_screen ),
2436                                   AllocNone ),
2437                  "black", &cursor_color );
2438
2439     p_vout->p_sys->blank_cursor =
2440         XCreatePixmapCursor( p_vout->p_sys->p_display,
2441                              p_vout->p_sys->cursor_pixmap,
2442                              p_vout->p_sys->cursor_pixmap,
2443                              &cursor_color, &cursor_color, 1, 1 );
2444 }
2445
2446 /*****************************************************************************
2447  * DestroyCursor: destroy the blank mouse pointer
2448  *****************************************************************************/
2449 static void DestroyCursor( vout_thread_t *p_vout )
2450 {
2451     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
2452 }
2453
2454 /*****************************************************************************
2455  * ToggleCursor: hide or show the mouse pointer
2456  *****************************************************************************
2457  * This function hides the X pointer if it is visible by setting the pointer
2458  * sprite to a blank one. To show it again, we disable the sprite.
2459  *****************************************************************************/
2460 static void ToggleCursor( vout_thread_t *p_vout )
2461 {
2462     if( p_vout->p_sys->b_mouse_pointer_visible )
2463     {
2464         XDefineCursor( p_vout->p_sys->p_display,
2465                        p_vout->p_sys->p_win->base_window,
2466                        p_vout->p_sys->blank_cursor );
2467         p_vout->p_sys->b_mouse_pointer_visible = 0;
2468     }
2469     else
2470     {
2471         XUndefineCursor( p_vout->p_sys->p_display,
2472                          p_vout->p_sys->p_win->base_window );
2473         p_vout->p_sys->b_mouse_pointer_visible = 1;
2474     }
2475 }
2476
2477 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
2478 /*****************************************************************************
2479  * XVideoGetPort: get YUV12 port
2480  *****************************************************************************/
2481 static int XVideoGetPort( vout_thread_t *p_vout,
2482                           vlc_fourcc_t i_chroma, vlc_fourcc_t *pi_newchroma )
2483 {
2484     XvAdaptorInfo *p_adaptor;
2485     unsigned int i;
2486     unsigned int i_adaptor, i_num_adaptors;
2487     int i_requested_adaptor;
2488     int i_selected_port;
2489
2490     switch( XvQueryExtension( p_vout->p_sys->p_display, &i, &i, &i, &i, &i ) )
2491     {
2492         case Success:
2493             break;
2494
2495         case XvBadExtension:
2496             msg_Warn( p_vout, "XvBadExtension" );
2497             return -1;
2498
2499         case XvBadAlloc:
2500             msg_Warn( p_vout, "XvBadAlloc" );
2501             return -1;
2502
2503         default:
2504             msg_Warn( p_vout, "XvQueryExtension failed" );
2505             return -1;
2506     }
2507
2508     switch( XvQueryAdaptors( p_vout->p_sys->p_display,
2509                              DefaultRootWindow( p_vout->p_sys->p_display ),
2510                              &i_num_adaptors, &p_adaptor ) )
2511     {
2512         case Success:
2513             break;
2514
2515         case XvBadExtension:
2516             msg_Warn( p_vout, "XvBadExtension for XvQueryAdaptors" );
2517             return -1;
2518
2519         case XvBadAlloc:
2520             msg_Warn( p_vout, "XvBadAlloc for XvQueryAdaptors" );
2521             return -1;
2522
2523         default:
2524             msg_Warn( p_vout, "XvQueryAdaptors failed" );
2525             return -1;
2526     }
2527
2528     i_selected_port = -1;
2529 #ifdef MODULE_NAME_IS_xvmc
2530     i_requested_adaptor = config_GetInt( p_vout, "xvmc-adaptor" );
2531 #else
2532     i_requested_adaptor = config_GetInt( p_vout, "xvideo-adaptor" );
2533 #endif
2534     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
2535     {
2536         XvImageFormatValues *p_formats;
2537         int i_format, i_num_formats;
2538         int i_port;
2539
2540         /* If we requested an adaptor and it's not this one, we aren't
2541          * interested */
2542         if( i_requested_adaptor != -1 && ((int)i_adaptor != i_requested_adaptor) )
2543         {
2544             continue;
2545         }
2546
2547         /* If the adaptor doesn't have the required properties, skip it */
2548         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
2549             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
2550         {
2551             continue;
2552         }
2553
2554         /* Check that adaptor supports our requested format... */
2555         p_formats = XvListImageFormats( p_vout->p_sys->p_display,
2556                                         p_adaptor[i_adaptor].base_id,
2557                                         &i_num_formats );
2558
2559         for( i_format = 0;
2560              i_format < i_num_formats && ( i_selected_port == -1 );
2561              i_format++ )
2562         {
2563             XvAttribute     *p_attr;
2564             int             i_attr, i_num_attributes;
2565             Atom            autopaint = None, colorkey = None;
2566
2567             /* If this is not the format we want, or at least a
2568              * similar one, forget it */
2569             if( !vout_ChromaCmp( p_formats[ i_format ].id, i_chroma ) )
2570             {
2571                 continue;
2572             }
2573
2574             /* Look for the first available port supporting this format */
2575             for( i_port = p_adaptor[i_adaptor].base_id;
2576                  ( i_port < (int)(p_adaptor[i_adaptor].base_id
2577                                    + p_adaptor[i_adaptor].num_ports) )
2578                    && ( i_selected_port == -1 );
2579                  i_port++ )
2580             {
2581                 if( XvGrabPort( p_vout->p_sys->p_display, i_port, CurrentTime )
2582                      == Success )
2583                 {
2584                     i_selected_port = i_port;
2585                     *pi_newchroma = p_formats[ i_format ].id;
2586                 }
2587             }
2588
2589             /* If no free port was found, forget it */
2590             if( i_selected_port == -1 )
2591             {
2592                 continue;
2593             }
2594
2595             /* If we found a port, print information about it */
2596             msg_Dbg( p_vout, "adaptor %i, port %i, format 0x%x (%4.4s) %s",
2597                      i_adaptor, i_selected_port, p_formats[ i_format ].id,
2598                      (char *)&p_formats[ i_format ].id,
2599                      ( p_formats[ i_format ].format == XvPacked ) ?
2600                          "packed" : "planar" );
2601
2602             /* Use XV_AUTOPAINT_COLORKEY if supported, otherwise we will
2603              * manually paint the colour key */
2604             p_attr = XvQueryPortAttributes( p_vout->p_sys->p_display,
2605                                             i_selected_port,
2606                                             &i_num_attributes );
2607
2608             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
2609             {
2610                 if( !strcmp( p_attr[i_attr].name, "XV_AUTOPAINT_COLORKEY" ) )
2611                 {
2612                     autopaint = XInternAtom( p_vout->p_sys->p_display,
2613                                              "XV_AUTOPAINT_COLORKEY", False );
2614                     XvSetPortAttribute( p_vout->p_sys->p_display,
2615                                         i_selected_port, autopaint, 1 );
2616                 }
2617                 if( !strcmp( p_attr[i_attr].name, "XV_COLORKEY" ) )
2618                 {
2619                     /* Find out the default colour key */
2620                     colorkey = XInternAtom( p_vout->p_sys->p_display,
2621                                             "XV_COLORKEY", False );
2622                     XvGetPortAttribute( p_vout->p_sys->p_display,
2623                                         i_selected_port, colorkey,
2624                                         &p_vout->p_sys->i_colourkey );
2625                 }
2626             }
2627             p_vout->p_sys->b_paint_colourkey =
2628                 autopaint == None && colorkey != None;
2629
2630             if( p_attr != NULL )
2631             {
2632                 XFree( p_attr );
2633             }
2634         }
2635
2636         if( p_formats != NULL )
2637         {
2638             XFree( p_formats );
2639         }
2640
2641     }
2642
2643     if( i_num_adaptors > 0 )
2644     {
2645         XvFreeAdaptorInfo( p_adaptor );
2646     }
2647
2648     if( i_selected_port == -1 )
2649     {
2650         int i_chroma_tmp = X112VLC_FOURCC( i_chroma );
2651         if( i_requested_adaptor == -1 )
2652         {
2653             msg_Warn( p_vout, "no free XVideo port found for format "
2654                       "0x%.8x (%4.4s)", i_chroma_tmp, (char*)&i_chroma_tmp );
2655         }
2656         else
2657         {
2658             msg_Warn( p_vout, "XVideo adaptor %i does not have a free "
2659                       "XVideo port for format 0x%.8x (%4.4s)",
2660                       i_requested_adaptor, i_chroma_tmp, (char*)&i_chroma_tmp );
2661         }
2662     }
2663
2664     return i_selected_port;
2665 }
2666
2667 /*****************************************************************************
2668  * XVideoReleasePort: release YUV12 port
2669  *****************************************************************************/
2670 static void XVideoReleasePort( vout_thread_t *p_vout, int i_port )
2671 {
2672     XvUngrabPort( p_vout->p_sys->p_display, i_port, CurrentTime );
2673 }
2674 #endif
2675
2676 /*****************************************************************************
2677  * InitDisplay: open and initialize X11 device
2678  *****************************************************************************
2679  * Create a window according to video output given size, and set other
2680  * properties according to the display properties.
2681  *****************************************************************************/
2682 static int InitDisplay( vout_thread_t *p_vout )
2683 {
2684 #ifdef MODULE_NAME_IS_x11
2685     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
2686     XVisualInfo *               p_xvisual;            /* visuals information */
2687     XVisualInfo                 xvisual_template;         /* visual template */
2688     int                         i_count, i;                    /* array size */
2689 #endif
2690
2691 #ifdef HAVE_SYS_SHM_H
2692     p_vout->p_sys->i_shm_opcode = 0;
2693
2694     if( config_GetInt( p_vout, MODULE_STRING "-shm" ) )
2695     {
2696         int major, evt, err;
2697
2698         if( XQueryExtension( p_vout->p_sys->p_display, "MIT-SHM", &major,
2699                              &evt, &err )
2700          && XShmQueryExtension( p_vout->p_sys->p_display ) )
2701             p_vout->p_sys->i_shm_opcode = major;
2702
2703         if( p_vout->p_sys->i_shm_opcode )
2704         {
2705             int major, minor;
2706             Bool pixmaps;
2707
2708             XShmQueryVersion( p_vout->p_sys->p_display, &major, &minor,
2709                               &pixmaps );
2710             msg_Dbg( p_vout, "XShm video extension v%d.%d "
2711                      "(with%s pixmaps, opcode: %d)",
2712                      major, minor, pixmaps ? "" : "out",
2713                      p_vout->p_sys->i_shm_opcode );
2714         }
2715         else
2716             msg_Warn( p_vout, "XShm video extension not available" );
2717     }
2718     else
2719         msg_Dbg( p_vout, "XShm video extension disabled" );
2720 #endif
2721
2722 #ifdef MODULE_NAME_IS_xvideo
2723     /* XXX The brightness and contrast values should be read from environment
2724      * XXX variables... */
2725 #if 0
2726     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
2727     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
2728 #endif
2729 #endif
2730
2731 #ifdef MODULE_NAME_IS_x11
2732     /* Initialize structure */
2733     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
2734
2735     /* Get screen depth */
2736     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
2737                                                    p_vout->p_sys->i_screen );
2738     switch( p_vout->p_sys->i_screen_depth )
2739     {
2740     case 8:
2741         /*
2742          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
2743          */
2744         xvisual_template.screen =   p_vout->p_sys->i_screen;
2745         xvisual_template.class =    DirectColor;
2746         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2747                                     VisualScreenMask | VisualClassMask,
2748                                     &xvisual_template, &i_count );
2749         if( p_xvisual == NULL )
2750         {
2751             msg_Err( p_vout, "no PseudoColor visual available" );
2752             return VLC_EGENERIC;
2753         }
2754         p_vout->p_sys->i_bytes_per_pixel = 1;
2755         p_vout->output.pf_setpalette = SetPalette;
2756         break;
2757     case 15:
2758     case 16:
2759     case 24:
2760     default:
2761         /*
2762          * Screen depth is higher than 8bpp. TrueColor visual is used.
2763          */
2764         xvisual_template.screen =   p_vout->p_sys->i_screen;
2765         xvisual_template.class =    TrueColor;
2766 /* In some cases, we get a truecolor class adaptor that has a different
2767    color depth. So try to get a real true color one first */
2768         xvisual_template.depth =    p_vout->p_sys->i_screen_depth;
2769
2770         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2771                                     VisualScreenMask | VisualClassMask |
2772                                     VisualDepthMask,
2773                                     &xvisual_template, &i_count );
2774         if( p_xvisual == NULL )
2775         {
2776             msg_Warn( p_vout, "No screen matching the required color depth" );
2777             p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2778                                     VisualScreenMask | VisualClassMask,
2779                                     &xvisual_template, &i_count );
2780             if( p_xvisual == NULL )
2781             {
2782
2783                 msg_Err( p_vout, "no TrueColor visual available" );
2784                 return VLC_EGENERIC;
2785             }
2786         }
2787
2788         p_vout->output.i_rmask = p_xvisual->red_mask;
2789         p_vout->output.i_gmask = p_xvisual->green_mask;
2790         p_vout->output.i_bmask = p_xvisual->blue_mask;
2791
2792         /* There is no difference yet between 3 and 4 Bpp. The only way
2793          * to find the actual number of bytes per pixel is to list supported
2794          * pixmap formats. */
2795         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
2796         p_vout->p_sys->i_bytes_per_pixel = 0;
2797
2798         for( i = 0; i < i_count; i++ )
2799         {
2800             /* Under XFree4.0, the list contains pixmap formats available
2801              * through all video depths ; so we have to check against current
2802              * depth. */
2803             if( p_formats[i].depth == (int)p_vout->p_sys->i_screen_depth )
2804             {
2805                 if( p_formats[i].bits_per_pixel / 8
2806                         > (int)p_vout->p_sys->i_bytes_per_pixel )
2807                 {
2808                     p_vout->p_sys->i_bytes_per_pixel =
2809                         p_formats[i].bits_per_pixel / 8;
2810                 }
2811             }
2812         }
2813         if( p_formats ) XFree( p_formats );
2814
2815         break;
2816     }
2817     p_vout->p_sys->p_visual = p_xvisual->visual;
2818     XFree( p_xvisual );
2819 #endif
2820
2821     return VLC_SUCCESS;
2822 }
2823
2824 #ifndef MODULE_NAME_IS_glx
2825
2826 #ifdef HAVE_SYS_SHM_H
2827 /*****************************************************************************
2828  * CreateShmImage: create an XImage or XvImage using shared memory extension
2829  *****************************************************************************
2830  * Prepare an XImage or XvImage for display function.
2831  * The order of the operations respects the recommandations of the mit-shm
2832  * document by J.Corbet and K.Packard. Most of the parameters were copied from
2833  * there. See http://ftp.xfree86.org/pub/XFree86/4.0/doc/mit-shm.TXT
2834  *****************************************************************************/
2835 IMAGE_TYPE * CreateShmImage( vout_thread_t *p_vout,
2836                                     Display* p_display, EXTRA_ARGS_SHM,
2837                                     int i_width, int i_height )
2838 {
2839     IMAGE_TYPE *p_image;
2840     Status result;
2841
2842     /* Create XImage / XvImage */
2843 #ifdef MODULE_NAME_IS_xvideo
2844
2845     /* Make sure the buffer is aligned to multiple of 16 */
2846     i_height = ( i_height + 15 ) >> 4 << 4;
2847     i_width = ( i_width + 15 ) >> 4 << 4;
2848
2849     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2850                                 i_width, i_height, p_shm );
2851 #elif defined(MODULE_NAME_IS_xvmc)
2852     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2853                                 i_width, i_height, p_shm );
2854 #else
2855     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2856                                p_shm, i_width, i_height );
2857 #endif
2858     if( p_image == NULL )
2859     {
2860         msg_Err( p_vout, "image creation failed" );
2861         return NULL;
2862     }
2863
2864     /* Allocate shared memory segment - 0776 set the access permission
2865      * rights (like umask), they are not yet supported by all X servers */
2866     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE(p_image), IPC_CREAT | 0776 );
2867     if( p_shm->shmid < 0 )
2868     {
2869         msg_Err( p_vout, "cannot allocate shared image data (%m)" );
2870         IMAGE_FREE( p_image );
2871         return NULL;
2872     }
2873
2874     /* Attach shared memory segment to process (read/write) */
2875     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
2876     if(! p_shm->shmaddr )
2877     {
2878         msg_Err( p_vout, "cannot attach shared memory (%m)" );
2879         IMAGE_FREE( p_image );
2880         shmctl( p_shm->shmid, IPC_RMID, 0 );
2881         return NULL;
2882     }
2883
2884     /* Read-only data. We won't be using XShmGetImage */
2885     p_shm->readOnly = True;
2886
2887     /* Attach shared memory segment to X server */
2888     XSynchronize( p_display, True );
2889     i_shm_major = p_vout->p_sys->i_shm_opcode;
2890     result = XShmAttach( p_display, p_shm );
2891     if( result == False || !i_shm_major )
2892     {
2893         msg_Err( p_vout, "cannot attach shared memory to X server" );
2894         IMAGE_FREE( p_image );
2895         shmctl( p_shm->shmid, IPC_RMID, 0 );
2896         shmdt( p_shm->shmaddr );
2897         return NULL;
2898     }
2899     XSynchronize( p_display, False );
2900
2901     /* Send image to X server. This instruction is required, since having
2902      * built a Shm XImage and not using it causes an error on XCloseDisplay,
2903      * and remember NOT to use XFlush ! */
2904     XSync( p_display, False );
2905
2906 #if 0
2907     /* Mark the shm segment to be removed when there are no more
2908      * attachements, so it is automatic on process exit or after shmdt */
2909     shmctl( p_shm->shmid, IPC_RMID, 0 );
2910 #endif
2911
2912     return p_image;
2913 }
2914 #endif
2915
2916 /*****************************************************************************
2917  * CreateImage: create an XImage or XvImage
2918  *****************************************************************************
2919  * Create a simple image used as a buffer.
2920  *****************************************************************************/
2921 static IMAGE_TYPE * CreateImage( vout_thread_t *p_vout,
2922                                  Display *p_display, EXTRA_ARGS,
2923                                  int i_width, int i_height )
2924 {
2925     uint8_t *    p_data;                          /* image data storage zone */
2926     IMAGE_TYPE *p_image;
2927 #ifdef MODULE_NAME_IS_x11
2928     int         i_quantum;                     /* XImage quantum (see below) */
2929     int         i_bytes_per_line;
2930 #endif
2931
2932     /* Allocate memory for image */
2933 #ifdef MODULE_NAME_IS_xvideo
2934
2935     /* Make sure the buffer is aligned to multiple of 16 */
2936     i_height = ( i_height + 15 ) >> 4 << 4;
2937     i_width = ( i_width + 15 ) >> 4 << 4;
2938
2939     p_data = malloc( i_width * i_height * i_bits_per_pixel / 8 );
2940 #elif defined(MODULE_NAME_IS_x11)
2941     i_bytes_per_line = i_width * i_bytes_per_pixel;
2942     p_data = malloc( i_bytes_per_line * i_height );
2943 #endif
2944     if( !p_data )
2945     {
2946         msg_Err( p_vout, "out of memory" );
2947         return NULL;
2948     }
2949
2950 #ifdef MODULE_NAME_IS_x11
2951     /* Optimize the quantum of a scanline regarding its size - the quantum is
2952        a diviser of the number of bits between the start of two scanlines. */
2953     if( i_bytes_per_line & 0xf )
2954     {
2955         i_quantum = 0x8;
2956     }
2957     else if( i_bytes_per_line & 0x10 )
2958     {
2959         i_quantum = 0x10;
2960     }
2961     else
2962     {
2963         i_quantum = 0x20;
2964     }
2965 #endif
2966
2967     /* Create XImage. p_data will be automatically freed */
2968 #ifdef MODULE_NAME_IS_xvideo
2969     p_image = XvCreateImage( p_display, i_xvport, i_chroma,
2970                              (char *)p_data, i_width, i_height );
2971 #elif defined(MODULE_NAME_IS_x11)
2972     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2973                             (char *)p_data, i_width, i_height, i_quantum, 0 );
2974 #endif
2975     if( p_image == NULL )
2976     {
2977         msg_Err( p_vout, "XCreateImage() failed" );
2978         free( p_data );
2979         return NULL;
2980     }
2981
2982     return p_image;
2983 }
2984
2985 #endif
2986 /*****************************************************************************
2987  * X11ErrorHandler: replace error handler so we can intercept some of them
2988  *****************************************************************************/
2989 static int X11ErrorHandler( Display * display, XErrorEvent * event )
2990 {
2991     char txt[1024];
2992
2993     XGetErrorText( display, event->error_code, txt, sizeof( txt ) );
2994     fprintf( stderr,
2995              "[????????] x11 video output error: X11 request %u.%u failed "
2996               "with error code %u:\n %s\n",
2997              event->request_code, event->minor_code, event->error_code, txt );
2998
2999     switch( event->request_code )
3000     {
3001     case X_SetInputFocus:
3002         /* Ignore errors on XSetInputFocus()
3003          * (they happen when a window is not yet mapped) */
3004         return 0;
3005     }
3006
3007 #ifdef HAVE_SYS_SHM_H
3008     if( event->request_code == i_shm_major ) /* MIT-SHM */
3009         return i_shm_major = 0;
3010 #endif
3011
3012     XSetErrorHandler(NULL);
3013     return (XSetErrorHandler(X11ErrorHandler))( display, event );
3014 }
3015
3016 #ifdef MODULE_NAME_IS_x11
3017 /*****************************************************************************
3018  * SetPalette: sets an 8 bpp palette
3019  *****************************************************************************
3020  * This function sets the palette given as an argument. It does not return
3021  * anything, but could later send information on which colors it was unable
3022  * to set.
3023  *****************************************************************************/
3024 static void SetPalette( vout_thread_t *p_vout,
3025                         uint16_t *red, uint16_t *green, uint16_t *blue )
3026 {
3027     int i;
3028     XColor p_colors[255];
3029
3030     /* allocate palette */
3031     for( i = 0; i < 255; i++ )
3032     {
3033         /* kludge: colors are indexed reversely because color 255 seems
3034          * to be reserved for black even if we try to set it to white */
3035         p_colors[ i ].pixel = 255 - i;
3036         p_colors[ i ].pad   = 0;
3037         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
3038         p_colors[ i ].red   = red[ 255 - i ];
3039         p_colors[ i ].blue  = blue[ 255 - i ];
3040         p_colors[ i ].green = green[ 255 - i ];
3041     }
3042
3043     XStoreColors( p_vout->p_sys->p_display,
3044                   p_vout->p_sys->colormap, p_colors, 255 );
3045 }
3046 #endif
3047
3048 /*****************************************************************************
3049  * Control: control facility for the vout
3050  *****************************************************************************/
3051 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
3052 {
3053     bool b_arg;
3054     unsigned int i_width, i_height;
3055     unsigned int *pi_width, *pi_height;
3056     Drawable d = 0;
3057
3058     switch( i_query )
3059     {
3060         case VOUT_GET_SIZE:
3061             if( p_vout->p_sys->p_win->owner_window )
3062                 return vout_ControlWindow( p_vout,
3063                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
3064
3065             pi_width  = va_arg( args, unsigned int * );
3066             pi_height = va_arg( args, unsigned int * );
3067
3068             vlc_mutex_lock( &p_vout->p_sys->lock );
3069             *pi_width  = p_vout->p_sys->p_win->i_width;
3070             *pi_height = p_vout->p_sys->p_win->i_height;
3071             vlc_mutex_unlock( &p_vout->p_sys->lock );
3072             return VLC_SUCCESS;
3073
3074         case VOUT_SET_SIZE:
3075             if( p_vout->p_sys->p_win->owner_window )
3076                 return vout_ControlWindow( p_vout,
3077                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
3078
3079             vlc_mutex_lock( &p_vout->p_sys->lock );
3080
3081             i_width  = va_arg( args, unsigned int );
3082             i_height = va_arg( args, unsigned int );
3083             if( !i_width ) i_width = p_vout->i_window_width;
3084             if( !i_height ) i_height = p_vout->i_window_height;
3085
3086 #ifdef MODULE_NAME_IS_xvmc
3087             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
3088 #endif
3089             /* Update dimensions */
3090             XResizeWindow( p_vout->p_sys->p_display,
3091                            p_vout->p_sys->p_win->base_window,
3092                            i_width, i_height );
3093 #ifdef MODULE_NAME_IS_xvmc
3094             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
3095 #endif
3096             vlc_mutex_unlock( &p_vout->p_sys->lock );
3097             return VLC_SUCCESS;
3098
3099        case VOUT_CLOSE:
3100             vlc_mutex_lock( &p_vout->p_sys->lock );
3101             XUnmapWindow( p_vout->p_sys->p_display,
3102                           p_vout->p_sys->original_window.base_window );
3103             vlc_mutex_unlock( &p_vout->p_sys->lock );
3104             /* Fall through */
3105
3106        case VOUT_REPARENT:
3107             vlc_mutex_lock( &p_vout->p_sys->lock );
3108             if( i_query == VOUT_REPARENT ) d = (Drawable)va_arg( args, int );
3109             if( !d )
3110             {
3111 #ifdef MODULE_NAME_IS_xvmc
3112             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
3113 #endif
3114             XReparentWindow( p_vout->p_sys->p_display,
3115                              p_vout->p_sys->original_window.base_window,
3116                              DefaultRootWindow( p_vout->p_sys->p_display ),
3117                              0, 0 );
3118             }
3119             else
3120             XReparentWindow( p_vout->p_sys->p_display,
3121                              p_vout->p_sys->original_window.base_window,
3122                              d, 0, 0);
3123             XSync( p_vout->p_sys->p_display, False );
3124             p_vout->p_sys->original_window.owner_window = 0;
3125 #ifdef MODULE_NAME_IS_xvmc
3126             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
3127 #endif
3128             vlc_mutex_unlock( &p_vout->p_sys->lock );
3129             return vout_vaControlDefault( p_vout, i_query, args );
3130
3131         case VOUT_SET_STAY_ON_TOP:
3132             if( p_vout->p_sys->p_win->owner_window )
3133                 return vout_ControlWindow( p_vout,
3134                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
3135
3136             b_arg = (bool) va_arg( args, int );
3137             vlc_mutex_lock( &p_vout->p_sys->lock );
3138 #ifdef MODULE_NAME_IS_xvmc
3139             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
3140 #endif
3141             WindowOnTop( p_vout, b_arg );
3142 #ifdef MODULE_NAME_IS_xvmc
3143             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
3144 #endif
3145             vlc_mutex_unlock( &p_vout->p_sys->lock );
3146             return VLC_SUCCESS;
3147
3148        default:
3149             return vout_vaControlDefault( p_vout, i_query, args );
3150     }
3151 }
3152
3153 /*****************************************************************************
3154  * TestNetWMSupport: tests for Extended Window Manager Hints support
3155  *****************************************************************************/
3156 static void TestNetWMSupport( vout_thread_t *p_vout )
3157 {
3158     int i_ret, i_format;
3159     unsigned long i, i_items, i_bytesafter;
3160     Atom net_wm_supported;
3161     union { Atom *p_atom; unsigned char *p_char; } p_args;
3162
3163     p_args.p_atom = NULL;
3164
3165     p_vout->p_sys->b_net_wm_state_fullscreen =
3166     p_vout->p_sys->b_net_wm_state_above =
3167     p_vout->p_sys->b_net_wm_state_below =
3168     p_vout->p_sys->b_net_wm_state_stays_on_top =
3169         false;
3170
3171     net_wm_supported =
3172         XInternAtom( p_vout->p_sys->p_display, "_NET_SUPPORTED", False );
3173
3174     i_ret = XGetWindowProperty( p_vout->p_sys->p_display,
3175                                 DefaultRootWindow( p_vout->p_sys->p_display ),
3176                                 net_wm_supported,
3177                                 0, 16384, False, AnyPropertyType,
3178                                 &net_wm_supported,
3179                                 &i_format, &i_items, &i_bytesafter,
3180                                 (unsigned char **)&p_args );
3181
3182     if( i_ret != Success || i_items == 0 ) return;
3183
3184     msg_Dbg( p_vout, "Window manager supports NetWM" );
3185
3186     p_vout->p_sys->net_wm_state =
3187         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE", False );
3188     p_vout->p_sys->net_wm_state_fullscreen =
3189         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_FULLSCREEN",
3190                      False );
3191     p_vout->p_sys->net_wm_state_above =
3192         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_ABOVE", False );
3193     p_vout->p_sys->net_wm_state_below =
3194         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_BELOW", False );
3195     p_vout->p_sys->net_wm_state_stays_on_top =
3196         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_STAYS_ON_TOP",
3197                      False );
3198
3199     for( i = 0; i < i_items; i++ )
3200     {
3201         if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_fullscreen )
3202         {
3203             msg_Dbg( p_vout,
3204                      "Window manager supports _NET_WM_STATE_FULLSCREEN" );
3205             p_vout->p_sys->b_net_wm_state_fullscreen = true;
3206         }
3207         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_above )
3208         {
3209             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_ABOVE" );
3210             p_vout->p_sys->b_net_wm_state_above = true;
3211         }
3212         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_below )
3213         {
3214             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_BELOW" );
3215             p_vout->p_sys->b_net_wm_state_below = true;
3216         }
3217         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_stays_on_top )
3218         {
3219             msg_Dbg( p_vout,
3220                      "Window manager supports _NET_WM_STATE_STAYS_ON_TOP" );
3221             p_vout->p_sys->b_net_wm_state_stays_on_top = true;
3222         }
3223     }
3224
3225     XFree( p_args.p_atom );
3226 }
3227
3228 /*****************************************************************************
3229  * Key events handling
3230  *****************************************************************************/
3231 static struct
3232 {
3233     int i_x11key;
3234     int i_vlckey;
3235
3236 } x11keys_to_vlckeys[] =
3237 {
3238     { XK_F1, KEY_F1 }, { XK_F2, KEY_F2 }, { XK_F3, KEY_F3 }, { XK_F4, KEY_F4 },
3239     { XK_F5, KEY_F5 }, { XK_F6, KEY_F6 }, { XK_F7, KEY_F7 }, { XK_F8, KEY_F8 },
3240     { XK_F9, KEY_F9 }, { XK_F10, KEY_F10 }, { XK_F11, KEY_F11 },
3241     { XK_F12, KEY_F12 },
3242
3243     { XK_Return, KEY_ENTER },
3244     { XK_KP_Enter, KEY_ENTER },
3245     { XK_space, KEY_SPACE },
3246     { XK_Escape, KEY_ESC },
3247
3248     { XK_Menu, KEY_MENU },
3249     { XK_Left, KEY_LEFT },
3250     { XK_Right, KEY_RIGHT },
3251     { XK_Up, KEY_UP },
3252     { XK_Down, KEY_DOWN },
3253
3254     { XK_Home, KEY_HOME },
3255     { XK_End, KEY_END },
3256     { XK_Page_Up, KEY_PAGEUP },
3257     { XK_Page_Down, KEY_PAGEDOWN },
3258
3259     { XK_Insert, KEY_INSERT },
3260     { XK_Delete, KEY_DELETE },
3261     { XF86XK_AudioNext, KEY_MEDIA_NEXT_TRACK},
3262     { XF86XK_AudioPrev, KEY_MEDIA_PREV_TRACK},
3263     { XF86XK_AudioMute, KEY_VOLUME_MUTE },
3264     { XF86XK_AudioLowerVolume, KEY_VOLUME_DOWN },
3265     { XF86XK_AudioRaiseVolume, KEY_VOLUME_UP },
3266     { XF86XK_AudioPlay, KEY_MEDIA_PLAY_PAUSE },
3267     { XF86XK_AudioPause, KEY_MEDIA_PLAY_PAUSE },
3268
3269     { 0, 0 }
3270 };
3271
3272 static int ConvertKey( int i_key )
3273 {
3274     int i;
3275
3276     for( i = 0; x11keys_to_vlckeys[i].i_x11key != 0; i++ )
3277     {
3278         if( x11keys_to_vlckeys[i].i_x11key == i_key )
3279         {
3280             return x11keys_to_vlckeys[i].i_vlckey;
3281         }
3282     }
3283
3284     return 0;
3285 }
3286
3287 /*****************************************************************************
3288  * WindowOnTop: Switches the "always on top" state of the video window.
3289  *****************************************************************************/
3290 static int WindowOnTop( vout_thread_t *p_vout, bool b_on_top )
3291 {
3292     if( p_vout->p_sys->b_net_wm_state_stays_on_top )
3293     {
3294         XClientMessageEvent event;
3295
3296         memset( &event, 0, sizeof( XClientMessageEvent ) );
3297
3298         event.type = ClientMessage;
3299         event.message_type = p_vout->p_sys->net_wm_state;
3300         event.display = p_vout->p_sys->p_display;
3301         event.window = p_vout->p_sys->p_win->base_window;
3302         event.format = 32;
3303         event.data.l[ 0 ] = b_on_top; /* set property */
3304         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_stays_on_top;
3305
3306         XSendEvent( p_vout->p_sys->p_display,
3307                     DefaultRootWindow( p_vout->p_sys->p_display ),
3308                     False, SubstructureRedirectMask,
3309                     (XEvent*)&event );
3310     }
3311
3312     /* use _NET_WM_STATE_ABOVE if window manager
3313      * doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
3314     else if( p_vout->p_sys->b_net_wm_state_above )
3315     {
3316         XClientMessageEvent event;
3317
3318         memset( &event, 0, sizeof( XClientMessageEvent ) );
3319
3320         event.type = ClientMessage;
3321         event.message_type = p_vout->p_sys->net_wm_state;
3322         event.display = p_vout->p_sys->p_display;
3323         event.window = p_vout->p_sys->p_win->base_window;
3324         event.format = 32;
3325         event.data.l[ 0 ] = b_on_top; /* set property */
3326         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_above;
3327
3328         XSendEvent( p_vout->p_sys->p_display,
3329                     DefaultRootWindow( p_vout->p_sys->p_display ),
3330                     False, SubstructureRedirectMask,
3331                     (XEvent*)&event );
3332     }
3333
3334     return VLC_SUCCESS;
3335 }