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