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