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