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