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