]> git.sesse.net Git - vlc/blob - modules/video_output/x11/xcommon.c
* src/video_output/*, src/libvlc.h, include/video_output.h: added an --align option...
[vlc] / modules / video_output / x11 / xcommon.c
1 /*****************************************************************************
2  * xcommon.c: Functions common to the X11 and XVideo plugins
3  *****************************************************************************
4  * Copyright (C) 1998-2001 VideoLAN
5  * $Id: xcommon.c,v 1.30 2003/08/28 21:11:55 gbazin Exp $
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          David Kennedy <dkennedy@tinytoad.com>
10  *          Gildas Bazin <gbazin@netcourrier.com>
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <errno.h>                                                 /* ENOMEM */
31 #include <stdlib.h>                                                /* free() */
32 #include <string.h>                                            /* strerror() */
33
34 #include <vlc/vlc.h>
35 #include <vlc/intf.h>
36 #include <vlc/vout.h>
37
38 #ifdef HAVE_MACHINE_PARAM_H
39     /* BSD */
40 #   include <machine/param.h>
41 #   include <sys/types.h>                                  /* typedef ushort */
42 #   include <sys/ipc.h>
43 #endif
44
45 #ifndef WIN32
46 #   include <netinet/in.h>                            /* BSD: struct in_addr */
47 #endif
48
49 #ifdef HAVE_SYS_SHM_H
50 #   include <sys/shm.h>                                /* shmget(), shmctl() */
51 #endif
52
53 #include <X11/Xlib.h>
54 #include <X11/Xmd.h>
55 #include <X11/Xutil.h>
56 #include <X11/keysym.h>
57 #ifdef HAVE_SYS_SHM_H
58 #   include <X11/extensions/XShm.h>
59 #endif
60 #ifdef DPMSINFO_IN_DPMS_H
61 #   include <X11/extensions/dpms.h>
62 #endif
63
64 #ifdef MODULE_NAME_IS_xvideo
65 #   include <X11/extensions/Xv.h>
66 #   include <X11/extensions/Xvlib.h>
67 #endif
68
69 #ifdef HAVE_XINERAMA
70 #   include <X11/extensions/Xinerama.h>
71 #endif
72
73 #include "xcommon.h"
74
75 /*****************************************************************************
76  * Local prototypes
77  *****************************************************************************/
78 int  E_(Activate)   ( vlc_object_t * );
79 void E_(Deactivate) ( vlc_object_t * );
80
81 static int  InitVideo      ( vout_thread_t * );
82 static void EndVideo       ( vout_thread_t * );
83 static void DisplayVideo   ( vout_thread_t *, picture_t * );
84 static int  ManageVideo    ( vout_thread_t * );
85
86 static int  InitDisplay    ( vout_thread_t * );
87
88 static int  CreateWindow   ( vout_thread_t *, x11_window_t * );
89 static void DestroyWindow  ( vout_thread_t *, x11_window_t * );
90
91 static int  NewPicture     ( vout_thread_t *, picture_t * );
92 static void FreePicture    ( vout_thread_t *, picture_t * );
93
94 static IMAGE_TYPE *CreateImage    ( vout_thread_t *,
95                                     Display *, EXTRA_ARGS, int, int );
96 #ifdef HAVE_SYS_SHM_H
97 static IMAGE_TYPE *CreateShmImage ( vout_thread_t *,
98                                     Display *, EXTRA_ARGS_SHM, int, int );
99 #endif
100
101 static void ToggleFullScreen      ( vout_thread_t * );
102
103 static void EnableXScreenSaver    ( vout_thread_t * );
104 static void DisableXScreenSaver   ( vout_thread_t * );
105
106 static void CreateCursor   ( vout_thread_t * );
107 static void DestroyCursor  ( vout_thread_t * );
108 static void ToggleCursor   ( vout_thread_t * );
109
110 #ifdef MODULE_NAME_IS_xvideo
111 static int  XVideoGetPort    ( vout_thread_t *, vlc_fourcc_t, vlc_fourcc_t * );
112 static void XVideoReleasePort( vout_thread_t *, int );
113 #endif
114
115 #ifdef MODULE_NAME_IS_x11
116 static void SetPalette     ( vout_thread_t *,
117                              uint16_t *, uint16_t *, uint16_t * );
118 #endif
119
120 static void TestNetWMSupport( vout_thread_t * );
121
122 /*****************************************************************************
123  * Activate: allocate X11 video thread output method
124  *****************************************************************************
125  * This function allocate and initialize a X11 vout method. It uses some of the
126  * vout properties to choose the window size, and change them according to the
127  * actual properties of the display.
128  *****************************************************************************/
129 int E_(Activate) ( vlc_object_t *p_this )
130 {
131     vout_thread_t *p_vout = (vout_thread_t *)p_this;
132     char *       psz_display;
133 #ifdef MODULE_NAME_IS_xvideo
134     char *       psz_chroma;
135     vlc_fourcc_t i_chroma = 0;
136     vlc_bool_t   b_chroma = 0;
137 #endif
138
139     p_vout->pf_init = InitVideo;
140     p_vout->pf_end = EndVideo;
141     p_vout->pf_manage = ManageVideo;
142     p_vout->pf_render = NULL;
143     p_vout->pf_display = DisplayVideo;
144
145     /* Allocate structure */
146     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
147     if( p_vout->p_sys == NULL )
148     {
149         msg_Err( p_vout, "out of memory" );
150         return VLC_ENOMEM;
151     }
152
153     /* Open display, using the "display" config variable or the DISPLAY
154      * environment variable */
155     psz_display = config_GetPsz( p_vout, MODULE_STRING "-display" );
156
157     p_vout->p_sys->p_display = XOpenDisplay( psz_display );
158
159     if( p_vout->p_sys->p_display == NULL )                          /* error */
160     {
161         msg_Err( p_vout, "cannot open display %s",
162                          XDisplayName( psz_display ) );
163         free( p_vout->p_sys );
164         if( psz_display ) free( psz_display );
165         return VLC_EGENERIC;
166     }
167     if( psz_display ) free( psz_display );
168
169     /* Get a screen ID matching the XOpenDisplay return value */
170     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
171
172 #ifdef MODULE_NAME_IS_xvideo
173     psz_chroma = config_GetPsz( p_vout, "xvideo-chroma" );
174     if( psz_chroma )
175     {
176         if( strlen( psz_chroma ) >= 4 )
177         {
178             /* Do not use direct assignment because we are not sure of the
179              * alignment. */
180             memcpy(&i_chroma, psz_chroma, 4);
181             b_chroma = 1;
182         }
183
184         free( psz_chroma );
185     }
186
187     if( b_chroma )
188     {
189         msg_Dbg( p_vout, "forcing chroma 0x%.8x (%4.4s)",
190                  i_chroma, (char*)&i_chroma );
191     }
192     else
193     {
194         i_chroma = p_vout->render.i_chroma;
195     }
196
197     /* Check that we have access to an XVideo port providing this chroma */
198     p_vout->p_sys->i_xvport = XVideoGetPort( p_vout, VLC2X11_FOURCC(i_chroma),
199                                              &p_vout->output.i_chroma );
200     if( p_vout->p_sys->i_xvport < 0 )
201     {
202         /* If a specific chroma format was requested, then we don't try to
203          * be cleverer than the user. He knew pretty well what he wanted. */
204         if( b_chroma )
205         {
206             XCloseDisplay( p_vout->p_sys->p_display );
207             free( p_vout->p_sys );
208             return VLC_EGENERIC;
209         }
210
211         /* It failed, but it's not completely lost ! We try to open an
212          * XVideo port for an YUY2 picture. We'll need to do an YUV
213          * conversion, but at least it has got scaling. */
214         p_vout->p_sys->i_xvport =
215                         XVideoGetPort( p_vout, X11_FOURCC('Y','U','Y','2'),
216                                                &p_vout->output.i_chroma );
217         if( p_vout->p_sys->i_xvport < 0 )
218         {
219             /* It failed, but it's not completely lost ! We try to open an
220              * XVideo port for a simple 16bpp RGB picture. We'll need to do
221              * an YUV conversion, but at least it has got scaling. */
222             p_vout->p_sys->i_xvport =
223                             XVideoGetPort( p_vout, X11_FOURCC('R','V','1','6'),
224                                                    &p_vout->output.i_chroma );
225             if( p_vout->p_sys->i_xvport < 0 )
226             {
227                 XCloseDisplay( p_vout->p_sys->p_display );
228                 free( p_vout->p_sys );
229                 return VLC_EGENERIC;
230             }
231         }
232     }
233     p_vout->output.i_chroma = X112VLC_FOURCC(p_vout->output.i_chroma);
234 #endif
235
236     /* Create blank cursor (for mouse cursor autohiding) */
237     p_vout->p_sys->i_time_mouse_last_moved = mdate();
238     p_vout->p_sys->b_mouse_pointer_visible = 1;
239     CreateCursor( p_vout );
240
241     /* Set main window's size */
242     p_vout->p_sys->original_window.i_width = p_vout->i_window_width;
243     p_vout->p_sys->original_window.i_height = p_vout->i_window_height;
244
245     /* Spawn base window - this window will include the video output window,
246      * but also command buttons, subtitles and other indicators */
247     if( CreateWindow( p_vout, &p_vout->p_sys->original_window ) )
248     {
249         msg_Err( p_vout, "cannot create X11 window" );
250         DestroyCursor( p_vout );
251         XCloseDisplay( p_vout->p_sys->p_display );
252         free( p_vout->p_sys );
253         return VLC_EGENERIC;
254     }
255
256     /* Open and initialize device. */
257     if( InitDisplay( p_vout ) )
258     {
259         msg_Err( p_vout, "cannot initialize X11 display" );
260         DestroyCursor( p_vout );
261         DestroyWindow( p_vout, &p_vout->p_sys->original_window );
262         XCloseDisplay( p_vout->p_sys->p_display );
263         free( p_vout->p_sys );
264         return VLC_EGENERIC;
265     }
266
267     /* Disable screen saver */
268     DisableXScreenSaver( p_vout );
269
270     /* Misc init */
271     p_vout->p_sys->b_altfullscreen = 0;
272     p_vout->p_sys->i_time_button_last_pressed = 0;
273
274     TestNetWMSupport( p_vout );
275
276     return VLC_SUCCESS;
277 }
278
279 /*****************************************************************************
280  * Deactivate: destroy X11 video thread output method
281  *****************************************************************************
282  * Terminate an output method created by Open
283  *****************************************************************************/
284 void E_(Deactivate) ( vlc_object_t *p_this )
285 {
286     vout_thread_t *p_vout = (vout_thread_t *)p_this;
287
288     /* If the fullscreen window is still open, close it */
289     if( p_vout->b_fullscreen )
290     {
291         ToggleFullScreen( p_vout );
292     }
293
294     /* Restore cursor if it was blanked */
295     if( !p_vout->p_sys->b_mouse_pointer_visible )
296     {
297         ToggleCursor( p_vout );
298     }
299
300 #ifdef MODULE_NAME_IS_x11
301     /* Destroy colormap */
302     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
303     {
304         XFreeColormap( p_vout->p_sys->p_display, p_vout->p_sys->colormap );
305     }
306 #else
307     XVideoReleasePort( p_vout, p_vout->p_sys->i_xvport );
308 #endif
309
310     DestroyCursor( p_vout );
311     EnableXScreenSaver( p_vout );
312     DestroyWindow( p_vout, &p_vout->p_sys->original_window );
313
314     XCloseDisplay( p_vout->p_sys->p_display );
315
316     /* Destroy structure */
317     free( p_vout->p_sys );
318 }
319
320 /*****************************************************************************
321  * InitVideo: initialize X11 video thread output method
322  *****************************************************************************
323  * This function create the XImages needed by the output thread. It is called
324  * at the beginning of the thread, but also each time the window is resized.
325  *****************************************************************************/
326 static int InitVideo( vout_thread_t *p_vout )
327 {
328     int i_index;
329     picture_t *p_pic;
330
331     I_OUTPUTPICTURES = 0;
332
333 #ifdef MODULE_NAME_IS_xvideo
334     /* Initialize the output structure; we already found an XVideo port,
335      * and the corresponding chroma we will be using. Since we can
336      * arbitrary scale, stick to the coordinates and aspect. */
337     p_vout->output.i_width  = p_vout->render.i_width;
338     p_vout->output.i_height = p_vout->render.i_height;
339     p_vout->output.i_aspect = p_vout->render.i_aspect;
340
341     switch( p_vout->output.i_chroma )
342     {
343         case VLC_FOURCC('R','V','1','5'):
344             p_vout->output.i_rmask = 0x001f;
345             p_vout->output.i_gmask = 0x07e0;
346             p_vout->output.i_bmask = 0xf800;
347             break;
348         case VLC_FOURCC('R','V','1','6'):
349             p_vout->output.i_rmask = 0x001f;
350             p_vout->output.i_gmask = 0x03e0;
351             p_vout->output.i_bmask = 0x7c00;
352             break;
353     }
354
355 #else
356     /* Initialize the output structure: RGB with square pixels, whatever
357      * the input format is, since it's the only format we know */
358     switch( p_vout->p_sys->i_screen_depth )
359     {
360         case 8: /* FIXME: set the palette */
361             p_vout->output.i_chroma = VLC_FOURCC('R','G','B','2'); break;
362         case 15:
363             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','5'); break;
364         case 16:
365             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','6'); break;
366         case 24:
367             p_vout->output.i_chroma = VLC_FOURCC('R','V','2','4'); break;
368         case 32:
369             p_vout->output.i_chroma = VLC_FOURCC('R','V','2','4'); break;
370         default:
371             msg_Err( p_vout, "unknown screen depth %i",
372                      p_vout->p_sys->i_screen_depth );
373             return VLC_SUCCESS;
374     }
375
376     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
377                        p_vout->p_sys->p_win->i_height,
378                        &i_index, &i_index,
379                        &p_vout->output.i_width, &p_vout->output.i_height );
380
381     /* Assume we have square pixels */
382     p_vout->output.i_aspect = p_vout->output.i_width
383                                * VOUT_ASPECT_FACTOR / p_vout->output.i_height;
384 #endif
385
386     /* Try to initialize up to MAX_DIRECTBUFFERS direct buffers */
387     while( I_OUTPUTPICTURES < MAX_DIRECTBUFFERS )
388     {
389         p_pic = NULL;
390
391         /* Find an empty picture slot */
392         for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
393         {
394           if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
395             {
396                 p_pic = p_vout->p_picture + i_index;
397                 break;
398             }
399         }
400
401         /* Allocate the picture */
402         if( p_pic == NULL || NewPicture( p_vout, p_pic ) )
403         {
404             break;
405         }
406
407         p_pic->i_status = DESTROYED_PICTURE;
408         p_pic->i_type   = DIRECT_PICTURE;
409
410         PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
411
412         I_OUTPUTPICTURES++;
413     }
414
415     return VLC_SUCCESS;
416 }
417
418  /*****************************************************************************
419  * DisplayVideo: displays previously rendered output
420  *****************************************************************************
421  * This function sends the currently rendered image to X11 server.
422  * (The Xv extension takes care of "double-buffering".)
423  *****************************************************************************/
424 static void DisplayVideo( vout_thread_t *p_vout, picture_t *p_pic )
425 {
426     int i_width, i_height, i_x, i_y;
427
428     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
429                        p_vout->p_sys->p_win->i_height,
430                        &i_x, &i_y, &i_width, &i_height );
431
432 #ifdef HAVE_SYS_SHM_H
433     if( p_vout->p_sys->b_shm )
434     {
435         /* Display rendered image using shared memory extension */
436 #   ifdef MODULE_NAME_IS_xvideo
437         XvShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
438                        p_vout->p_sys->p_win->video_window,
439                        p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
440                        0 /*src_x*/, 0 /*src_y*/,
441                        p_vout->output.i_width, p_vout->output.i_height,
442                        0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height,
443                        False /* Don't put True here or you'll waste your CPU */ );
444 #   else
445         XShmPutImage( p_vout->p_sys->p_display,
446                       p_vout->p_sys->p_win->video_window,
447                       p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
448                       0 /*src_x*/, 0 /*src_y*/, 0 /*dest_x*/, 0 /*dest_y*/,
449                       p_vout->output.i_width, p_vout->output.i_height,
450                       False /* Don't put True here ! */ );
451 #   endif
452     }
453     else
454 #endif /* HAVE_SYS_SHM_H */
455     {
456         /* Use standard XPutImage -- this is gonna be slow ! */
457 #ifdef MODULE_NAME_IS_xvideo
458         XvPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
459                     p_vout->p_sys->p_win->video_window,
460                     p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
461                     0 /*src_x*/, 0 /*src_y*/,
462                     p_vout->output.i_width, p_vout->output.i_height,
463                     0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height );
464 #else
465         XPutImage( p_vout->p_sys->p_display,
466                    p_vout->p_sys->p_win->video_window,
467                    p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
468                    0 /*src_x*/, 0 /*src_y*/, 0 /*dest_x*/, 0 /*dest_y*/,
469                    p_vout->output.i_width, p_vout->output.i_height );
470 #endif
471     }
472
473     /* Make sure the command is sent now - do NOT use XFlush !*/
474     XSync( p_vout->p_sys->p_display, False );
475 }
476
477 /*****************************************************************************
478  * ManageVideo: handle X11 events
479  *****************************************************************************
480  * This function should be called regularly by video output thread. It manages
481  * X11 events and allows window resizing. It returns a non null value on
482  * error.
483  *****************************************************************************/
484 static int ManageVideo( vout_thread_t *p_vout )
485 {
486     XEvent      xevent;                                         /* X11 event */
487     char        i_key;                                    /* ISO Latin-1 key */
488     KeySym      x_key_symbol;
489     vlc_value_t val;
490
491     /* Handle X11 events: ConfigureNotify events are parsed to know if the
492      * output window's size changed, MapNotify and UnmapNotify to know if the
493      * window is mapped (and if the display is useful), and ClientMessages
494      * to intercept window destruction requests */
495
496     while( XCheckWindowEvent( p_vout->p_sys->p_display,
497                               p_vout->p_sys->p_win->base_window,
498                               StructureNotifyMask | KeyPressMask |
499                               ButtonPressMask | ButtonReleaseMask |
500                               PointerMotionMask | Button1MotionMask , &xevent )
501            == True )
502     {
503         /* ConfigureNotify event: prepare  */
504         if( xevent.type == ConfigureNotify )
505         {
506             if( (unsigned int)xevent.xconfigure.width
507                    != p_vout->p_sys->p_win->i_width
508               || (unsigned int)xevent.xconfigure.height
509                     != p_vout->p_sys->p_win->i_height )
510             {
511                 /* Update dimensions */
512                 p_vout->i_changes |= VOUT_SIZE_CHANGE;
513                 p_vout->p_sys->p_win->i_width = xevent.xconfigure.width;
514                 p_vout->p_sys->p_win->i_height = xevent.xconfigure.height;
515             }
516         }
517         /* Keyboard event */
518         else if( xevent.type == KeyPress )
519         {
520             /* We may have keys like F1 trough F12, ESC ... */
521             x_key_symbol = XKeycodeToKeysym( p_vout->p_sys->p_display,
522                                              xevent.xkey.keycode, 0 );
523             switch( (int)x_key_symbol )
524             {
525             case XK_Escape:
526                 if( p_vout->b_fullscreen )
527                 {
528                     p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
529                 }
530                 else
531                 {
532                     /* the user wants to close the window */
533                     playlist_t * p_playlist =
534                         (playlist_t *)vlc_object_find( p_vout,
535                                                        VLC_OBJECT_PLAYLIST,
536                                                        FIND_ANYWHERE );
537                     if( p_playlist != NULL )
538                     {
539                         playlist_Stop( p_playlist );
540                         vlc_object_release( p_playlist );
541                     }
542                 }
543                 break;
544             case XK_Menu:
545                 {
546                     intf_thread_t *p_intf;
547                     playlist_t * p_playlist;
548
549                     p_intf = vlc_object_find( p_vout, VLC_OBJECT_INTF,
550                                                       FIND_ANYWHERE );
551                     if( p_intf )
552                     {
553                         p_intf->b_menu_change = 1;
554                         vlc_object_release( p_intf );
555                     }
556
557                     p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
558                                                            FIND_ANYWHERE );
559                     if( p_playlist != NULL )
560                     {
561                         vlc_value_t val;
562                         var_Set( p_playlist, "intf-popupmenu", val );
563                         vlc_object_release( p_playlist );
564                     }
565                 }
566                 break;
567             case XK_Left:
568 /*                input_Seek( p_vout, -5, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR ); */
569                 val.psz_string = "LEFT";
570                 var_Set( p_vout, "key-pressed", val );
571                 break;
572             case XK_Right:
573 /*                input_Seek( p_vout, 5, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR ); */
574                 val.psz_string = "RIGHT";
575                 var_Set( p_vout, "key-pressed", val );
576                 break;
577             case XK_Up:
578 /*                input_Seek( p_vout, 60, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR ); */
579                 val.psz_string = "UP";
580                 var_Set( p_vout, "key-pressed", val );
581                 break;
582             case XK_Down:
583 /*                input_Seek( p_vout, -60, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR ); */
584                 val.psz_string = "DOWN";
585                 var_Set( p_vout, "key-pressed", val );
586                 break;
587             case XK_Return:
588             case XK_KP_Enter:
589                 val.psz_string = "ENTER";
590                 var_Set( p_vout, "key-pressed", val );
591                 break;
592             case XK_Home:
593                 input_Seek( p_vout, 0, INPUT_SEEK_BYTES | INPUT_SEEK_SET );
594                 break;
595             case XK_End:
596                 input_Seek( p_vout, 0, INPUT_SEEK_BYTES | INPUT_SEEK_END );
597                 break;
598             case XK_Page_Up:
599                 input_Seek( p_vout, 10, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR );
600                 break;
601             case XK_Page_Down:
602                 input_Seek( p_vout, -10, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR );
603                 break;
604             case XK_space:
605                 input_SetStatus( p_vout, INPUT_STATUS_PAUSE );
606                 break;
607
608             default:
609                 /* "Normal Keys"
610                  * The reason why I use this instead of XK_0 is that
611                  * with XLookupString, we don't have to care about
612                  * keymaps. */
613
614                 if( XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
615                 {
616                     /* FIXME: handle stuff here */
617                     switch( i_key )
618                     {
619                     case 'q':
620                     case 'Q':
621                         p_vout->p_vlc->b_die = 1;
622                         break;
623                     case 'f':
624                     case 'F':
625                         p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
626                         break;
627
628                     default:
629                         break;
630                     }
631                 }
632                 break;
633             }
634         }
635         /* Mouse click */
636         else if( xevent.type == ButtonPress )
637         {
638             switch( ((XButtonEvent *)&xevent)->button )
639             {
640                 case Button1:
641                     var_Get( p_vout, "mouse-button-down", &val );
642                     val.i_int |= 1;
643                     var_Set( p_vout, "mouse-button-down", val );
644                     
645                     /* detect double-clicks */
646                     if( ( ((XButtonEvent *)&xevent)->time -
647                           p_vout->p_sys->i_time_button_last_pressed ) < 300 )
648                     {
649                         p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
650                     }
651
652                     p_vout->p_sys->i_time_button_last_pressed =
653                         ((XButtonEvent *)&xevent)->time;
654                     break;
655                 case Button2:
656                     var_Get( p_vout, "mouse-button-down", &val );
657                     val.i_int |= 2;
658                     var_Set( p_vout, "mouse-button-down", val );
659                     break;
660                 
661                 case Button3:
662                     var_Get( p_vout, "mouse-button-down", &val );
663                     val.i_int |= 4;
664                     var_Set( p_vout, "mouse-button-down", val );
665                     break;
666                 
667                 case Button4:
668                     var_Get( p_vout, "mouse-button-down", &val );
669                     val.i_int |= 8;
670                     var_Set( p_vout, "mouse-button-down", val );
671                     input_Seek( p_vout, 15, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR );
672                     break;
673
674                 case Button5:
675                     var_Get( p_vout, "mouse-button-down", &val );
676                     val.i_int |= 16;
677                     var_Set( p_vout, "mouse-button-down", val );
678                     input_Seek( p_vout, -15, INPUT_SEEK_SECONDS | INPUT_SEEK_CUR );
679                     break;
680             }
681         }
682         /* Mouse release */
683         else if( xevent.type == ButtonRelease )
684         {
685             switch( ((XButtonEvent *)&xevent)->button )
686             {
687                 case Button1:
688                     var_Get( p_vout, "mouse-button-down", &val );
689                     val.i_int &= ~1;
690                     var_Set( p_vout, "mouse-button-down", val );
691
692                     val.b_bool = VLC_TRUE;
693                     var_Set( p_vout, "mouse-clicked", val );
694                     break;
695                     
696                 case Button2:
697                     {
698                         playlist_t *p_playlist;
699
700                         var_Get( p_vout, "mouse-button-down", &val );
701                         val.i_int &= ~2;
702                         var_Set( p_vout, "mouse-button-down", val );
703
704                         p_playlist = vlc_object_find( p_vout,
705                                                       VLC_OBJECT_PLAYLIST,
706                                                       FIND_ANYWHERE );
707                         if( p_playlist != NULL )
708                         {
709                             vlc_value_t val;
710                             var_Get( p_playlist, "intf-show", &val );
711                             val.b_bool = !val.b_bool;
712                             var_Set( p_playlist, "intf-show", val );
713                             vlc_object_release( p_playlist );
714                         }
715                     }
716                     break;
717                     
718                 case Button3:
719                     {
720                         intf_thread_t *p_intf;
721                         playlist_t *p_playlist;
722
723                         var_Get( p_vout, "mouse-button-down", &val );
724                         val.i_int &= ~4;
725                         var_Set( p_vout, "mouse-button-down", val );
726                         p_intf = vlc_object_find( p_vout, VLC_OBJECT_INTF,
727                                                           FIND_ANYWHERE );
728                         if( p_intf )
729                         {
730                             p_intf->b_menu_change = 1;
731                             vlc_object_release( p_intf );
732                         }
733
734                         p_playlist = vlc_object_find( p_vout,
735                                                       VLC_OBJECT_PLAYLIST,
736                                                       FIND_ANYWHERE );
737                         if( p_playlist != NULL )
738                         {
739                             vlc_value_t val;
740                             var_Set( p_playlist, "intf-popupmenu", val );
741                             vlc_object_release( p_playlist );
742                         }
743                     }
744                     break;
745
746                 case Button4:
747                     var_Get( p_vout, "mouse-button-down", &val );
748                     val.i_int &= ~8;
749                     var_Set( p_vout, "mouse-button-down", val );
750                     break;
751
752                 case Button5:
753                     var_Get( p_vout, "mouse-button-down", &val );
754                     val.i_int &= ~16;
755                     var_Set( p_vout, "mouse-button-down", val );
756                     break;
757                     
758             }
759         }
760         /* Mouse move */
761         else if( xevent.type == MotionNotify )
762         {
763             int i_width, i_height, i_x, i_y;
764             vlc_value_t val;
765
766             /* somewhat different use for vout_PlacePicture:
767              * here the values are needed to give to mouse coordinates
768              * in the original picture space */
769             vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
770                                p_vout->p_sys->p_win->i_height,
771                                &i_x, &i_y, &i_width, &i_height );
772
773             val.i_int = ( xevent.xmotion.x - i_x )
774                          * p_vout->render.i_width / i_width;
775             var_Set( p_vout, "mouse-x", val );
776             val.i_int = ( xevent.xmotion.y - i_y )
777                          * p_vout->render.i_height / i_height;
778             var_Set( p_vout, "mouse-y", val );
779
780             val.b_bool = VLC_TRUE;
781             var_Set( p_vout, "mouse-moved", val );
782
783             p_vout->p_sys->i_time_mouse_last_moved = mdate();
784             if( ! p_vout->p_sys->b_mouse_pointer_visible )
785             {
786                 ToggleCursor( p_vout );
787             }
788         }
789         else if( xevent.type == ReparentNotify /* XXX: why do we get this? */
790                   || xevent.type == MapNotify
791                   || xevent.type == UnmapNotify )
792         {
793             /* Ignore these events */
794         }
795         else /* Other events */
796         {
797             msg_Warn( p_vout, "unhandled event %d received", xevent.type );
798         }
799     }
800
801     /* Handle events for video output sub-window */
802     while( XCheckWindowEvent( p_vout->p_sys->p_display,
803                               p_vout->p_sys->p_win->video_window,
804                               ExposureMask, &xevent ) == True )
805     {
806         /* Window exposed (only handled if stream playback is paused) */
807         if( xevent.type == Expose )
808         {
809             if( ((XExposeEvent *)&xevent)->count == 0 )
810             {
811                 /* (if this is the last a collection of expose events...) */
812 #if 0
813                 if( p_vout->p_vlc->p_input_bank->pp_input[0] != NULL )
814                 {
815                     if( PAUSE_S == p_vout->p_vlc->p_input_bank->pp_input[0]
816                                                    ->stream.control.i_status )
817                     {
818                         /* XVideoDisplay( p_vout )*/;
819                     }
820                 }
821 #endif
822             }
823         }
824     }
825
826     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
827      * are handled - according to the man pages, the format is always 32
828      * in this case */
829     while( XCheckTypedEvent( p_vout->p_sys->p_display,
830                              ClientMessage, &xevent ) )
831     {
832         if( (xevent.xclient.message_type == p_vout->p_sys->p_win->wm_protocols)
833                && ((Atom)xevent.xclient.data.l[0]
834                      == p_vout->p_sys->p_win->wm_delete_window ) )
835         {
836             /* the user wants to close the window */
837             playlist_t * p_playlist =
838                 (playlist_t *)vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
839                                                FIND_ANYWHERE );
840             if( p_playlist != NULL )
841             {
842                 playlist_Stop( p_playlist );
843                 vlc_object_release( p_playlist );
844             }
845         }
846     }
847
848     /*
849      * Fullscreen Change
850      */
851     if ( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
852     {
853         vlc_value_t val;
854
855         /* Update the object variable and trigger callback */
856         val.b_bool = !p_vout->b_fullscreen;
857         var_Set( p_vout, "fullscreen", val );
858
859         ToggleFullScreen( p_vout );
860         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
861     }
862
863     /*
864      * Size change
865      *
866      * (Needs to be placed after VOUT_FULLSREEN_CHANGE because we can activate
867      *  the size flag inside the fullscreen routine)
868      */
869     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
870     {
871         int i_width, i_height, i_x, i_y;
872
873         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
874
875 #ifdef MODULE_NAME_IS_x11
876         /* We need to signal the vout thread about the size change because it
877          * is doing the rescaling */
878         p_vout->i_changes |= VOUT_SIZE_CHANGE;
879 #endif
880
881         vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
882                            p_vout->p_sys->p_win->i_height,
883                            &i_x, &i_y, &i_width, &i_height );
884
885         XMoveResizeWindow( p_vout->p_sys->p_display,
886                            p_vout->p_sys->p_win->video_window,
887                            i_x, i_y, i_width, i_height );
888     }
889
890     /* Autohide Cursour */
891     if( mdate() - p_vout->p_sys->i_time_mouse_last_moved > 2000000 )
892     {
893         /* Hide the mouse automatically */
894         if( p_vout->p_sys->b_mouse_pointer_visible )
895         {
896             ToggleCursor( p_vout );
897         }
898     }
899
900     return 0;
901 }
902
903 /*****************************************************************************
904  * EndVideo: terminate X11 video thread output method
905  *****************************************************************************
906  * Destroy the X11 XImages created by Init. It is called at the end of
907  * the thread, but also each time the window is resized.
908  *****************************************************************************/
909 static void EndVideo( vout_thread_t *p_vout )
910 {
911     int i_index;
912
913     /* Free the direct buffers we allocated */
914     for( i_index = I_OUTPUTPICTURES ; i_index ; )
915     {
916         i_index--;
917         FreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
918     }
919 }
920
921 /* following functions are local */
922
923 /*****************************************************************************
924  * CreateWindow: open and set-up X11 main window
925  *****************************************************************************/
926 static int CreateWindow( vout_thread_t *p_vout, x11_window_t *p_win )
927 {
928     XSizeHints              xsize_hints;
929     XSetWindowAttributes    xwindow_attributes;
930     XGCValues               xgcvalues;
931     XEvent                  xevent;
932
933     vlc_bool_t              b_expose = VLC_FALSE;
934     vlc_bool_t              b_configure_notify = VLC_FALSE;
935     vlc_bool_t              b_map_notify = VLC_FALSE;
936
937     vlc_value_t             val;
938     long long int           i_drawable;
939
940     /* Prepare window manager hints and properties */
941     xsize_hints.base_width          = p_win->i_width;
942     xsize_hints.base_height         = p_win->i_height;
943     xsize_hints.flags               = PSize;
944     p_win->wm_protocols =
945              XInternAtom( p_vout->p_sys->p_display, "WM_PROTOCOLS", True );
946     p_win->wm_delete_window =
947              XInternAtom( p_vout->p_sys->p_display, "WM_DELETE_WINDOW", True );
948
949     /* Prepare window attributes */
950     xwindow_attributes.backing_store = Always;       /* save the hidden part */
951     xwindow_attributes.background_pixel = BlackPixel(p_vout->p_sys->p_display,
952                                                      p_vout->p_sys->i_screen);
953     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
954
955     /* Check whether someone provided us with a window ID */
956     var_Get( p_vout->p_vlc, "drawable", &val );
957     i_drawable = p_vout->b_fullscreen ? 0 : val.i_int;
958
959     if( !i_drawable )
960     {
961         /* Create the window and set hints - the window must receive
962          * ConfigureNotify events, and until it is displayed, Expose and
963          * MapNotify events. */
964
965         p_win->base_window =
966             XCreateWindow( p_vout->p_sys->p_display,
967                            DefaultRootWindow( p_vout->p_sys->p_display ),
968                            0, 0,
969                            p_win->i_width, p_win->i_height,
970                            0,
971                            0, InputOutput, 0,
972                            CWBackingStore | CWBackPixel | CWEventMask,
973                            &xwindow_attributes );
974
975         if( !p_vout->b_fullscreen )
976         {
977             /* Set window manager hints and properties: size hints, command,
978              * window's name, and accepted protocols */
979             XSetWMNormalHints( p_vout->p_sys->p_display,
980                                p_win->base_window, &xsize_hints );
981             XSetCommand( p_vout->p_sys->p_display, p_win->base_window,
982                          p_vout->p_vlc->ppsz_argv, p_vout->p_vlc->i_argc );
983
984             XStoreName( p_vout->p_sys->p_display, p_win->base_window,
985 #ifdef MODULE_NAME_IS_x11
986                         VOUT_TITLE " (X11 output)"
987 #else
988                         VOUT_TITLE " (XVideo output)"
989 #endif
990                       );
991         }
992     }
993     else
994     {
995         /* Get the parent window's geometry information */
996         Window dummy1;
997         unsigned int dummy2, dummy3;
998         XGetGeometry( p_vout->p_sys->p_display, i_drawable,
999                       &dummy1, &dummy2, &dummy3,
1000                       &p_win->i_width,
1001                       &p_win->i_height,
1002                       &dummy2, &dummy3 );
1003
1004         /* We are already configured */
1005         b_configure_notify = VLC_TRUE;
1006
1007         /* From man XSelectInput: only one client at a time can select a
1008          * ButtonPress event, so we need to open a new window anyway. */
1009         p_win->base_window =
1010             XCreateWindow( p_vout->p_sys->p_display,
1011                            i_drawable,
1012                            0, 0,
1013                            p_win->i_width, p_win->i_height,
1014                            0,
1015                            0, CopyFromParent, 0,
1016                            CWBackingStore | CWBackPixel | CWEventMask,
1017                            &xwindow_attributes );
1018     }
1019
1020     if( (p_win->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1021         || (p_win->wm_delete_window == None)
1022         || !XSetWMProtocols( p_vout->p_sys->p_display, p_win->base_window,
1023                              &p_win->wm_delete_window, 1 ) )
1024     {
1025         /* WM_DELETE_WINDOW is not supported by window manager */
1026         msg_Warn( p_vout, "missing or bad window manager" );
1027     }
1028
1029     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1030      * event when using functions like XCopyArea */
1031     xgcvalues.graphics_exposures = False;
1032     p_win->gc = XCreateGC( p_vout->p_sys->p_display,
1033                            p_win->base_window,
1034                            GCGraphicsExposures, &xgcvalues );
1035
1036     /* Send orders to server, and wait until window is displayed - three
1037      * events must be received: a MapNotify event, an Expose event allowing
1038      * drawing in the window, and a ConfigureNotify to get the window
1039      * dimensions. Once those events have been received, only
1040      * ConfigureNotify events need to be received. */
1041     XMapWindow( p_vout->p_sys->p_display, p_win->base_window );
1042     do
1043     {
1044         XNextEvent( p_vout->p_sys->p_display, &xevent);
1045         if( (xevent.type == Expose)
1046             && (xevent.xexpose.window == p_win->base_window) )
1047         {
1048             b_expose = VLC_TRUE;
1049         }
1050         else if( (xevent.type == MapNotify)
1051                  && (xevent.xmap.window == p_win->base_window) )
1052         {
1053             b_map_notify = VLC_TRUE;
1054         }
1055         else if( (xevent.type == ConfigureNotify)
1056                  && (xevent.xconfigure.window == p_win->base_window) )
1057         {
1058             b_configure_notify = VLC_TRUE;
1059             p_win->i_width = xevent.xconfigure.width;
1060             p_win->i_height = xevent.xconfigure.height;
1061         }
1062     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1063
1064     XSelectInput( p_vout->p_sys->p_display, p_win->base_window,
1065                   StructureNotifyMask | KeyPressMask |
1066                   ButtonPressMask | ButtonReleaseMask |
1067                   PointerMotionMask );
1068
1069 #ifdef MODULE_NAME_IS_x11
1070     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1071     {
1072         /* Allocate a new palette */
1073         p_vout->p_sys->colormap =
1074             XCreateColormap( p_vout->p_sys->p_display,
1075                              DefaultRootWindow( p_vout->p_sys->p_display ),
1076                              DefaultVisual( p_vout->p_sys->p_display,
1077                                             p_vout->p_sys->i_screen ),
1078                              AllocAll );
1079
1080         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1081         XChangeWindowAttributes( p_vout->p_sys->p_display, p_win->base_window,
1082                                  CWColormap, &xwindow_attributes );
1083     }
1084 #endif
1085
1086     /* Create video output sub-window. */
1087     p_win->video_window =  XCreateSimpleWindow(
1088                                       p_vout->p_sys->p_display,
1089                                       p_win->base_window, 0, 0,
1090                                       p_win->i_width, p_win->i_height,
1091                                       0,
1092                                       BlackPixel( p_vout->p_sys->p_display,
1093                                                   p_vout->p_sys->i_screen ),
1094                                       WhitePixel( p_vout->p_sys->p_display,
1095                                                   p_vout->p_sys->i_screen ) );
1096
1097     XSetWindowBackground( p_vout->p_sys->p_display, p_win->video_window,
1098                           BlackPixel( p_vout->p_sys->p_display,
1099                                       p_vout->p_sys->i_screen ) );
1100
1101     XMapWindow( p_vout->p_sys->p_display, p_win->video_window );
1102     XSelectInput( p_vout->p_sys->p_display, p_win->video_window,
1103                   ExposureMask );
1104
1105     /* make sure the video window will be centered in the next ManageVideo() */
1106     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1107
1108     /* If the cursor was formerly blank than blank it again */
1109     if( !p_vout->p_sys->b_mouse_pointer_visible )
1110     {
1111         ToggleCursor( p_vout );
1112         ToggleCursor( p_vout );
1113     }
1114
1115     /* Do NOT use XFlush here ! */
1116     XSync( p_vout->p_sys->p_display, False );
1117
1118     /* At this stage, the window is open, displayed, and ready to
1119      * receive data */
1120     p_vout->p_sys->p_win = p_win;
1121
1122     return VLC_SUCCESS;
1123 }
1124
1125 /*****************************************************************************
1126  * DestroyWindow: destroy the window
1127  *****************************************************************************
1128  *
1129  *****************************************************************************/
1130 static void DestroyWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1131 {
1132     /* Do NOT use XFlush here ! */
1133     XSync( p_vout->p_sys->p_display, False );
1134
1135     XDestroyWindow( p_vout->p_sys->p_display, p_win->video_window );
1136     XFreeGC( p_vout->p_sys->p_display, p_win->gc );
1137
1138     XUnmapWindow( p_vout->p_sys->p_display, p_win->base_window );
1139     XDestroyWindow( p_vout->p_sys->p_display, p_win->base_window );
1140 }
1141
1142 /*****************************************************************************
1143  * NewPicture: allocate a picture
1144  *****************************************************************************
1145  * Returns 0 on success, -1 otherwise
1146  *****************************************************************************/
1147 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1148 {
1149     /* We know the chroma, allocate a buffer which will be used
1150      * directly by the decoder */
1151     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1152
1153     if( p_pic->p_sys == NULL )
1154     {
1155         return -1;
1156     }
1157
1158 #ifdef HAVE_SYS_SHM_H
1159     if( p_vout->p_sys->b_shm )
1160     {
1161         /* Create image using XShm extension */
1162         p_pic->p_sys->p_image =
1163             CreateShmImage( p_vout, p_vout->p_sys->p_display,
1164 #   ifdef MODULE_NAME_IS_xvideo
1165                             p_vout->p_sys->i_xvport, p_vout->output.i_chroma,
1166 #   else
1167                             p_vout->p_sys->p_visual,
1168                             p_vout->p_sys->i_screen_depth,
1169 #   endif
1170                             &p_pic->p_sys->shminfo,
1171                             p_vout->output.i_width, p_vout->output.i_height );
1172     }
1173     else
1174 #endif /* HAVE_SYS_SHM_H */
1175     {
1176         /* Create image without XShm extension */
1177         p_pic->p_sys->p_image =
1178             CreateImage( p_vout, p_vout->p_sys->p_display,
1179 #ifdef MODULE_NAME_IS_xvideo
1180                          p_vout->p_sys->i_xvport, p_vout->output.i_chroma,
1181 #else
1182                          p_vout->p_sys->p_visual,
1183                          p_vout->p_sys->i_screen_depth,
1184                          p_vout->p_sys->i_bytes_per_pixel,
1185 #endif
1186                          p_vout->output.i_width, p_vout->output.i_height );
1187     }
1188
1189     if( p_pic->p_sys->p_image == NULL )
1190     {
1191         free( p_pic->p_sys );
1192         return -1;
1193     }
1194
1195     switch( p_vout->output.i_chroma )
1196     {
1197 #ifdef MODULE_NAME_IS_xvideo
1198         case VLC_FOURCC('I','4','2','0'):
1199
1200             p_pic->Y_PIXELS = p_pic->p_sys->p_image->data
1201                                + p_pic->p_sys->p_image->offsets[0];
1202             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1203             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->p_image->pitches[0];
1204             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1205             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width;
1206
1207             p_pic->U_PIXELS = p_pic->p_sys->p_image->data
1208                                + p_pic->p_sys->p_image->offsets[1];
1209             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1210             p_pic->p[U_PLANE].i_pitch = p_pic->p_sys->p_image->pitches[1];
1211             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1212             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2;
1213
1214             p_pic->V_PIXELS = p_pic->p_sys->p_image->data
1215                                + p_pic->p_sys->p_image->offsets[2];
1216             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1217             p_pic->p[V_PLANE].i_pitch = p_pic->p_sys->p_image->pitches[2];
1218             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1219             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2;
1220
1221             p_pic->i_planes = 3;
1222             break;
1223
1224         case VLC_FOURCC('Y','V','1','2'):
1225
1226             p_pic->Y_PIXELS = p_pic->p_sys->p_image->data
1227                                + p_pic->p_sys->p_image->offsets[0];
1228             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1229             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->p_image->pitches[0];
1230             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1231             p_pic->p[Y_PLANE].i_visible_pitch = p_pic->p[Y_PLANE].i_pitch;
1232             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width;
1233
1234             p_pic->U_PIXELS = p_pic->p_sys->p_image->data
1235                                + p_pic->p_sys->p_image->offsets[2];
1236             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1237             p_pic->p[U_PLANE].i_pitch = p_pic->p_sys->p_image->pitches[2];
1238             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1239             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2;
1240
1241             p_pic->V_PIXELS = p_pic->p_sys->p_image->data
1242                                + p_pic->p_sys->p_image->offsets[1];
1243             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1244             p_pic->p[V_PLANE].i_pitch = p_pic->p_sys->p_image->pitches[1];
1245             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1246             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2;
1247
1248             p_pic->i_planes = 3;
1249             break;
1250
1251         case VLC_FOURCC('Y','2','1','1'):
1252
1253             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1254                                   + p_pic->p_sys->p_image->offsets[0];
1255             p_pic->p->i_lines = p_vout->output.i_height;
1256             /* XXX: this just looks so plain wrong... check it out ! */
1257             p_pic->p->i_pitch = p_pic->p_sys->p_image->pitches[0] / 4;
1258             p_pic->p->i_pixel_pitch = 4;
1259             p_pic->p->i_visible_pitch = p_vout->output.i_width * 4;
1260
1261             p_pic->i_planes = 1;
1262             break;
1263
1264         case VLC_FOURCC('Y','U','Y','2'):
1265         case VLC_FOURCC('U','Y','V','Y'):
1266
1267             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1268                                   + p_pic->p_sys->p_image->offsets[0];
1269             p_pic->p->i_lines = p_vout->output.i_height;
1270             p_pic->p->i_pitch = p_pic->p_sys->p_image->pitches[0];
1271             p_pic->p->i_pixel_pitch = 4;
1272             p_pic->p->i_visible_pitch = p_vout->output.i_width * 4;
1273
1274             p_pic->i_planes = 1;
1275             break;
1276
1277         case VLC_FOURCC('R','V','1','5'):
1278
1279             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1280                                   + p_pic->p_sys->p_image->offsets[0];
1281             p_pic->p->i_lines = p_vout->output.i_height;
1282             p_pic->p->i_pitch = p_pic->p_sys->p_image->pitches[0];
1283             p_pic->p->i_pixel_pitch = 2;
1284             p_pic->p->i_visible_pitch = p_vout->output.i_width * 2;
1285
1286             p_pic->i_planes = 1;
1287             break;
1288
1289         case VLC_FOURCC('R','V','1','6'):
1290
1291             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1292                                   + p_pic->p_sys->p_image->offsets[0];
1293             p_pic->p->i_lines = p_vout->output.i_height;
1294             p_pic->p->i_pitch = p_pic->p_sys->p_image->pitches[0];
1295             p_pic->p->i_pixel_pitch = 2;
1296             p_pic->p->i_visible_pitch = p_vout->output.i_width * 2;
1297
1298             p_pic->i_planes = 1;
1299             break;
1300
1301 #else
1302         case VLC_FOURCC('R','G','B','2'):
1303
1304             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1305                                   + p_pic->p_sys->p_image->xoffset;
1306             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
1307             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
1308             p_pic->p->i_pixel_pitch = p_pic->p_sys->p_image->depth;
1309             p_pic->p->i_visible_pitch = p_pic->p_sys->p_image->width;
1310
1311             p_pic->i_planes = 1;
1312
1313             break;
1314
1315         case VLC_FOURCC('R','V','1','6'):
1316         case VLC_FOURCC('R','V','1','5'):
1317
1318             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1319                                   + p_pic->p_sys->p_image->xoffset;
1320             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
1321             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
1322             p_pic->p->i_pixel_pitch = p_pic->p_sys->p_image->depth;
1323             p_pic->p->i_visible_pitch = 2 * p_pic->p_sys->p_image->width;
1324
1325             p_pic->i_planes = 1;
1326
1327             break;
1328
1329         case VLC_FOURCC('R','V','3','2'):
1330         case VLC_FOURCC('R','V','2','4'):
1331
1332             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
1333                                   + p_pic->p_sys->p_image->xoffset;
1334             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
1335             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
1336             p_pic->p->i_pixel_pitch = p_pic->p_sys->p_image->depth;
1337             p_pic->p->i_visible_pitch = 4 * p_pic->p_sys->p_image->width;
1338
1339             p_pic->i_planes = 1;
1340
1341             break;
1342 #endif
1343
1344         default:
1345             /* Unknown chroma, tell the guy to get lost */
1346             IMAGE_FREE( p_pic->p_sys->p_image );
1347             free( p_pic->p_sys );
1348             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1349                      p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
1350             p_pic->i_planes = 0;
1351             return -1;
1352     }
1353
1354     return 0;
1355 }
1356
1357 /*****************************************************************************
1358  * FreePicture: destroy a picture allocated with NewPicture
1359  *****************************************************************************
1360  * Destroy XImage AND associated data. If using Shm, detach shared memory
1361  * segment from server and process, then free it. The XDestroyImage manpage
1362  * says that both the image structure _and_ the data pointed to by the
1363  * image structure are freed, so no need to free p_image->data.
1364  *****************************************************************************/
1365 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
1366 {
1367     /* The order of operations is correct */
1368 #ifdef HAVE_SYS_SHM_H
1369     if( p_vout->p_sys->b_shm )
1370     {
1371         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
1372         IMAGE_FREE( p_pic->p_sys->p_image );
1373
1374         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
1375         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
1376         {
1377             msg_Err( p_vout, "cannot detach shared memory (%s)",
1378                              strerror(errno) );
1379         }
1380     }
1381     else
1382 #endif
1383     {
1384         IMAGE_FREE( p_pic->p_sys->p_image );
1385     }
1386
1387     /* Do NOT use XFlush here ! */
1388     XSync( p_vout->p_sys->p_display, False );
1389
1390     free( p_pic->p_sys );
1391 }
1392
1393 /*****************************************************************************
1394  * ToggleFullScreen: Enable or disable full screen mode
1395  *****************************************************************************
1396  * This function will switch between fullscreen and window mode.
1397  *****************************************************************************/
1398 static void ToggleFullScreen ( vout_thread_t *p_vout )
1399 {
1400     Atom prop;
1401     XEvent xevent;
1402     mwmhints_t mwmhints;
1403     XSetWindowAttributes attributes;
1404
1405 #ifdef HAVE_XINERAMA
1406     int i_d1, i_d2;
1407 #endif
1408
1409     p_vout->b_fullscreen = !p_vout->b_fullscreen;
1410
1411     if( p_vout->b_fullscreen )
1412     {
1413         msg_Dbg( p_vout, "entering fullscreen mode" );
1414
1415         p_vout->p_sys->b_altfullscreen =
1416             config_GetInt( p_vout, MODULE_STRING "-altfullscreen" );
1417
1418         XUnmapWindow( p_vout->p_sys->p_display,
1419                       p_vout->p_sys->p_win->base_window);
1420
1421         p_vout->p_sys->p_win = &p_vout->p_sys->fullscreen_window;
1422
1423         /* fullscreen window size and position */
1424         p_vout->p_sys->p_win->i_width =
1425             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1426         p_vout->p_sys->p_win->i_height =
1427             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1428
1429         CreateWindow( p_vout, p_vout->p_sys->p_win );
1430
1431         /* To my knowledge there are two ways to create a borderless window.
1432          * There's the generic way which is to tell x to bypass the window
1433          * manager, but this creates problems with the focus of other
1434          * applications.
1435          * The other way is to use the motif property "_MOTIF_WM_HINTS" which
1436          * luckily seems to be supported by most window managers. */
1437         if( !p_vout->p_sys->b_altfullscreen )
1438         {
1439             mwmhints.flags = MWM_HINTS_DECORATIONS;
1440             mwmhints.decorations = False;
1441
1442             prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1443                                 False );
1444             XChangeProperty( p_vout->p_sys->p_display,
1445                              p_vout->p_sys->p_win->base_window,
1446                              prop, prop, 32, PropModeReplace,
1447                              (unsigned char *)&mwmhints,
1448                              PROP_MWM_HINTS_ELEMENTS );
1449         }
1450         else
1451         {
1452             /* brute force way to remove decorations */
1453             attributes.override_redirect = True;
1454             XChangeWindowAttributes( p_vout->p_sys->p_display,
1455                                      p_vout->p_sys->p_win->base_window,
1456                                      CWOverrideRedirect,
1457                                      &attributes);
1458
1459             /* Make sure the change is effective */
1460             XReparentWindow( p_vout->p_sys->p_display,
1461                              p_vout->p_sys->p_win->base_window,
1462                              DefaultRootWindow( p_vout->p_sys->p_display ),
1463                              0, 0 );
1464         }
1465
1466         if( p_vout->p_sys->b_net_wm_state_fullscreen )
1467         {
1468             XClientMessageEvent event;
1469
1470             memset( &event, 0, sizeof( XClientMessageEvent ) );
1471
1472             event.type = ClientMessage;
1473             event.message_type = p_vout->p_sys->net_wm_state;
1474             event.display = p_vout->p_sys->p_display;
1475             event.window = p_vout->p_sys->p_win->base_window;
1476             event.format = 32;
1477             event.data.l[ 0 ] = 1; /* set property */
1478             event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_fullscreen;
1479
1480             XSendEvent( p_vout->p_sys->p_display,
1481                         DefaultRootWindow( p_vout->p_sys->p_display ),
1482                         False, SubstructureRedirectMask,
1483                         (XEvent*)&event );
1484         }
1485
1486         /* Make sure the change is effective */
1487         XReparentWindow( p_vout->p_sys->p_display,
1488                          p_vout->p_sys->p_win->base_window,
1489                          DefaultRootWindow( p_vout->p_sys->p_display ),
1490                          0, 0 );
1491
1492         /* fullscreen window size and position */
1493         p_vout->p_sys->p_win->i_width =
1494             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1495         p_vout->p_sys->p_win->i_height =
1496             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1497
1498         p_vout->p_sys->p_win->i_x = 0;
1499         p_vout->p_sys->p_win->i_y = 0;
1500
1501 #ifdef HAVE_XINERAMA
1502         if( XineramaQueryExtension( p_vout->p_sys->p_display, &i_d1, &i_d2 ) &&
1503             XineramaIsActive( p_vout->p_sys->p_display ) )
1504         {
1505             XineramaScreenInfo *screens;   /* infos for xinerama */
1506             int i_num_screens;
1507
1508             msg_Dbg( p_vout, "Using XFree Xinerama extension");
1509
1510 #define SCREEN p_vout->p_sys->p_win->i_screen
1511
1512             /* Get Informations about Xinerama (num of screens) */
1513             screens = XineramaQueryScreens( p_vout->p_sys->p_display,
1514                                             &i_num_screens );
1515
1516             if( !SCREEN )
1517                 SCREEN = config_GetInt( p_vout,
1518                                         MODULE_STRING "-xineramascreen" );
1519
1520             /* just check that user has entered a good value */
1521             if( SCREEN >= i_num_screens || SCREEN < 0 )
1522             {
1523                 msg_Dbg( p_vout, "requested screen number invalid" );
1524                 SCREEN = 0;
1525             }
1526
1527             /* Get the X/Y upper left corner coordinate of the above screen */
1528             p_vout->p_sys->p_win->i_x = screens[SCREEN].x_org;
1529             p_vout->p_sys->p_win->i_y = screens[SCREEN].y_org;
1530
1531             /* Set the Height/width to the screen resolution */
1532             p_vout->p_sys->p_win->i_width = screens[SCREEN].width;
1533             p_vout->p_sys->p_win->i_height = screens[SCREEN].height;
1534
1535             XFree(screens);
1536
1537 #undef SCREEN
1538
1539         }
1540 #endif
1541
1542         XMoveResizeWindow( p_vout->p_sys->p_display,
1543                            p_vout->p_sys->p_win->base_window,
1544                            p_vout->p_sys->p_win->i_x,
1545                            p_vout->p_sys->p_win->i_y,
1546                            p_vout->p_sys->p_win->i_width,
1547                            p_vout->p_sys->p_win->i_height );
1548     }
1549     else
1550     {
1551         msg_Dbg( p_vout, "leaving fullscreen mode" );
1552         DestroyWindow( p_vout, &p_vout->p_sys->fullscreen_window );
1553         p_vout->p_sys->p_win = &p_vout->p_sys->original_window;
1554
1555         XMapWindow( p_vout->p_sys->p_display,
1556                     p_vout->p_sys->p_win->base_window);
1557     }
1558
1559     /* Unfortunately, using XSync() here is not enough to ensure the
1560      * window has already been mapped because the XMapWindow() request
1561      * has not necessarily been sent directly to our window (remember,
1562      * the call is first redirected to the window manager) */
1563     do
1564     {
1565         XWindowEvent( p_vout->p_sys->p_display,
1566                       p_vout->p_sys->p_win->base_window,
1567                       StructureNotifyMask, &xevent );
1568     } while( xevent.type != MapNotify );
1569
1570     /* Be careful, this can generate a BadMatch error if the window is not
1571      * already mapped by the server (see above) */
1572     XSetInputFocus(p_vout->p_sys->p_display,
1573                    p_vout->p_sys->p_win->base_window,
1574                    RevertToParent,
1575                    CurrentTime);
1576
1577     /* signal that the size needs to be updated */
1578     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1579 }
1580
1581 /*****************************************************************************
1582  * EnableXScreenSaver: enable screen saver
1583  *****************************************************************************
1584  * This function enables the screen saver on a display after it has been
1585  * disabled by XDisableScreenSaver.
1586  * FIXME: what happens if multiple vlc sessions are running at the same
1587  *        time ???
1588  *****************************************************************************/
1589 static void EnableXScreenSaver( vout_thread_t *p_vout )
1590 {
1591 #ifdef DPMSINFO_IN_DPMS_H
1592     int dummy;
1593 #endif
1594
1595     if( p_vout->p_sys->i_ss_timeout )
1596     {
1597         XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
1598                          p_vout->p_sys->i_ss_interval,
1599                          p_vout->p_sys->i_ss_blanking,
1600                          p_vout->p_sys->i_ss_exposure );
1601     }
1602
1603     /* Restore DPMS settings */
1604 #ifdef DPMSINFO_IN_DPMS_H
1605     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
1606     {
1607         if( p_vout->p_sys->b_ss_dpms )
1608         {
1609             DPMSEnable( p_vout->p_sys->p_display );
1610         }
1611     }
1612 #endif
1613 }
1614
1615 /*****************************************************************************
1616  * DisableXScreenSaver: disable screen saver
1617  *****************************************************************************
1618  * See XEnableXScreenSaver
1619  *****************************************************************************/
1620 static void DisableXScreenSaver( vout_thread_t *p_vout )
1621 {
1622 #ifdef DPMSINFO_IN_DPMS_H
1623     int dummy;
1624 #endif
1625
1626     /* Save screen saver informations */
1627     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
1628                      &p_vout->p_sys->i_ss_interval,
1629                      &p_vout->p_sys->i_ss_blanking,
1630                      &p_vout->p_sys->i_ss_exposure );
1631
1632     /* Disable screen saver */
1633     if( p_vout->p_sys->i_ss_timeout )
1634     {
1635         XSetScreenSaver( p_vout->p_sys->p_display, 0,
1636                          p_vout->p_sys->i_ss_interval,
1637                          p_vout->p_sys->i_ss_blanking,
1638                          p_vout->p_sys->i_ss_exposure );
1639     }
1640
1641     /* Disable DPMS */
1642 #ifdef DPMSINFO_IN_DPMS_H
1643     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
1644     {
1645         CARD16 unused;
1646         /* Save DPMS current state */
1647         DPMSInfo( p_vout->p_sys->p_display, &unused,
1648                   &p_vout->p_sys->b_ss_dpms );
1649         DPMSDisable( p_vout->p_sys->p_display );
1650    }
1651 #endif
1652 }
1653
1654 /*****************************************************************************
1655  * CreateCursor: create a blank mouse pointer
1656  *****************************************************************************/
1657 static void CreateCursor( vout_thread_t *p_vout )
1658 {
1659     XColor cursor_color;
1660
1661     p_vout->p_sys->cursor_pixmap =
1662         XCreatePixmap( p_vout->p_sys->p_display,
1663                        DefaultRootWindow( p_vout->p_sys->p_display ),
1664                        1, 1, 1 );
1665
1666     XParseColor( p_vout->p_sys->p_display,
1667                  XCreateColormap( p_vout->p_sys->p_display,
1668                                   DefaultRootWindow(
1669                                                     p_vout->p_sys->p_display ),
1670                                   DefaultVisual(
1671                                                 p_vout->p_sys->p_display,
1672                                                 p_vout->p_sys->i_screen ),
1673                                   AllocNone ),
1674                  "black", &cursor_color );
1675
1676     p_vout->p_sys->blank_cursor =
1677         XCreatePixmapCursor( p_vout->p_sys->p_display,
1678                              p_vout->p_sys->cursor_pixmap,
1679                              p_vout->p_sys->cursor_pixmap,
1680                              &cursor_color, &cursor_color, 1, 1 );
1681 }
1682
1683 /*****************************************************************************
1684  * DestroyCursor: destroy the blank mouse pointer
1685  *****************************************************************************/
1686 static void DestroyCursor( vout_thread_t *p_vout )
1687 {
1688     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
1689 }
1690
1691 /*****************************************************************************
1692  * ToggleCursor: hide or show the mouse pointer
1693  *****************************************************************************
1694  * This function hides the X pointer if it is visible by setting the pointer
1695  * sprite to a blank one. To show it again, we disable the sprite.
1696  *****************************************************************************/
1697 static void ToggleCursor( vout_thread_t *p_vout )
1698 {
1699     if( p_vout->p_sys->b_mouse_pointer_visible )
1700     {
1701         XDefineCursor( p_vout->p_sys->p_display,
1702                        p_vout->p_sys->p_win->base_window,
1703                        p_vout->p_sys->blank_cursor );
1704         p_vout->p_sys->b_mouse_pointer_visible = 0;
1705     }
1706     else
1707     {
1708         XUndefineCursor( p_vout->p_sys->p_display,
1709                          p_vout->p_sys->p_win->base_window );
1710         p_vout->p_sys->b_mouse_pointer_visible = 1;
1711     }
1712 }
1713
1714 #ifdef MODULE_NAME_IS_xvideo
1715 /*****************************************************************************
1716  * XVideoGetPort: get YUV12 port
1717  *****************************************************************************/
1718 static int XVideoGetPort( vout_thread_t *p_vout,
1719                           vlc_fourcc_t i_chroma, vlc_fourcc_t *pi_newchroma )
1720 {
1721     XvAdaptorInfo *p_adaptor;
1722     unsigned int i;
1723     int i_adaptor, i_num_adaptors, i_requested_adaptor;
1724     int i_selected_port;
1725
1726     switch( XvQueryExtension( p_vout->p_sys->p_display, &i, &i, &i, &i, &i ) )
1727     {
1728         case Success:
1729             break;
1730
1731         case XvBadExtension:
1732             msg_Warn( p_vout, "XvBadExtension" );
1733             return -1;
1734
1735         case XvBadAlloc:
1736             msg_Warn( p_vout, "XvBadAlloc" );
1737             return -1;
1738
1739         default:
1740             msg_Warn( p_vout, "XvQueryExtension failed" );
1741             return -1;
1742     }
1743
1744     switch( XvQueryAdaptors( p_vout->p_sys->p_display,
1745                              DefaultRootWindow( p_vout->p_sys->p_display ),
1746                              &i_num_adaptors, &p_adaptor ) )
1747     {
1748         case Success:
1749             break;
1750
1751         case XvBadExtension:
1752             msg_Warn( p_vout, "XvBadExtension for XvQueryAdaptors" );
1753             return -1;
1754
1755         case XvBadAlloc:
1756             msg_Warn( p_vout, "XvBadAlloc for XvQueryAdaptors" );
1757             return -1;
1758
1759         default:
1760             msg_Warn( p_vout, "XvQueryAdaptors failed" );
1761             return -1;
1762     }
1763
1764     i_selected_port = -1;
1765     i_requested_adaptor = config_GetInt( p_vout, "xvideo-adaptor" );
1766
1767     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
1768     {
1769         XvImageFormatValues *p_formats;
1770         int i_format, i_num_formats;
1771         int i_port;
1772
1773         /* If we requested an adaptor and it's not this one, we aren't
1774          * interested */
1775         if( i_requested_adaptor != -1 && i_adaptor != i_requested_adaptor )
1776         {
1777             continue;
1778         }
1779
1780         /* If the adaptor doesn't have the required properties, skip it */
1781         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
1782             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
1783         {
1784             continue;
1785         }
1786
1787         /* Check that adaptor supports our requested format... */
1788         p_formats = XvListImageFormats( p_vout->p_sys->p_display,
1789                                         p_adaptor[i_adaptor].base_id,
1790                                         &i_num_formats );
1791
1792         for( i_format = 0;
1793              i_format < i_num_formats && ( i_selected_port == -1 );
1794              i_format++ )
1795         {
1796             /* Code removed, we can get this through xvinfo anyway */
1797 #if 0
1798             XvEncodingInfo  *p_enc;
1799             int             i_enc, i_num_encodings;
1800             XvAttribute     *p_attr;
1801             int             i_attr, i_num_attributes;
1802 #endif
1803
1804             /* If this is not the format we want, or at least a
1805              * similar one, forget it */
1806             if( !vout_ChromaCmp( p_formats[ i_format ].id, i_chroma ) )
1807             {
1808                 continue;
1809             }
1810
1811             /* Look for the first available port supporting this format */
1812             for( i_port = p_adaptor[i_adaptor].base_id;
1813                  ( i_port < (int)(p_adaptor[i_adaptor].base_id
1814                                    + p_adaptor[i_adaptor].num_ports) )
1815                    && ( i_selected_port == -1 );
1816                  i_port++ )
1817             {
1818                 if( XvGrabPort( p_vout->p_sys->p_display, i_port, CurrentTime )
1819                      == Success )
1820                 {
1821                     i_selected_port = i_port;
1822                     *pi_newchroma = p_formats[ i_format ].id;
1823                 }
1824             }
1825
1826             /* If no free port was found, forget it */
1827             if( i_selected_port == -1 )
1828             {
1829                 continue;
1830             }
1831
1832             /* If we found a port, print information about it */
1833             msg_Dbg( p_vout, "adaptor %i, port %i, format 0x%x (%4.4s) %s",
1834                      i_adaptor, i_selected_port, p_formats[ i_format ].id,
1835                      (char *)&p_formats[ i_format ].id,
1836                      ( p_formats[ i_format ].format == XvPacked ) ?
1837                          "packed" : "planar" );
1838
1839 #if 0
1840             msg_Dbg( p_vout, " encoding list:" );
1841
1842             if( XvQueryEncodings( p_vout->p_sys->p_display, i_selected_port,
1843                                   &i_num_encodings, &p_enc )
1844                  != Success )
1845             {
1846                 msg_Dbg( p_vout, "  XvQueryEncodings failed" );
1847                 continue;
1848             }
1849
1850             for( i_enc = 0; i_enc < i_num_encodings; i_enc++ )
1851             {
1852                 msg_Dbg( p_vout, "  id=%ld, name=%s, size=%ldx%ld,"
1853                                       " numerator=%d, denominator=%d",
1854                              p_enc[i_enc].encoding_id, p_enc[i_enc].name,
1855                              p_enc[i_enc].width, p_enc[i_enc].height,
1856                              p_enc[i_enc].rate.numerator,
1857                              p_enc[i_enc].rate.denominator );
1858             }
1859
1860             if( p_enc != NULL )
1861             {
1862                 XvFreeEncodingInfo( p_enc );
1863             }
1864
1865             msg_Dbg( p_vout, " attribute list:" );
1866             p_attr = XvQueryPortAttributes( p_vout->p_sys->p_display,
1867                                             i_selected_port,
1868                                             &i_num_attributes );
1869             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
1870             {
1871                 msg_Dbg( p_vout, "  name=%s, flags=[%s%s ], min=%i, max=%i",
1872                       p_attr[i_attr].name,
1873                       (p_attr[i_attr].flags & XvGettable) ? " get" : "",
1874                       (p_attr[i_attr].flags & XvSettable) ? " set" : "",
1875                       p_attr[i_attr].min_value, p_attr[i_attr].max_value );
1876             }
1877
1878             if( p_attr != NULL )
1879             {
1880                 XFree( p_attr );
1881             }
1882 #endif
1883         }
1884
1885         if( p_formats != NULL )
1886         {
1887             XFree( p_formats );
1888         }
1889
1890     }
1891
1892     if( i_num_adaptors > 0 )
1893     {
1894         XvFreeAdaptorInfo( p_adaptor );
1895     }
1896
1897     if( i_selected_port == -1 )
1898     {
1899         int i_chroma_tmp = X112VLC_FOURCC( i_chroma );
1900         if( i_requested_adaptor == -1 )
1901         {
1902             msg_Warn( p_vout, "no free XVideo port found for format "
1903                       "0x%.8x (%4.4s)", i_chroma_tmp, (char*)&i_chroma_tmp );
1904         }
1905         else
1906         {
1907             msg_Warn( p_vout, "XVideo adaptor %i does not have a free "
1908                       "XVideo port for format 0x%.8x (%4.4s)",
1909                       i_requested_adaptor, i_chroma_tmp, (char*)&i_chroma_tmp );
1910         }
1911     }
1912
1913     return i_selected_port;
1914 }
1915
1916 /*****************************************************************************
1917  * XVideoReleasePort: release YUV12 port
1918  *****************************************************************************/
1919 static void XVideoReleasePort( vout_thread_t *p_vout, int i_port )
1920 {
1921     XvUngrabPort( p_vout->p_sys->p_display, i_port, CurrentTime );
1922 }
1923 #endif
1924
1925 /*****************************************************************************
1926  * InitDisplay: open and initialize X11 device
1927  *****************************************************************************
1928  * Create a window according to video output given size, and set other
1929  * properties according to the display properties.
1930  *****************************************************************************/
1931 static int InitDisplay( vout_thread_t *p_vout )
1932 {
1933 #ifdef MODULE_NAME_IS_x11
1934     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
1935     XVisualInfo *               p_xvisual;           /* visuals informations */
1936     XVisualInfo                 xvisual_template;         /* visual template */
1937     int                         i_count;                       /* array size */
1938 #endif
1939
1940 #ifdef HAVE_SYS_SHM_H
1941     p_vout->p_sys->b_shm = 0;
1942
1943     if( config_GetInt( p_vout, MODULE_STRING "-shm" ) )
1944     {
1945 #   ifdef SYS_DARWIN
1946         /* FIXME: As of 2001-03-16, XFree4 for MacOS X does not support Xshm */
1947 #   else
1948         p_vout->p_sys->b_shm =
1949                   ( XShmQueryExtension( p_vout->p_sys->p_display ) == True );
1950 #   endif
1951
1952         if( !p_vout->p_sys->b_shm )
1953         {
1954             msg_Warn( p_vout, "XShm video extension is unavailable" );
1955         }
1956     }
1957     else
1958     {
1959         msg_Dbg( p_vout, "disabling XShm video extension" );
1960     }
1961
1962 #else
1963     msg_Warn( p_vout, "XShm video extension is unavailable" );
1964
1965 #endif
1966
1967 #ifdef MODULE_NAME_IS_xvideo
1968     /* XXX The brightness and contrast values should be read from environment
1969      * XXX variables... */
1970 #if 0
1971     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
1972     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
1973 #endif
1974 #endif
1975
1976 #ifdef MODULE_NAME_IS_x11
1977     /* Initialize structure */
1978     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
1979
1980     /* Get screen depth */
1981     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
1982                                                    p_vout->p_sys->i_screen );
1983     switch( p_vout->p_sys->i_screen_depth )
1984     {
1985     case 8:
1986         /*
1987          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
1988          */
1989         xvisual_template.screen =   p_vout->p_sys->i_screen;
1990         xvisual_template.class =    DirectColor;
1991         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
1992                                     VisualScreenMask | VisualClassMask,
1993                                     &xvisual_template, &i_count );
1994         if( p_xvisual == NULL )
1995         {
1996             msg_Err( p_vout, "no PseudoColor visual available" );
1997             return VLC_EGENERIC;
1998         }
1999         p_vout->p_sys->i_bytes_per_pixel = 1;
2000         p_vout->output.pf_setpalette = SetPalette;
2001         break;
2002     case 15:
2003     case 16:
2004     case 24:
2005     default:
2006         /*
2007          * Screen depth is higher than 8bpp. TrueColor visual is used.
2008          */
2009         xvisual_template.screen =   p_vout->p_sys->i_screen;
2010         xvisual_template.class =    TrueColor;
2011         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2012                                     VisualScreenMask | VisualClassMask,
2013                                     &xvisual_template, &i_count );
2014         if( p_xvisual == NULL )
2015         {
2016             msg_Err( p_vout, "no TrueColor visual available" );
2017             return VLC_EGENERIC;
2018         }
2019
2020         p_vout->output.i_rmask = p_xvisual->red_mask;
2021         p_vout->output.i_gmask = p_xvisual->green_mask;
2022         p_vout->output.i_bmask = p_xvisual->blue_mask;
2023
2024         /* There is no difference yet between 3 and 4 Bpp. The only way
2025          * to find the actual number of bytes per pixel is to list supported
2026          * pixmap formats. */
2027         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
2028         p_vout->p_sys->i_bytes_per_pixel = 0;
2029
2030         for( ; i_count-- ; p_formats++ )
2031         {
2032             /* Under XFree4.0, the list contains pixmap formats available
2033              * through all video depths ; so we have to check against current
2034              * depth. */
2035             if( p_formats->depth == (int)p_vout->p_sys->i_screen_depth )
2036             {
2037                 if( p_formats->bits_per_pixel / 8
2038                         > (int)p_vout->p_sys->i_bytes_per_pixel )
2039                 {
2040                     p_vout->p_sys->i_bytes_per_pixel =
2041                                                p_formats->bits_per_pixel / 8;
2042                 }
2043             }
2044         }
2045         break;
2046     }
2047     p_vout->p_sys->p_visual = p_xvisual->visual;
2048     XFree( p_xvisual );
2049 #endif
2050
2051     return VLC_SUCCESS;
2052 }
2053
2054 #ifdef HAVE_SYS_SHM_H
2055 /*****************************************************************************
2056  * CreateShmImage: create an XImage or XvImage using shared memory extension
2057  *****************************************************************************
2058  * Prepare an XImage or XvImage for display function.
2059  * The order of the operations respects the recommandations of the mit-shm
2060  * document by J.Corbet and K.Packard. Most of the parameters were copied from
2061  * there. See http://ftp.xfree86.org/pub/XFree86/4.0/doc/mit-shm.TXT
2062  *****************************************************************************/
2063 static IMAGE_TYPE * CreateShmImage( vout_thread_t *p_vout,
2064                                     Display* p_display, EXTRA_ARGS_SHM,
2065                                     int i_width, int i_height )
2066 {
2067     IMAGE_TYPE *p_image;
2068
2069     /* Create XImage / XvImage */
2070 #ifdef MODULE_NAME_IS_xvideo
2071     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2072                                 i_width, i_height, p_shm );
2073 #else
2074     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2075                                p_shm, i_width, i_height );
2076 #endif
2077     if( p_image == NULL )
2078     {
2079         msg_Err( p_vout, "image creation failed" );
2080         return NULL;
2081     }
2082
2083     /* Allocate shared memory segment - 0776 set the access permission
2084      * rights (like umask), they are not yet supported by all X servers */
2085     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE(p_image), IPC_CREAT | 0776 );
2086     if( p_shm->shmid < 0 )
2087     {
2088         msg_Err( p_vout, "cannot allocate shared image data (%s)",
2089                          strerror( errno ) );
2090         IMAGE_FREE( p_image );
2091         return NULL;
2092     }
2093
2094     /* Attach shared memory segment to process (read/write) */
2095     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
2096     if(! p_shm->shmaddr )
2097     {
2098         msg_Err( p_vout, "cannot attach shared memory (%s)",
2099                          strerror(errno));
2100         IMAGE_FREE( p_image );
2101         shmctl( p_shm->shmid, IPC_RMID, 0 );
2102         return NULL;
2103     }
2104
2105     /* Read-only data. We won't be using XShmGetImage */
2106     p_shm->readOnly = True;
2107
2108     /* Attach shared memory segment to X server */
2109     if( XShmAttach( p_display, p_shm ) == False )
2110     {
2111         msg_Err( p_vout, "cannot attach shared memory to X server" );
2112         IMAGE_FREE( p_image );
2113         shmctl( p_shm->shmid, IPC_RMID, 0 );
2114         shmdt( p_shm->shmaddr );
2115         return NULL;
2116     }
2117
2118     /* Send image to X server. This instruction is required, since having
2119      * built a Shm XImage and not using it causes an error on XCloseDisplay,
2120      * and remember NOT to use XFlush ! */
2121     XSync( p_display, False );
2122
2123 #if 0
2124     /* Mark the shm segment to be removed when there are no more
2125      * attachements, so it is automatic on process exit or after shmdt */
2126     shmctl( p_shm->shmid, IPC_RMID, 0 );
2127 #endif
2128
2129     return p_image;
2130 }
2131 #endif
2132
2133 /*****************************************************************************
2134  * CreateImage: create an XImage or XvImage
2135  *****************************************************************************
2136  * Create a simple image used as a buffer.
2137  *****************************************************************************/
2138 static IMAGE_TYPE * CreateImage( vout_thread_t *p_vout,
2139                                  Display *p_display, EXTRA_ARGS,
2140                                  int i_width, int i_height )
2141 {
2142     byte_t *    p_data;                           /* image data storage zone */
2143     IMAGE_TYPE *p_image;
2144 #ifdef MODULE_NAME_IS_x11
2145     int         i_quantum;                     /* XImage quantum (see below) */
2146     int         i_bytes_per_line;
2147 #endif
2148
2149     /* Allocate memory for image */
2150 #ifdef MODULE_NAME_IS_xvideo
2151     p_data = (byte_t *) malloc( i_width * i_height * 2 ); /* XXX */
2152 #else
2153     i_bytes_per_line = i_width * i_bytes_per_pixel;
2154     p_data = (byte_t *) malloc( i_bytes_per_line * i_height );
2155 #endif
2156     if( !p_data )
2157     {
2158         msg_Err( p_vout, "out of memory" );
2159         return NULL;
2160     }
2161
2162 #ifdef MODULE_NAME_IS_x11
2163     /* Optimize the quantum of a scanline regarding its size - the quantum is
2164        a diviser of the number of bits between the start of two scanlines. */
2165     if( i_bytes_per_line & 0xf )
2166     {
2167         i_quantum = 0x8;
2168     }
2169     else if( i_bytes_per_line & 0x10 )
2170     {
2171         i_quantum = 0x10;
2172     }
2173     else
2174     {
2175         i_quantum = 0x20;
2176     }
2177 #endif
2178
2179     /* Create XImage. p_data will be automatically freed */
2180 #ifdef MODULE_NAME_IS_xvideo
2181     p_image = XvCreateImage( p_display, i_xvport, i_chroma,
2182                              p_data, i_width, i_height );
2183 #else
2184     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2185                             p_data, i_width, i_height, i_quantum, 0 );
2186 #endif
2187     if( p_image == NULL )
2188     {
2189         msg_Err( p_vout, "XCreateImage() failed" );
2190         free( p_data );
2191         return NULL;
2192     }
2193
2194     return p_image;
2195 }
2196
2197 #ifdef MODULE_NAME_IS_x11
2198 /*****************************************************************************
2199  * SetPalette: sets an 8 bpp palette
2200  *****************************************************************************
2201  * This function sets the palette given as an argument. It does not return
2202  * anything, but could later send information on which colors it was unable
2203  * to set.
2204  *****************************************************************************/
2205 static void SetPalette( vout_thread_t *p_vout,
2206                         uint16_t *red, uint16_t *green, uint16_t *blue )
2207 {
2208     int i;
2209     XColor p_colors[255];
2210
2211     /* allocate palette */
2212     for( i = 0; i < 255; i++ )
2213     {
2214         /* kludge: colors are indexed reversely because color 255 seems
2215          * to be reserved for black even if we try to set it to white */
2216         p_colors[ i ].pixel = 255 - i;
2217         p_colors[ i ].pad   = 0;
2218         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
2219         p_colors[ i ].red   = red[ 255 - i ];
2220         p_colors[ i ].blue  = blue[ 255 - i ];
2221         p_colors[ i ].green = green[ 255 - i ];
2222     }
2223
2224     XStoreColors( p_vout->p_sys->p_display,
2225                   p_vout->p_sys->colormap, p_colors, 255 );
2226 }
2227 #endif
2228
2229 /*****************************************************************************
2230  * TestNetWMSupport: tests for Extended Window Manager Hints support
2231  *****************************************************************************/
2232 static void TestNetWMSupport( vout_thread_t *p_vout )
2233 {
2234     int i_ret, i_format;
2235     unsigned long i, i_items, i_bytesafter;
2236     Atom net_wm_supported, *p_args = NULL;
2237
2238     p_vout->p_sys->b_net_wm_state_fullscreen = VLC_FALSE;
2239     p_vout->p_sys->b_net_wm_state_above = VLC_FALSE;
2240     p_vout->p_sys->b_net_wm_state_below = VLC_FALSE;
2241     p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_FALSE;
2242
2243     net_wm_supported =
2244         XInternAtom( p_vout->p_sys->p_display, "_NET_SUPPORTED", False );
2245
2246     i_ret = XGetWindowProperty( p_vout->p_sys->p_display,
2247                                 DefaultRootWindow( p_vout->p_sys->p_display ),
2248                                 net_wm_supported,
2249                                 0, 16384, False, AnyPropertyType,
2250                                 &net_wm_supported,
2251                                 &i_format, &i_items, &i_bytesafter,
2252                                 (unsigned char **)&p_args );
2253
2254     if( i_ret != Success || i_items == 0 ) return;
2255
2256     msg_Dbg( p_vout, "Window manager supports NetWM" );
2257
2258     p_vout->p_sys->net_wm_state =
2259         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE", False );
2260     p_vout->p_sys->net_wm_state_fullscreen =
2261         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_FULLSCREEN",
2262                      False );
2263     p_vout->p_sys->net_wm_state_above =
2264         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_ABOVE", False );
2265     p_vout->p_sys->net_wm_state_below =
2266         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_BELOW", False );
2267     p_vout->p_sys->net_wm_state_stays_on_top =
2268         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_STAYS_ON_TOP",
2269                      False );
2270
2271     for( i = 0; i < i_items; i++ )
2272     {
2273         if( p_args[i] == p_vout->p_sys->net_wm_state_fullscreen )
2274         {
2275             msg_Dbg( p_vout,
2276                      "Window manager supports _NET_WM_STATE_FULLSCREEN" );
2277             p_vout->p_sys->b_net_wm_state_fullscreen = VLC_TRUE;
2278         }
2279         else if( p_args[i] == p_vout->p_sys->net_wm_state_above )
2280         {
2281             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_ABOVE" );
2282             p_vout->p_sys->b_net_wm_state_above = VLC_TRUE;
2283         }
2284         else if( p_args[i] == p_vout->p_sys->net_wm_state_below )
2285         {
2286             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_BELOW" );
2287             p_vout->p_sys->b_net_wm_state_below = VLC_TRUE;
2288         }
2289         else if( p_args[i] == p_vout->p_sys->net_wm_state_stays_on_top )
2290         {
2291             msg_Dbg( p_vout,
2292                      "Window manager supports _NET_WM_STATE_STAYS_ON_TOP" );
2293             p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_TRUE;
2294         }
2295     }
2296
2297     XFree( p_args );
2298 }