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