]> git.sesse.net Git - vlc/blob - plugins/x11/vout_x11.c
* Borrowed config.guess and config.sub from SDL [MacOS X port] ;
[vlc] / plugins / x11 / vout_x11.c
1 /*****************************************************************************
2  * vout_x11.c: X11 video output display method
3  *****************************************************************************
4  * Copyright (C) 1998, 1999, 2000 VideoLAN
5  * $Id: vout_x11.c,v 1.16 2001/03/16 22:37:06 massiot Exp $
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 #define MODULE_NAME x11
26 #include "modules_inner.h"
27
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 #include "defs.h"
32
33 #include <errno.h>                                                 /* ENOMEM */
34 #include <stdlib.h>                                                /* free() */
35 #include <string.h>                                            /* strerror() */
36
37 #ifdef HAVE_MACHINE_PARAM_H
38 /* BSD */
39 #include <machine/param.h>
40 #include <sys/types.h>                                     /* typedef ushort */
41 #include <sys/ipc.h>
42 #endif
43
44 #include <sys/shm.h>                                   /* shmget(), shmctl() */
45 #include <X11/Xlib.h>
46 #include <X11/Xutil.h>
47 #include <X11/keysym.h>
48 #include <X11/extensions/XShm.h>
49
50 #include "config.h"
51 #include "common.h"
52 #include "threads.h"
53 #include "mtime.h"
54 #include "tests.h"
55 #include "modules.h"
56
57 #include "video.h"
58 #include "video_output.h"
59
60 #include "interface.h"
61 #include "intf_msg.h"
62
63 #include "main.h"
64
65 /*****************************************************************************
66  * vout_sys_t: video output X11 method descriptor
67  *****************************************************************************
68  * This structure is part of the video output thread descriptor.
69  * It describes the X11 specific properties of an output thread. X11 video
70  * output is performed through regular resizable windows. Windows can be
71  * dynamically resized to adapt to the size of the streams.
72  *****************************************************************************/
73 typedef struct vout_sys_s
74 {
75     /* User settings */
76     boolean_t           b_shm;               /* shared memory extension flag */
77
78     /* Internal settings and properties */
79     Display *           p_display;                        /* display pointer */
80     Visual *            p_visual;                          /* visual pointer */
81     int                 i_screen;                           /* screen number */
82     Window              window;                               /* root window */
83     GC                  gc;              /* graphic context instance handler */
84     Colormap            colormap;               /* colormap used (8bpp only) */
85
86     /* Display buffers and shared memory information */
87     XImage *            p_ximage[2];                       /* XImage pointer */
88     XShmSegmentInfo     shm_info[2];       /* shared memory zone information */
89
90     /* X11 generic properties */
91     Atom                wm_protocols;
92     Atom                wm_delete_window;
93
94     int                 i_width;                     /* width of main window */
95     int                 i_height;                   /* height of main window */
96
97     /* Screen saver properties */
98     int                 i_ss_timeout;                             /* timeout */
99     int                 i_ss_interval;           /* interval between changes */
100     int                 i_ss_blanking;                      /* blanking mode */
101     int                 i_ss_exposure;                      /* exposure mode */
102
103     /* Mouse pointer properties */
104     boolean_t           b_mouse;         /* is the mouse pointer displayed ? */
105
106 } vout_sys_t;
107
108 /*****************************************************************************
109  * Local prototypes
110  *****************************************************************************/
111 static int  vout_Probe     ( probedata_t *p_data );
112 static int  vout_Create    ( struct vout_thread_s * );
113 static int  vout_Init      ( struct vout_thread_s * );
114 static void vout_End       ( struct vout_thread_s * );
115 static void vout_Destroy   ( struct vout_thread_s * );
116 static int  vout_Manage    ( struct vout_thread_s * );
117 static void vout_Display   ( struct vout_thread_s * );
118 static void vout_SetPalette( struct vout_thread_s *, u16*, u16*, u16*, u16* );
119
120 static int  X11CreateWindow     ( vout_thread_t *p_vout );
121 static int  X11InitDisplay      ( vout_thread_t *p_vout, char *psz_display );
122
123 static int  X11CreateImage      ( vout_thread_t *p_vout, XImage **pp_ximage );
124 static void X11DestroyImage     ( XImage *p_ximage );
125 static int  X11CreateShmImage   ( vout_thread_t *p_vout, XImage **pp_ximage,
126                                   XShmSegmentInfo *p_shm_info );
127 static void X11DestroyShmImage  ( vout_thread_t *p_vout, XImage *p_ximage,
128                                   XShmSegmentInfo *p_shm_info );
129
130 static void X11TogglePointer            ( vout_thread_t *p_vout );
131 static void X11EnableScreenSaver        ( vout_thread_t *p_vout );
132 static void X11DisableScreenSaver       ( vout_thread_t *p_vout );
133
134 /*****************************************************************************
135  * Functions exported as capabilities. They are declared as static so that
136  * we don't pollute the namespace too much.
137  *****************************************************************************/
138 void _M( vout_getfunctions )( function_list_t * p_function_list )
139 {
140     p_function_list->pf_probe = vout_Probe;
141     p_function_list->functions.vout.pf_create     = vout_Create;
142     p_function_list->functions.vout.pf_init       = vout_Init;
143     p_function_list->functions.vout.pf_end        = vout_End;
144     p_function_list->functions.vout.pf_destroy    = vout_Destroy;
145     p_function_list->functions.vout.pf_manage     = vout_Manage;
146     p_function_list->functions.vout.pf_display    = vout_Display;
147     p_function_list->functions.vout.pf_setpalette = vout_SetPalette;
148 }
149
150 /*****************************************************************************
151  * vout_Probe: probe the video driver and return a score
152  *****************************************************************************
153  * This function tries to initialize SDL and returns a score to the
154  * plugin manager so that it can select the best plugin.
155  *****************************************************************************/
156 static int vout_Probe( probedata_t *p_data )
157 {
158     if( TestMethod( VOUT_METHOD_VAR, "x11" ) )
159     {
160         return( 999 );
161     }
162
163     return( 50 );
164 }
165
166 /*****************************************************************************
167  * vout_Create: allocate X11 video thread output method
168  *****************************************************************************
169  * This function allocate and initialize a X11 vout method. It uses some of the
170  * vout properties to choose the window size, and change them according to the
171  * actual properties of the display.
172  *****************************************************************************/
173 static int vout_Create( vout_thread_t *p_vout )
174 {
175     char *psz_display;
176
177     /* Allocate structure */
178     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
179     if( p_vout->p_sys == NULL )
180     {
181         intf_ErrMsg("error: %s", strerror(ENOMEM) );
182         return( 1 );
183     }
184
185     /* Open display, unsing 'vlc_display' or DISPLAY environment variable */
186     psz_display = XDisplayName( main_GetPszVariable( VOUT_DISPLAY_VAR, NULL ) );
187     p_vout->p_sys->p_display = XOpenDisplay( psz_display );
188
189     if( p_vout->p_sys->p_display == NULL )                          /* error */
190     {
191         intf_ErrMsg("error: can't open display %s\n", psz_display );
192         free( p_vout->p_sys );
193         return( 1 );
194     }
195     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
196
197     /* Spawn base window - this window will include the video output window,
198      * but also command buttons, subtitles and other indicators */
199     if( X11CreateWindow( p_vout ) )
200     {
201         intf_ErrMsg("error: can't create interface window\n" );
202         XCloseDisplay( p_vout->p_sys->p_display );
203         free( p_vout->p_sys );
204         return( 1 );
205     }
206
207     /* Open and initialize device. This function issues its own error messages.
208      * Since XLib is usually not thread-safe, we can't use the same display
209      * pointer than the interface or another thread. However, the root window
210      * id is still valid. */
211     if( X11InitDisplay( p_vout, psz_display ) )
212     {
213         intf_ErrMsg("error: can't initialize X11 display" );
214         XCloseDisplay( p_vout->p_sys->p_display );
215         free( p_vout->p_sys );
216         return( 1 );
217     }
218
219     p_vout->p_sys->b_mouse = 1;
220
221     /* Disable screen saver and return */
222     X11DisableScreenSaver( p_vout );
223
224     return( 0 );
225 }
226
227 /*****************************************************************************
228  * vout_Init: initialize X11 video thread output method
229  *****************************************************************************
230  * This function create the XImages needed by the output thread. It is called
231  * at the beginning of the thread, but also each time the window is resized.
232  *****************************************************************************/
233 static int vout_Init( vout_thread_t *p_vout )
234 {
235     int i_err;
236
237 #ifdef SYS_DARWIN1_3
238     /* FIXME : As of 2001-03-16, XFree4 for MacOS X does not support Xshm. */
239     p_vout->p_sys->b_shm = 0;
240 #endif
241
242     /* Create XImages using XShm extension - on failure, fall back to regular
243      * way (and destroy the first image if it was created successfully) */
244     if( p_vout->p_sys->b_shm )
245     {
246         /* Create first image */
247         i_err = X11CreateShmImage( p_vout, &p_vout->p_sys->p_ximage[0],
248                                    &p_vout->p_sys->shm_info[0] );
249         if( !i_err )                         /* first image has been created */
250         {
251             /* Create second image */
252             if( X11CreateShmImage( p_vout, &p_vout->p_sys->p_ximage[1],
253                                    &p_vout->p_sys->shm_info[1] ) )
254             {                             /* error creating the second image */
255                 X11DestroyShmImage( p_vout, p_vout->p_sys->p_ximage[0],
256                                     &p_vout->p_sys->shm_info[0] );
257                 i_err = 1;
258             }
259         }
260         if( i_err )                                      /* an error occured */
261         {
262             intf_Msg("vout: XShm video extension unavailable" );
263             p_vout->p_sys->b_shm = 0;
264         }
265     }
266
267     /* Create XImages without XShm extension */
268     if( !p_vout->p_sys->b_shm )
269     {
270         if( X11CreateImage( p_vout, &p_vout->p_sys->p_ximage[0] ) )
271         {
272             intf_ErrMsg("error: can't create images");
273             p_vout->p_sys->p_ximage[0] = NULL;
274             p_vout->p_sys->p_ximage[1] = NULL;
275             return( 1 );
276         }
277         if( X11CreateImage( p_vout, &p_vout->p_sys->p_ximage[1] ) )
278         {
279             intf_ErrMsg("error: can't create images");
280             X11DestroyImage( p_vout->p_sys->p_ximage[0] );
281             p_vout->p_sys->p_ximage[0] = NULL;
282             p_vout->p_sys->p_ximage[1] = NULL;
283             return( 1 );
284         }
285     }
286
287     /* Set bytes per line and initialize buffers */
288     p_vout->i_bytes_per_line = p_vout->p_sys->p_ximage[0]->bytes_per_line;
289     vout_SetBuffers( p_vout, p_vout->p_sys->p_ximage[ 0 ]->data,
290                      p_vout->p_sys->p_ximage[ 1 ]->data );
291     return( 0 );
292 }
293
294 /*****************************************************************************
295  * vout_End: terminate X11 video thread output method
296  *****************************************************************************
297  * Destroy the X11 XImages created by vout_Init. It is called at the end of
298  * the thread, but also each time the window is resized.
299  *****************************************************************************/
300 static void vout_End( vout_thread_t *p_vout )
301 {
302     if( p_vout->p_sys->b_shm )                             /* Shm XImages... */
303     {
304         X11DestroyShmImage( p_vout, p_vout->p_sys->p_ximage[0],
305                             &p_vout->p_sys->shm_info[0] );
306         X11DestroyShmImage( p_vout, p_vout->p_sys->p_ximage[1],
307                             &p_vout->p_sys->shm_info[1] );
308     }
309     else                                          /* ...or regular XImages */
310     {
311         X11DestroyImage( p_vout->p_sys->p_ximage[0] );
312         X11DestroyImage( p_vout->p_sys->p_ximage[1] );
313     }
314 }
315
316 /*****************************************************************************
317  * vout_Destroy: destroy X11 video thread output method
318  *****************************************************************************
319  * Terminate an output method created by vout_CreateOutputMethod
320  *****************************************************************************/
321 static void vout_Destroy( vout_thread_t *p_vout )
322 {
323     /* Enable screen saver */
324     X11EnableScreenSaver( p_vout );
325
326     /* Destroy colormap */
327     if( p_vout->i_screen_depth == 8 )
328     {
329         XFreeColormap( p_vout->p_sys->p_display, p_vout->p_sys->colormap );
330     }
331
332     /* Destroy window */
333     XUnmapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
334     XFreeGC( p_vout->p_sys->p_display, p_vout->p_sys->gc );
335     XDestroyWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
336
337     XCloseDisplay( p_vout->p_sys->p_display );
338
339     /* Destroy structure */
340     free( p_vout->p_sys );
341 }
342
343 /*****************************************************************************
344  * vout_Manage: handle X11 events
345  *****************************************************************************
346  * This function should be called regularly by video output thread. It manages
347  * X11 events and allows window resizing. It returns a non null value on
348  * error.
349  *****************************************************************************/
350 static int vout_Manage( vout_thread_t *p_vout )
351 {
352     XEvent      xevent;                                         /* X11 event */
353     boolean_t   b_resized;                        /* window has been resized */
354     char        i_key;                                    /* ISO Latin-1 key */
355
356     /* Handle X11 events: ConfigureNotify events are parsed to know if the
357      * output window's size changed, MapNotify and UnmapNotify to know if the
358      * window is mapped (and if the display is useful), and ClientMessages
359      * to intercept window destruction requests */
360     b_resized = 0;
361     while( XCheckWindowEvent( p_vout->p_sys->p_display, p_vout->p_sys->window,
362                               StructureNotifyMask | KeyPressMask |
363                               ButtonPressMask | ButtonReleaseMask, &xevent )
364            == True )
365     {
366         /* ConfigureNotify event: prepare  */
367         if( (xevent.type == ConfigureNotify)
368             && ((xevent.xconfigure.width != p_vout->p_sys->i_width)
369                 || (xevent.xconfigure.height != p_vout->p_sys->i_height)) )
370         {
371             /* Update dimensions */
372             b_resized = 1;
373             p_vout->p_sys->i_width = xevent.xconfigure.width;
374             p_vout->p_sys->i_height = xevent.xconfigure.height;
375         }
376         /* MapNotify event: change window status and disable screen saver */
377         else if( xevent.type == MapNotify)
378         {
379             if( (p_vout != NULL) && !p_vout->b_active )
380             {
381                 X11DisableScreenSaver( p_vout );
382                 p_vout->b_active = 1;
383             }
384         }
385         /* UnmapNotify event: change window status and enable screen saver */
386         else if( xevent.type == UnmapNotify )
387         {
388             if( (p_vout != NULL) && p_vout->b_active )
389             {
390                 X11EnableScreenSaver( p_vout );
391                 p_vout->b_active = 0;
392             }
393         }
394         /* Keyboard event */
395         else if( xevent.type == KeyPress )
396         {
397             if( XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
398             {
399                 /* FIXME: handle stuff here */
400                 switch( i_key )
401                 {
402                 case 'q':
403                     /* FIXME: need locking ! */
404                     p_main->p_intf->b_die = 1;
405                     break;
406                 }
407             }
408         }
409         /* Mouse click */
410         else if( xevent.type == ButtonPress )
411         {
412             switch( ((XButtonEvent *)&xevent)->button )
413             {
414                 case Button1:
415                     /* in this part we will eventually manage
416                      * clicks for DVD navigation for instance */
417                     break;
418
419                 case Button2:
420                     X11TogglePointer( p_vout );
421                     break;
422             }
423         }
424         /* Mouse release */
425         else if( xevent.type == ButtonRelease )
426         {
427             switch( ((XButtonEvent *)&xevent)->button )
428             {
429                 case Button3:
430                     /* FIXME: need locking ! */
431                     p_main->p_intf->b_menu_change = 1;
432                     break;
433             }
434         }
435 #ifdef DEBUG
436         /* Other event */
437         else
438         {
439             intf_DbgMsg( "%p -> unhandled event type %d received",
440                          p_vout, xevent.type );
441         }
442 #endif
443     }
444
445     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
446      * are handled - according to the man pages, the format is always 32
447      * in this case */
448     while( XCheckTypedEvent( p_vout->p_sys->p_display,
449                              ClientMessage, &xevent ) )
450     {
451         if( (xevent.xclient.message_type == p_vout->p_sys->wm_protocols)
452             && (xevent.xclient.data.l[0] == p_vout->p_sys->wm_delete_window ) )
453         {
454             p_main->p_intf->b_die = 1;
455         }
456         else
457         {
458             intf_DbgMsg( "%p -> unhandled ClientMessage received", p_vout );
459         }
460     }
461
462     /*
463      * Handle vout window resizing
464      */
465     if( b_resized )
466     {
467         /* If interface window has been resized, change vout size */
468         intf_DbgMsg( "resizing output window" );
469         p_vout->i_width =  p_vout->p_sys->i_width;
470         p_vout->i_height = p_vout->p_sys->i_height;
471         p_vout->i_changes |= VOUT_SIZE_CHANGE;
472     }
473     else if( (p_vout->i_width  != p_vout->p_sys->i_width) ||
474              (p_vout->i_height != p_vout->p_sys->i_height) )
475     {
476         /* If video output size has changed, change interface window size */
477         intf_DbgMsg( "resizing output window" );
478         p_vout->p_sys->i_width =    p_vout->i_width;
479         p_vout->p_sys->i_height =   p_vout->i_height;
480         XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->window,
481                        p_vout->p_sys->i_width, p_vout->p_sys->i_height );
482     }
483     /*
484      * Color/Grayscale or gamma change: in 8bpp, just change the colormap
485      */
486     if( (p_vout->i_changes & VOUT_GRAYSCALE_CHANGE)
487         && (p_vout->i_screen_depth == 8) )
488     {
489         /* FIXME: clear flags ?? */
490     }
491
492     /*
493      * Size change
494      */
495     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
496     {
497         intf_DbgMsg("resizing window");
498         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
499
500         /* Resize window */
501         XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->window,
502                        p_vout->i_width, p_vout->i_height );
503
504         /* Destroy XImages to change their size */
505         vout_End( p_vout );
506
507         /* Recreate XImages. If SysInit failed, the thread can't go on. */
508         if( vout_Init( p_vout ) )
509         {
510             intf_ErrMsg("error: can't resize display");
511             return( 1 );
512        }
513
514         /* Tell the video output thread that it will need to rebuild YUV
515          * tables. This is needed since conversion buffer size may have
516          * changed */
517         p_vout->i_changes |= VOUT_YUV_CHANGE;
518         intf_Msg("vout: video display resized (%dx%d)", p_vout->i_width, p_vout->i_height);
519     }
520
521     return 0;
522 }
523
524 /*****************************************************************************
525  * vout_Display: displays previously rendered output
526  *****************************************************************************
527  * This function send the currently rendered image to X11 server, wait until
528  * it is displayed and switch the two rendering buffer, preparing next frame.
529  *****************************************************************************/
530 static void vout_Display( vout_thread_t *p_vout )
531 {
532     if( p_vout->p_sys->b_shm)                                /* XShm is used */
533     {
534         /* Display rendered image using shared memory extension */
535         XShmPutImage(p_vout->p_sys->p_display, p_vout->p_sys->window, p_vout->p_sys->gc,
536                      p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ],
537                      0, 0, 0, 0,
538                      p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->width,
539                      p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->height, True);
540
541         /* Send the order to the X server */
542         XSync(p_vout->p_sys->p_display, False);
543     }
544     else                                /* regular X11 capabilities are used */
545     {
546         XPutImage(p_vout->p_sys->p_display, p_vout->p_sys->window, p_vout->p_sys->gc,
547                   p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ],
548                   0, 0, 0, 0,
549                   p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->width,
550                   p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->height);
551
552         /* Send the order to the X server */
553         XSync(p_vout->p_sys->p_display, False);
554     }
555 }
556
557 /*****************************************************************************
558  * vout_SetPalette: sets an 8 bpp palette
559  *****************************************************************************
560  * This function sets the palette given as an argument. It does not return
561  * anything, but could later send information on which colors it was unable
562  * to set.
563  *****************************************************************************/
564 static void vout_SetPalette( p_vout_thread_t p_vout,
565                              u16 *red, u16 *green, u16 *blue, u16 *transp )
566 {
567     int i, j;
568     XColor p_colors[255];
569
570     intf_DbgMsg( "Palette change called" );
571
572     /* allocate palette */
573     for( i = 0, j = 255; i < 255; i++, j-- )
574     {
575         /* kludge: colors are indexed reversely because color 255 seems
576          * to be reserved for black even if we try to set it to white */
577         p_colors[ i ].pixel = j;
578         p_colors[ i ].pad   = 0;
579         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
580         p_colors[ i ].red   = red[ j ];
581         p_colors[ i ].blue  = blue[ j ];
582         p_colors[ i ].green = green[ j ];
583     }
584
585     XStoreColors( p_vout->p_sys->p_display,
586                   p_vout->p_sys->colormap, p_colors, 256 );
587 }
588
589 /* following functions are local */
590
591 /*****************************************************************************
592  * X11CreateWindow: open and set-up X11 main window
593  *****************************************************************************/
594 static int X11CreateWindow( vout_thread_t *p_vout )
595 {
596     XSizeHints              xsize_hints;
597     XSetWindowAttributes    xwindow_attributes;
598     XGCValues               xgcvalues;
599     XEvent                  xevent;
600     boolean_t               b_expose;
601     boolean_t               b_configure_notify;
602     boolean_t               b_map_notify;
603
604     /* Set main window's size */
605     p_vout->p_sys->i_width =  main_GetIntVariable( VOUT_WIDTH_VAR,
606                                                    VOUT_WIDTH_DEFAULT );
607     p_vout->p_sys->i_height = main_GetIntVariable( VOUT_HEIGHT_VAR,
608                                                    VOUT_HEIGHT_DEFAULT );
609
610     /* Prepare window manager hints and properties */
611     xsize_hints.base_width          = p_vout->p_sys->i_width;
612     xsize_hints.base_height         = p_vout->p_sys->i_height;
613     xsize_hints.flags               = PSize;
614     p_vout->p_sys->wm_protocols     = XInternAtom( p_vout->p_sys->p_display,
615                                                    "WM_PROTOCOLS", True );
616     p_vout->p_sys->wm_delete_window = XInternAtom( p_vout->p_sys->p_display,
617                                                    "WM_DELETE_WINDOW", True );
618
619     /* Prepare window attributes */
620     xwindow_attributes.backing_store = Always;       /* save the hidden part */
621     xwindow_attributes.background_pixel = WhitePixel( p_vout->p_sys->p_display,
622                                                       p_vout->p_sys->i_screen );
623
624     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
625
626     /* Create the window and set hints - the window must receive ConfigureNotify
627      * events, and, until it is displayed, Expose and MapNotify events. */
628     p_vout->p_sys->window =
629             XCreateWindow( p_vout->p_sys->p_display,
630                            DefaultRootWindow( p_vout->p_sys->p_display ),
631                            0, 0,
632                            p_vout->p_sys->i_width, p_vout->p_sys->i_height, 1,
633                            0, InputOutput, 0,
634                            CWBackingStore | CWBackPixel | CWEventMask,
635                            &xwindow_attributes );
636
637     /* Set window manager hints and properties: size hints, command,
638      * window's name, and accepted protocols */
639     XSetWMNormalHints( p_vout->p_sys->p_display, p_vout->p_sys->window,
640                        &xsize_hints );
641     XSetCommand( p_vout->p_sys->p_display, p_vout->p_sys->window,
642                  p_main->ppsz_argv, p_main->i_argc );
643     XStoreName( p_vout->p_sys->p_display, p_vout->p_sys->window,
644                 VOUT_TITLE " (X11 output)" );
645
646     if( (p_vout->p_sys->wm_protocols == None)        /* use WM_DELETE_WINDOW */
647         || (p_vout->p_sys->wm_delete_window == None)
648         || !XSetWMProtocols( p_vout->p_sys->p_display, p_vout->p_sys->window,
649                              &p_vout->p_sys->wm_delete_window, 1 ) )
650     {
651         /* WM_DELETE_WINDOW is not supported by window manager */
652         intf_Msg( "intf error: missing or bad window manager" );
653     }
654
655     /* Creation of a graphic context that doesn't generate a GraphicsExpose
656      * event when using functions like XCopyArea */
657     xgcvalues.graphics_exposures = False;
658     p_vout->p_sys->gc = XCreateGC( p_vout->p_sys->p_display,
659                                    p_vout->p_sys->window,
660                                    GCGraphicsExposures, &xgcvalues);
661
662     /* Send orders to server, and wait until window is displayed - three
663      * events must be received: a MapNotify event, an Expose event allowing
664      * drawing in the window, and a ConfigureNotify to get the window
665      * dimensions. Once those events have been received, only ConfigureNotify
666      * events need to be received. */
667     b_expose = 0;
668     b_configure_notify = 0;
669     b_map_notify = 0;
670     XMapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window);
671     do
672     {
673         XNextEvent( p_vout->p_sys->p_display, &xevent);
674         if( (xevent.type == Expose)
675             && (xevent.xexpose.window == p_vout->p_sys->window) )
676         {
677             b_expose = 1;
678         }
679         else if( (xevent.type == MapNotify)
680                  && (xevent.xmap.window == p_vout->p_sys->window) )
681         {
682             b_map_notify = 1;
683         }
684         else if( (xevent.type == ConfigureNotify)
685                  && (xevent.xconfigure.window == p_vout->p_sys->window) )
686         {
687             b_configure_notify = 1;
688             p_vout->p_sys->i_width = xevent.xconfigure.width;
689             p_vout->p_sys->i_height = xevent.xconfigure.height;
690         }
691     } while( !( b_expose && b_configure_notify && b_map_notify ) );
692
693     XSelectInput( p_vout->p_sys->p_display, p_vout->p_sys->window,
694                   StructureNotifyMask | KeyPressMask |
695                   ButtonPressMask | ButtonReleaseMask );
696
697     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
698     {
699         /* Allocate a new palette */
700         p_vout->p_sys->colormap =
701             XCreateColormap( p_vout->p_sys->p_display,
702                              DefaultRootWindow( p_vout->p_sys->p_display ),
703                              DefaultVisual( p_vout->p_sys->p_display,
704                                             p_vout->p_sys->i_screen ),
705                              AllocAll );
706
707         xwindow_attributes.colormap = p_vout->p_sys->colormap;
708         XChangeWindowAttributes( p_vout->p_sys->p_display,
709                                  p_vout->p_sys->window,
710                                  CWColormap, &xwindow_attributes );
711     }
712
713     /* At this stage, the window is open, displayed, and ready to
714      * receive data */
715     return( 0 );
716 }
717
718 /*****************************************************************************
719  * X11InitDisplay: open and initialize X11 device
720  *****************************************************************************
721  * Create a window according to video output given size, and set other
722  * properties according to the display properties.
723  *****************************************************************************/
724 static int X11InitDisplay( vout_thread_t *p_vout, char *psz_display )
725 {
726     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
727     XVisualInfo *               p_xvisual;           /* visuals informations */
728     XVisualInfo                 xvisual_template;         /* visual template */
729     int                         i_count;                       /* array size */
730
731     /* Initialize structure */
732     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
733     p_vout->p_sys->b_shm    = ( XShmQueryExtension( p_vout->p_sys->p_display )
734                                  == True );
735     if( !p_vout->p_sys->b_shm )
736     {
737         intf_Msg("vout: XShm video extension is not available");
738     }
739
740     /* Get screen depth */
741     p_vout->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
742                                             p_vout->p_sys->i_screen );
743     switch( p_vout->i_screen_depth )
744     {
745     case 8:
746         /*
747          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
748          */
749         xvisual_template.screen =   p_vout->p_sys->i_screen;
750         xvisual_template.class =    DirectColor;
751         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
752                                     VisualScreenMask | VisualClassMask,
753                                     &xvisual_template, &i_count );
754         if( p_xvisual == NULL )
755         {
756             intf_ErrMsg("vout error: no PseudoColor visual available");
757             return( 1 );
758         }
759         p_vout->i_bytes_per_pixel = 1;
760         break;
761     case 15:
762     case 16:
763     case 24:
764     default:
765         /*
766          * Screen depth is higher than 8bpp. TrueColor visual is used.
767          */
768         xvisual_template.screen =   p_vout->p_sys->i_screen;
769         xvisual_template.class =    TrueColor;
770         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
771                                     VisualScreenMask | VisualClassMask,
772                                     &xvisual_template, &i_count );
773         if( p_xvisual == NULL )
774         {
775             intf_ErrMsg("vout error: no TrueColor visual available");
776             return( 1 );
777         }
778         p_vout->i_red_mask =        p_xvisual->red_mask;
779         p_vout->i_green_mask =      p_xvisual->green_mask;
780         p_vout->i_blue_mask =       p_xvisual->blue_mask;
781
782         /* There is no difference yet between 3 and 4 Bpp. The only way
783          * to find the actual number of bytes per pixel is to list supported
784          * pixmap formats. */
785         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
786         p_vout->i_bytes_per_pixel = 0;
787
788         for( ; i_count-- ; p_formats++ )
789         {
790             /* Under XFree4.0, the list contains pixmap formats available
791              * through all video depths ; so we have to check against current
792              * depth. */
793             if( p_formats->depth == p_vout->i_screen_depth )
794             {
795                 if( p_formats->bits_per_pixel / 8
796                         > p_vout->i_bytes_per_pixel )
797                 {
798                     p_vout->i_bytes_per_pixel = p_formats->bits_per_pixel / 8;
799                 }
800             }
801         }
802         break;
803     }
804     p_vout->p_sys->p_visual = p_xvisual->visual;
805     XFree( p_xvisual );
806
807     return( 0 );
808 }
809
810 /*****************************************************************************
811  * X11CreateImage: create an XImage
812  *****************************************************************************
813  * Create a simple XImage used as a buffer.
814  *****************************************************************************/
815 static int X11CreateImage( vout_thread_t *p_vout, XImage **pp_ximage )
816 {
817     byte_t *    pb_data;                          /* image data storage zone */
818     int         i_quantum;                     /* XImage quantum (see below) */
819
820     /* Allocate memory for image */
821     p_vout->i_bytes_per_line = p_vout->i_width * p_vout->i_bytes_per_pixel;
822     pb_data = (byte_t *) malloc( p_vout->i_bytes_per_line * p_vout->i_height );
823     if( !pb_data )                                                  /* error */
824     {
825         intf_ErrMsg("error: %s", strerror(ENOMEM));
826         return( 1 );
827     }
828
829     /* Optimize the quantum of a scanline regarding its size - the quantum is
830        a diviser of the number of bits between the start of two scanlines. */
831     if( !(( p_vout->i_bytes_per_line ) % 32) )
832     {
833         i_quantum = 32;
834     }
835     else
836     {
837         if( !(( p_vout->i_bytes_per_line ) % 16) )
838         {
839             i_quantum = 16;
840         }
841         else
842         {
843             i_quantum = 8;
844         }
845     }
846
847     /* Create XImage */
848     *pp_ximage = XCreateImage( p_vout->p_sys->p_display,
849                                p_vout->p_sys->p_visual, p_vout->i_screen_depth,
850                                ZPixmap, 0, pb_data,
851                                p_vout->i_width, p_vout->i_height, i_quantum, 0);
852     if(! *pp_ximage )                                               /* error */
853     {
854         intf_ErrMsg( "error: XCreateImage() failed" );
855         free( pb_data );
856         return( 1 );
857     }
858
859     return 0;
860 }
861
862 /*****************************************************************************
863  * X11CreateShmImage: create an XImage using shared memory extension
864  *****************************************************************************
865  * Prepare an XImage for DisplayX11ShmImage function.
866  * The order of the operations respects the recommandations of the mit-shm
867  * document by J.Corbet and K.Packard. Most of the parameters were copied from
868  * there.
869  *****************************************************************************/
870 static int X11CreateShmImage( vout_thread_t *p_vout, XImage **pp_ximage,
871                               XShmSegmentInfo *p_shm_info)
872 {
873     /* Create XImage */
874     *pp_ximage =
875         XShmCreateImage( p_vout->p_sys->p_display, p_vout->p_sys->p_visual,
876                          p_vout->i_screen_depth, ZPixmap, 0,
877                          p_shm_info, p_vout->i_width, p_vout->i_height );
878     if(! *pp_ximage )                                               /* error */
879     {
880         intf_ErrMsg("error: XShmCreateImage() failed");
881         return( 1 );
882     }
883
884     /* Allocate shared memory segment - 0777 set the access permission
885      * rights (like umask), they are not yet supported by X servers */
886     p_shm_info->shmid =
887         shmget( IPC_PRIVATE, (*pp_ximage)->bytes_per_line
888                                  * (*pp_ximage)->height, IPC_CREAT | 0777);
889     if( p_shm_info->shmid < 0)                                      /* error */
890     {
891         intf_ErrMsg("error: can't allocate shared image data (%s)",
892                     strerror(errno));
893         XDestroyImage( *pp_ximage );
894         return( 1 );
895     }
896
897     /* Attach shared memory segment to process (read/write) */
898     p_shm_info->shmaddr = (*pp_ximage)->data = shmat(p_shm_info->shmid, 0, 0);
899     if(! p_shm_info->shmaddr )
900     {                                                               /* error */
901         intf_ErrMsg("error: can't attach shared memory (%s)",
902                     strerror(errno));
903         shmctl( p_shm_info->shmid, IPC_RMID, 0 );      /* free shared memory */
904         XDestroyImage( *pp_ximage );
905         return( 1 );
906     }
907
908     /* Mark the shm segment to be removed when there will be no more
909      * attachements, so it is automatic on process exit or after shmdt */
910     shmctl( p_shm_info->shmid, IPC_RMID, 0 );
911
912     /* Attach shared memory segment to X server (read only) */
913     p_shm_info->readOnly = True;
914     if( XShmAttach( p_vout->p_sys->p_display, p_shm_info )
915          == False )                                                 /* error */
916     {
917         intf_ErrMsg("error: can't attach shared memory to X11 server");
918         shmdt( p_shm_info->shmaddr );   /* detach shared memory from process
919                                          * and automatic free */
920         XDestroyImage( *pp_ximage );
921         return( 1 );
922     }
923
924     /* Send image to X server. This instruction is required, since having
925      * built a Shm XImage and not using it causes an error on XCloseDisplay */
926     XFlush( p_vout->p_sys->p_display );
927     return( 0 );
928 }
929
930 /*****************************************************************************
931  * X11DestroyImage: destroy an XImage
932  *****************************************************************************
933  * Destroy XImage AND associated data. If pointer is NULL, the image won't be
934  * destroyed (see vout_ManageOutputMethod())
935  *****************************************************************************/
936 static void X11DestroyImage( XImage *p_ximage )
937 {
938     if( p_ximage != NULL )
939     {
940         XDestroyImage( p_ximage );                     /* no free() required */
941     }
942 }
943
944 /*****************************************************************************
945  * X11DestroyShmImage
946  *****************************************************************************
947  * Destroy XImage AND associated data. Detach shared memory segment from
948  * server and process, then free it. If pointer is NULL, the image won't be
949  * destroyed (see vout_ManageOutputMethod())
950  *****************************************************************************/
951 static void X11DestroyShmImage( vout_thread_t *p_vout, XImage *p_ximage,
952                                 XShmSegmentInfo *p_shm_info )
953 {
954     /* If pointer is NULL, do nothing */
955     if( p_ximage == NULL )
956     {
957         return;
958     }
959
960     XShmDetach( p_vout->p_sys->p_display, p_shm_info );/* detach from server */
961     XDestroyImage( p_ximage );
962
963     if( shmdt( p_shm_info->shmaddr ) )  /* detach shared memory from process */
964     {                                   /* also automatic freeing...         */
965         intf_ErrMsg( "error: can't detach shared memory (%s)",
966                      strerror(errno) );
967     }
968 }
969
970
971 /* WAZAAAAAAAAAAA */
972
973 /*****************************************************************************
974  * X11EnableScreenSaver: enable screen saver
975  *****************************************************************************
976  * This function enable the screen saver on a display after it had been
977  * disabled by XDisableScreenSaver. Both functions use a counter mechanism to
978  * know wether the screen saver can be activated or not: if n successive calls
979  * are made to XDisableScreenSaver, n successive calls to XEnableScreenSaver
980  * will be required before the screen saver could effectively be activated.
981  *****************************************************************************/
982 void X11EnableScreenSaver( vout_thread_t *p_vout )
983 {
984     intf_DbgMsg( "intf: enabling screen saver" );
985     XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
986                      p_vout->p_sys->i_ss_interval,
987                      p_vout->p_sys->i_ss_blanking,
988                      p_vout->p_sys->i_ss_exposure );
989 }
990
991 /*****************************************************************************
992  * X11DisableScreenSaver: disable screen saver
993  *****************************************************************************
994  * See XEnableScreenSaver
995  *****************************************************************************/
996 void X11DisableScreenSaver( vout_thread_t *p_vout )
997 {
998     /* Save screen saver informations */
999     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
1000                      &p_vout->p_sys->i_ss_interval,
1001                      &p_vout->p_sys->i_ss_blanking,
1002                      &p_vout->p_sys->i_ss_exposure );
1003
1004     /* Disable screen saver */
1005     intf_DbgMsg("intf: disabling screen saver");
1006     XSetScreenSaver( p_vout->p_sys->p_display, 0,
1007                      p_vout->p_sys->i_ss_interval,
1008                      p_vout->p_sys->i_ss_blanking,
1009                      p_vout->p_sys->i_ss_exposure );
1010 }
1011
1012 /*****************************************************************************
1013  * X11TogglePointer: hide or show the mouse pointer
1014  *****************************************************************************
1015  * This function hides the X pointer if it is visible by putting it at
1016  * coordinates (32,32) and setting the pointer sprite to a blank one. To
1017  * show it again, we disable the sprite and restore the original coordinates.
1018  *****************************************************************************/
1019 void X11TogglePointer( vout_thread_t *p_vout )
1020 {
1021     static Cursor cursor;
1022     static boolean_t b_cursor = 0;
1023
1024     if( p_vout->p_sys->b_mouse )
1025     {
1026         p_vout->p_sys->b_mouse = 0;
1027
1028         if( !b_cursor )
1029         {
1030             XColor color;
1031             Pixmap blank = XCreatePixmap( p_vout->p_sys->p_display,
1032                                DefaultRootWindow(p_vout->p_sys->p_display),
1033                                1, 1, 1 );
1034
1035             XParseColor( p_vout->p_sys->p_display,
1036                          XCreateColormap( p_vout->p_sys->p_display,
1037                                           DefaultRootWindow(
1038                                                   p_vout->p_sys->p_display ),
1039                                           DefaultVisual(
1040                                                   p_vout->p_sys->p_display,
1041                                                   p_vout->p_sys->i_screen ),
1042                                           AllocNone ),
1043                          "black", &color );
1044
1045             cursor = XCreatePixmapCursor( p_vout->p_sys->p_display,
1046                            blank, blank, &color, &color, 1, 1 );
1047
1048             b_cursor = 1;
1049         }
1050         XDefineCursor( p_vout->p_sys->p_display,
1051                        p_vout->p_sys->window, cursor );
1052     }
1053     else
1054     {
1055         p_vout->p_sys->b_mouse = 1;
1056
1057         XUndefineCursor( p_vout->p_sys->p_display, p_vout->p_sys->window );
1058     }
1059 }
1060