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