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