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