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