]> git.sesse.net Git - vlc/blob - plugins/x11/vout_x11.c
* Ported Glide and MGA plugins to the new module API. MGA never worked,
[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.15 2001/02/20 07:49:13 sam 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     /* Create XImages using XShm extension - on failure, fall back to regular
238      * way (and destroy the first image if it was created successfully) */
239     if( p_vout->p_sys->b_shm )
240     {
241         /* Create first image */
242         i_err = X11CreateShmImage( p_vout, &p_vout->p_sys->p_ximage[0],
243                                    &p_vout->p_sys->shm_info[0] );
244         if( !i_err )                         /* first image has been created */
245         {
246             /* Create second image */
247             if( X11CreateShmImage( p_vout, &p_vout->p_sys->p_ximage[1],
248                                    &p_vout->p_sys->shm_info[1] ) )
249             {                             /* error creating the second image */
250                 X11DestroyShmImage( p_vout, p_vout->p_sys->p_ximage[0],
251                                     &p_vout->p_sys->shm_info[0] );
252                 i_err = 1;
253             }
254         }
255         if( i_err )                                      /* an error occured */
256         {
257             intf_Msg("vout: XShm video extension unavailable" );
258             p_vout->p_sys->b_shm = 0;
259         }
260     }
261
262     /* Create XImages without XShm extension */
263     if( !p_vout->p_sys->b_shm )
264     {
265         if( X11CreateImage( p_vout, &p_vout->p_sys->p_ximage[0] ) )
266         {
267             intf_ErrMsg("error: can't create images");
268             p_vout->p_sys->p_ximage[0] = NULL;
269             p_vout->p_sys->p_ximage[1] = NULL;
270             return( 1 );
271         }
272         if( X11CreateImage( p_vout, &p_vout->p_sys->p_ximage[1] ) )
273         {
274             intf_ErrMsg("error: can't create images");
275             X11DestroyImage( p_vout->p_sys->p_ximage[0] );
276             p_vout->p_sys->p_ximage[0] = NULL;
277             p_vout->p_sys->p_ximage[1] = NULL;
278             return( 1 );
279         }
280     }
281
282     /* Set bytes per line and initialize buffers */
283     p_vout->i_bytes_per_line = p_vout->p_sys->p_ximage[0]->bytes_per_line;
284     vout_SetBuffers( p_vout, p_vout->p_sys->p_ximage[ 0 ]->data,
285                      p_vout->p_sys->p_ximage[ 1 ]->data );
286     return( 0 );
287 }
288
289 /*****************************************************************************
290  * vout_End: terminate X11 video thread output method
291  *****************************************************************************
292  * Destroy the X11 XImages created by vout_Init. It is called at the end of
293  * the thread, but also each time the window is resized.
294  *****************************************************************************/
295 static void vout_End( vout_thread_t *p_vout )
296 {
297     if( p_vout->p_sys->b_shm )                             /* Shm XImages... */
298     {
299         X11DestroyShmImage( p_vout, p_vout->p_sys->p_ximage[0],
300                             &p_vout->p_sys->shm_info[0] );
301         X11DestroyShmImage( p_vout, p_vout->p_sys->p_ximage[1],
302                             &p_vout->p_sys->shm_info[1] );
303     }
304     else                                          /* ...or regular XImages */
305     {
306         X11DestroyImage( p_vout->p_sys->p_ximage[0] );
307         X11DestroyImage( p_vout->p_sys->p_ximage[1] );
308     }
309 }
310
311 /*****************************************************************************
312  * vout_Destroy: destroy X11 video thread output method
313  *****************************************************************************
314  * Terminate an output method created by vout_CreateOutputMethod
315  *****************************************************************************/
316 static void vout_Destroy( vout_thread_t *p_vout )
317 {
318     /* Enable screen saver */
319     X11EnableScreenSaver( p_vout );
320
321     /* Destroy colormap */
322     if( p_vout->i_screen_depth == 8 )
323     {
324         XFreeColormap( p_vout->p_sys->p_display, p_vout->p_sys->colormap );
325     }
326
327     /* Destroy window */
328     XUnmapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
329     XFreeGC( p_vout->p_sys->p_display, p_vout->p_sys->gc );
330     XDestroyWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
331
332     XCloseDisplay( p_vout->p_sys->p_display );
333
334     /* Destroy structure */
335     free( p_vout->p_sys );
336 }
337
338 /*****************************************************************************
339  * vout_Manage: handle X11 events
340  *****************************************************************************
341  * This function should be called regularly by video output thread. It manages
342  * X11 events and allows window resizing. It returns a non null value on
343  * error.
344  *****************************************************************************/
345 static int vout_Manage( vout_thread_t *p_vout )
346 {
347     XEvent      xevent;                                         /* X11 event */
348     boolean_t   b_resized;                        /* window has been resized */
349     char        i_key;                                    /* ISO Latin-1 key */
350
351     /* Handle X11 events: ConfigureNotify events are parsed to know if the
352      * output window's size changed, MapNotify and UnmapNotify to know if the
353      * window is mapped (and if the display is useful), and ClientMessages
354      * to intercept window destruction requests */
355     b_resized = 0;
356     while( XCheckWindowEvent( p_vout->p_sys->p_display, p_vout->p_sys->window,
357                               StructureNotifyMask | KeyPressMask |
358                               ButtonPressMask | ButtonReleaseMask, &xevent )
359            == True )
360     {
361         /* ConfigureNotify event: prepare  */
362         if( (xevent.type == ConfigureNotify)
363             && ((xevent.xconfigure.width != p_vout->p_sys->i_width)
364                 || (xevent.xconfigure.height != p_vout->p_sys->i_height)) )
365         {
366             /* Update dimensions */
367             b_resized = 1;
368             p_vout->p_sys->i_width = xevent.xconfigure.width;
369             p_vout->p_sys->i_height = xevent.xconfigure.height;
370         }
371         /* MapNotify event: change window status and disable screen saver */
372         else if( xevent.type == MapNotify)
373         {
374             if( (p_vout != NULL) && !p_vout->b_active )
375             {
376                 X11DisableScreenSaver( p_vout );
377                 p_vout->b_active = 1;
378             }
379         }
380         /* UnmapNotify event: change window status and enable screen saver */
381         else if( xevent.type == UnmapNotify )
382         {
383             if( (p_vout != NULL) && p_vout->b_active )
384             {
385                 X11EnableScreenSaver( p_vout );
386                 p_vout->b_active = 0;
387             }
388         }
389         /* Keyboard event */
390         else if( xevent.type == KeyPress )
391         {
392             if( XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
393             {
394                 /* FIXME: handle stuff here */
395                 switch( i_key )
396                 {
397                 case 'q':
398                     /* FIXME: need locking ! */
399                     p_main->p_intf->b_die = 1;
400                     break;
401                 }
402             }
403         }
404         /* Mouse click */
405         else if( xevent.type == ButtonPress )
406         {
407             switch( ((XButtonEvent *)&xevent)->button )
408             {
409                 case Button1:
410                     /* in this part we will eventually manage
411                      * clicks for DVD navigation for instance */
412                     break;
413
414                 case Button2:
415                     X11TogglePointer( p_vout );
416                     break;
417             }
418         }
419         /* Mouse release */
420         else if( xevent.type == ButtonRelease )
421         {
422             switch( ((XButtonEvent *)&xevent)->button )
423             {
424                 case Button3:
425                     /* FIXME: need locking ! */
426                     p_main->p_intf->b_menu_change = 1;
427                     break;
428             }
429         }
430 #ifdef DEBUG
431         /* Other event */
432         else
433         {
434             intf_DbgMsg( "%p -> unhandled event type %d received",
435                          p_vout, xevent.type );
436         }
437 #endif
438     }
439
440     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
441      * are handled - according to the man pages, the format is always 32
442      * in this case */
443     while( XCheckTypedEvent( p_vout->p_sys->p_display,
444                              ClientMessage, &xevent ) )
445     {
446         if( (xevent.xclient.message_type == p_vout->p_sys->wm_protocols)
447             && (xevent.xclient.data.l[0] == p_vout->p_sys->wm_delete_window ) )
448         {
449             p_main->p_intf->b_die = 1;
450         }
451         else
452         {
453             intf_DbgMsg( "%p -> unhandled ClientMessage received", p_vout );
454         }
455     }
456
457     /*
458      * Handle vout window resizing
459      */
460     if( b_resized )
461     {
462         /* If interface window has been resized, change vout size */
463         intf_DbgMsg( "resizing output window" );
464         p_vout->i_width =  p_vout->p_sys->i_width;
465         p_vout->i_height = p_vout->p_sys->i_height;
466         p_vout->i_changes |= VOUT_SIZE_CHANGE;
467     }
468     else if( (p_vout->i_width  != p_vout->p_sys->i_width) ||
469              (p_vout->i_height != p_vout->p_sys->i_height) )
470     {
471         /* If video output size has changed, change interface window size */
472         intf_DbgMsg( "resizing output window" );
473         p_vout->p_sys->i_width =    p_vout->i_width;
474         p_vout->p_sys->i_height =   p_vout->i_height;
475         XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->window,
476                        p_vout->p_sys->i_width, p_vout->p_sys->i_height );
477     }
478     /*
479      * Color/Grayscale or gamma change: in 8bpp, just change the colormap
480      */
481     if( (p_vout->i_changes & VOUT_GRAYSCALE_CHANGE)
482         && (p_vout->i_screen_depth == 8) )
483     {
484         /* FIXME: clear flags ?? */
485     }
486
487     /*
488      * Size change
489      */
490     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
491     {
492         intf_DbgMsg("resizing window");
493         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
494
495         /* Resize window */
496         XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->window,
497                        p_vout->i_width, p_vout->i_height );
498
499         /* Destroy XImages to change their size */
500         vout_End( p_vout );
501
502         /* Recreate XImages. If SysInit failed, the thread can't go on. */
503         if( vout_Init( p_vout ) )
504         {
505             intf_ErrMsg("error: can't resize display");
506             return( 1 );
507        }
508
509         /* Tell the video output thread that it will need to rebuild YUV
510          * tables. This is needed since conversion buffer size may have
511          * changed */
512         p_vout->i_changes |= VOUT_YUV_CHANGE;
513         intf_Msg("vout: video display resized (%dx%d)", p_vout->i_width, p_vout->i_height);
514     }
515
516     return 0;
517 }
518
519 /*****************************************************************************
520  * vout_Display: displays previously rendered output
521  *****************************************************************************
522  * This function send the currently rendered image to X11 server, wait until
523  * it is displayed and switch the two rendering buffer, preparing next frame.
524  *****************************************************************************/
525 static void vout_Display( vout_thread_t *p_vout )
526 {
527     if( p_vout->p_sys->b_shm)                                /* XShm is used */
528     {
529         /* Display rendered image using shared memory extension */
530         XShmPutImage(p_vout->p_sys->p_display, p_vout->p_sys->window, p_vout->p_sys->gc,
531                      p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ],
532                      0, 0, 0, 0,
533                      p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->width,
534                      p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->height, True);
535
536         /* Send the order to the X server */
537         XSync(p_vout->p_sys->p_display, False);
538     }
539     else                                /* regular X11 capabilities are used */
540     {
541         XPutImage(p_vout->p_sys->p_display, p_vout->p_sys->window, p_vout->p_sys->gc,
542                   p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ],
543                   0, 0, 0, 0,
544                   p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->width,
545                   p_vout->p_sys->p_ximage[ p_vout->i_buffer_index ]->height);
546
547         /* Send the order to the X server */
548         XSync(p_vout->p_sys->p_display, False);
549     }
550 }
551
552 /*****************************************************************************
553  * vout_SetPalette: sets an 8 bpp palette
554  *****************************************************************************
555  * This function sets the palette given as an argument. It does not return
556  * anything, but could later send information on which colors it was unable
557  * to set.
558  *****************************************************************************/
559 static void vout_SetPalette( p_vout_thread_t p_vout,
560                              u16 *red, u16 *green, u16 *blue, u16 *transp )
561 {
562     int i, j;
563     XColor p_colors[255];
564
565     intf_DbgMsg( "Palette change called" );
566
567     /* allocate palette */
568     for( i = 0, j = 255; i < 255; i++, j-- )
569     {
570         /* kludge: colors are indexed reversely because color 255 seems
571          * to be reserved for black even if we try to set it to white */
572         p_colors[ i ].pixel = j;
573         p_colors[ i ].pad   = 0;
574         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
575         p_colors[ i ].red   = red[ j ];
576         p_colors[ i ].blue  = blue[ j ];
577         p_colors[ i ].green = green[ j ];
578     }
579
580     XStoreColors( p_vout->p_sys->p_display,
581                   p_vout->p_sys->colormap, p_colors, 256 );
582 }
583
584 /* following functions are local */
585
586 /*****************************************************************************
587  * X11CreateWindow: open and set-up X11 main window
588  *****************************************************************************/
589 static int X11CreateWindow( vout_thread_t *p_vout )
590 {
591     XSizeHints              xsize_hints;
592     XSetWindowAttributes    xwindow_attributes;
593     XGCValues               xgcvalues;
594     XEvent                  xevent;
595     boolean_t               b_expose;
596     boolean_t               b_configure_notify;
597     boolean_t               b_map_notify;
598
599     /* Set main window's size */
600     p_vout->p_sys->i_width =  main_GetIntVariable( VOUT_WIDTH_VAR,
601                                                    VOUT_WIDTH_DEFAULT );
602     p_vout->p_sys->i_height = main_GetIntVariable( VOUT_HEIGHT_VAR,
603                                                    VOUT_HEIGHT_DEFAULT );
604
605     /* Prepare window manager hints and properties */
606     xsize_hints.base_width          = p_vout->p_sys->i_width;
607     xsize_hints.base_height         = p_vout->p_sys->i_height;
608     xsize_hints.flags               = PSize;
609     p_vout->p_sys->wm_protocols     = XInternAtom( p_vout->p_sys->p_display,
610                                                    "WM_PROTOCOLS", True );
611     p_vout->p_sys->wm_delete_window = XInternAtom( p_vout->p_sys->p_display,
612                                                    "WM_DELETE_WINDOW", True );
613
614     /* Prepare window attributes */
615     xwindow_attributes.backing_store = Always;       /* save the hidden part */
616     xwindow_attributes.background_pixel = WhitePixel( p_vout->p_sys->p_display,
617                                                       p_vout->p_sys->i_screen );
618
619     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
620
621     /* Create the window and set hints - the window must receive ConfigureNotify
622      * events, and, until it is displayed, Expose and MapNotify events. */
623     p_vout->p_sys->window =
624             XCreateWindow( p_vout->p_sys->p_display,
625                            DefaultRootWindow( p_vout->p_sys->p_display ),
626                            0, 0,
627                            p_vout->p_sys->i_width, p_vout->p_sys->i_height, 1,
628                            0, InputOutput, 0,
629                            CWBackingStore | CWBackPixel | CWEventMask,
630                            &xwindow_attributes );
631
632     /* Set window manager hints and properties: size hints, command,
633      * window's name, and accepted protocols */
634     XSetWMNormalHints( p_vout->p_sys->p_display, p_vout->p_sys->window,
635                        &xsize_hints );
636     XSetCommand( p_vout->p_sys->p_display, p_vout->p_sys->window,
637                  p_main->ppsz_argv, p_main->i_argc );
638     XStoreName( p_vout->p_sys->p_display, p_vout->p_sys->window,
639                 VOUT_TITLE " (X11 output)" );
640
641     if( (p_vout->p_sys->wm_protocols == None)        /* use WM_DELETE_WINDOW */
642         || (p_vout->p_sys->wm_delete_window == None)
643         || !XSetWMProtocols( p_vout->p_sys->p_display, p_vout->p_sys->window,
644                              &p_vout->p_sys->wm_delete_window, 1 ) )
645     {
646         /* WM_DELETE_WINDOW is not supported by window manager */
647         intf_Msg( "intf error: missing or bad window manager" );
648     }
649
650     /* Creation of a graphic context that doesn't generate a GraphicsExpose
651      * event when using functions like XCopyArea */
652     xgcvalues.graphics_exposures = False;
653     p_vout->p_sys->gc = XCreateGC( p_vout->p_sys->p_display,
654                                    p_vout->p_sys->window,
655                                    GCGraphicsExposures, &xgcvalues);
656
657     /* Send orders to server, and wait until window is displayed - three
658      * events must be received: a MapNotify event, an Expose event allowing
659      * drawing in the window, and a ConfigureNotify to get the window
660      * dimensions. Once those events have been received, only ConfigureNotify
661      * events need to be received. */
662     b_expose = 0;
663     b_configure_notify = 0;
664     b_map_notify = 0;
665     XMapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window);
666     do
667     {
668         XNextEvent( p_vout->p_sys->p_display, &xevent);
669         if( (xevent.type == Expose)
670             && (xevent.xexpose.window == p_vout->p_sys->window) )
671         {
672             b_expose = 1;
673         }
674         else if( (xevent.type == MapNotify)
675                  && (xevent.xmap.window == p_vout->p_sys->window) )
676         {
677             b_map_notify = 1;
678         }
679         else if( (xevent.type == ConfigureNotify)
680                  && (xevent.xconfigure.window == p_vout->p_sys->window) )
681         {
682             b_configure_notify = 1;
683             p_vout->p_sys->i_width = xevent.xconfigure.width;
684             p_vout->p_sys->i_height = xevent.xconfigure.height;
685         }
686     } while( !( b_expose && b_configure_notify && b_map_notify ) );
687
688     XSelectInput( p_vout->p_sys->p_display, p_vout->p_sys->window,
689                   StructureNotifyMask | KeyPressMask |
690                   ButtonPressMask | ButtonReleaseMask );
691
692     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
693     {
694         /* Allocate a new palette */
695         p_vout->p_sys->colormap =
696             XCreateColormap( p_vout->p_sys->p_display,
697                              DefaultRootWindow( p_vout->p_sys->p_display ),
698                              DefaultVisual( p_vout->p_sys->p_display,
699                                             p_vout->p_sys->i_screen ),
700                              AllocAll );
701
702         xwindow_attributes.colormap = p_vout->p_sys->colormap;
703         XChangeWindowAttributes( p_vout->p_sys->p_display,
704                                  p_vout->p_sys->window,
705                                  CWColormap, &xwindow_attributes );
706     }
707
708     /* At this stage, the window is open, displayed, and ready to
709      * receive data */
710     return( 0 );
711 }
712
713 /*****************************************************************************
714  * X11InitDisplay: open and initialize X11 device
715  *****************************************************************************
716  * Create a window according to video output given size, and set other
717  * properties according to the display properties.
718  *****************************************************************************/
719 static int X11InitDisplay( vout_thread_t *p_vout, char *psz_display )
720 {
721     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
722     XVisualInfo *               p_xvisual;           /* visuals informations */
723     XVisualInfo                 xvisual_template;         /* visual template */
724     int                         i_count;                       /* array size */
725
726     /* Initialize structure */
727     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
728     p_vout->p_sys->b_shm    = ( XShmQueryExtension( p_vout->p_sys->p_display )
729                                  == True );
730     if( !p_vout->p_sys->b_shm )
731     {
732         intf_Msg("vout: XShm video extension is not available");
733     }
734
735     /* Get screen depth */
736     p_vout->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
737                                             p_vout->p_sys->i_screen );
738     switch( p_vout->i_screen_depth )
739     {
740     case 8:
741         /*
742          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
743          */
744         xvisual_template.screen =   p_vout->p_sys->i_screen;
745         xvisual_template.class =    DirectColor;
746         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
747                                     VisualScreenMask | VisualClassMask,
748                                     &xvisual_template, &i_count );
749         if( p_xvisual == NULL )
750         {
751             intf_ErrMsg("vout error: no PseudoColor visual available");
752             return( 1 );
753         }
754         p_vout->i_bytes_per_pixel = 1;
755         break;
756     case 15:
757     case 16:
758     case 24:
759     default:
760         /*
761          * Screen depth is higher than 8bpp. TrueColor visual is used.
762          */
763         xvisual_template.screen =   p_vout->p_sys->i_screen;
764         xvisual_template.class =    TrueColor;
765         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
766                                     VisualScreenMask | VisualClassMask,
767                                     &xvisual_template, &i_count );
768         if( p_xvisual == NULL )
769         {
770             intf_ErrMsg("vout error: no TrueColor visual available");
771             return( 1 );
772         }
773         p_vout->i_red_mask =        p_xvisual->red_mask;
774         p_vout->i_green_mask =      p_xvisual->green_mask;
775         p_vout->i_blue_mask =       p_xvisual->blue_mask;
776
777         /* There is no difference yet between 3 and 4 Bpp. The only way
778          * to find the actual number of bytes per pixel is to list supported
779          * pixmap formats. */
780         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
781         p_vout->i_bytes_per_pixel = 0;
782
783         for( ; i_count-- ; p_formats++ )
784         {
785             /* Under XFree4.0, the list contains pixmap formats available
786              * through all video depths ; so we have to check against current
787              * depth. */
788             if( p_formats->depth == p_vout->i_screen_depth )
789             {
790                 if( p_formats->bits_per_pixel / 8
791                         > p_vout->i_bytes_per_pixel )
792                 {
793                     p_vout->i_bytes_per_pixel = p_formats->bits_per_pixel / 8;
794                 }
795             }
796         }
797         break;
798     }
799     p_vout->p_sys->p_visual = p_xvisual->visual;
800     XFree( p_xvisual );
801
802     return( 0 );
803 }
804
805 /*****************************************************************************
806  * X11CreateImage: create an XImage
807  *****************************************************************************
808  * Create a simple XImage used as a buffer.
809  *****************************************************************************/
810 static int X11CreateImage( vout_thread_t *p_vout, XImage **pp_ximage )
811 {
812     byte_t *    pb_data;                          /* image data storage zone */
813     int         i_quantum;                     /* XImage quantum (see below) */
814
815     /* Allocate memory for image */
816     p_vout->i_bytes_per_line = p_vout->i_width * p_vout->i_bytes_per_pixel;
817     pb_data = (byte_t *) malloc( p_vout->i_bytes_per_line * p_vout->i_height );
818     if( !pb_data )                                                  /* error */
819     {
820         intf_ErrMsg("error: %s", strerror(ENOMEM));
821         return( 1 );
822     }
823
824     /* Optimize the quantum of a scanline regarding its size - the quantum is
825        a diviser of the number of bits between the start of two scanlines. */
826     if( !(( p_vout->i_bytes_per_line ) % 32) )
827     {
828         i_quantum = 32;
829     }
830     else
831     {
832         if( !(( p_vout->i_bytes_per_line ) % 16) )
833         {
834             i_quantum = 16;
835         }
836         else
837         {
838             i_quantum = 8;
839         }
840     }
841
842     /* Create XImage */
843     *pp_ximage = XCreateImage( p_vout->p_sys->p_display,
844                                p_vout->p_sys->p_visual, p_vout->i_screen_depth,
845                                ZPixmap, 0, pb_data,
846                                p_vout->i_width, p_vout->i_height, i_quantum, 0);
847     if(! *pp_ximage )                                               /* error */
848     {
849         intf_ErrMsg( "error: XCreateImage() failed" );
850         free( pb_data );
851         return( 1 );
852     }
853
854     return 0;
855 }
856
857 /*****************************************************************************
858  * X11CreateShmImage: create an XImage using shared memory extension
859  *****************************************************************************
860  * Prepare an XImage for DisplayX11ShmImage function.
861  * The order of the operations respects the recommandations of the mit-shm
862  * document by J.Corbet and K.Packard. Most of the parameters were copied from
863  * there.
864  *****************************************************************************/
865 static int X11CreateShmImage( vout_thread_t *p_vout, XImage **pp_ximage,
866                               XShmSegmentInfo *p_shm_info)
867 {
868     /* Create XImage */
869     *pp_ximage =
870         XShmCreateImage( p_vout->p_sys->p_display, p_vout->p_sys->p_visual,
871                          p_vout->i_screen_depth, ZPixmap, 0,
872                          p_shm_info, p_vout->i_width, p_vout->i_height );
873     if(! *pp_ximage )                                               /* error */
874     {
875         intf_ErrMsg("error: XShmCreateImage() failed");
876         return( 1 );
877     }
878
879     /* Allocate shared memory segment - 0777 set the access permission
880      * rights (like umask), they are not yet supported by X servers */
881     p_shm_info->shmid =
882         shmget( IPC_PRIVATE, (*pp_ximage)->bytes_per_line
883                                  * (*pp_ximage)->height, IPC_CREAT | 0777);
884     if( p_shm_info->shmid < 0)                                      /* error */
885     {
886         intf_ErrMsg("error: can't allocate shared image data (%s)",
887                     strerror(errno));
888         XDestroyImage( *pp_ximage );
889         return( 1 );
890     }
891
892     /* Attach shared memory segment to process (read/write) */
893     p_shm_info->shmaddr = (*pp_ximage)->data = shmat(p_shm_info->shmid, 0, 0);
894     if(! p_shm_info->shmaddr )
895     {                                                               /* error */
896         intf_ErrMsg("error: can't attach shared memory (%s)",
897                     strerror(errno));
898         shmctl( p_shm_info->shmid, IPC_RMID, 0 );      /* free shared memory */
899         XDestroyImage( *pp_ximage );
900         return( 1 );
901     }
902
903     /* Mark the shm segment to be removed when there will be no more
904      * attachements, so it is automatic on process exit or after shmdt */
905     shmctl( p_shm_info->shmid, IPC_RMID, 0 );
906
907     /* Attach shared memory segment to X server (read only) */
908     p_shm_info->readOnly = True;
909     if( XShmAttach( p_vout->p_sys->p_display, p_shm_info )
910          == False )                                                 /* error */
911     {
912         intf_ErrMsg("error: can't attach shared memory to X11 server");
913         shmdt( p_shm_info->shmaddr );   /* detach shared memory from process
914                                          * and automatic free */
915         XDestroyImage( *pp_ximage );
916         return( 1 );
917     }
918
919     /* Send image to X server. This instruction is required, since having
920      * built a Shm XImage and not using it causes an error on XCloseDisplay */
921     XFlush( p_vout->p_sys->p_display );
922     return( 0 );
923 }
924
925 /*****************************************************************************
926  * X11DestroyImage: destroy an XImage
927  *****************************************************************************
928  * Destroy XImage AND associated data. If pointer is NULL, the image won't be
929  * destroyed (see vout_ManageOutputMethod())
930  *****************************************************************************/
931 static void X11DestroyImage( XImage *p_ximage )
932 {
933     if( p_ximage != NULL )
934     {
935         XDestroyImage( p_ximage );                     /* no free() required */
936     }
937 }
938
939 /*****************************************************************************
940  * X11DestroyShmImage
941  *****************************************************************************
942  * Destroy XImage AND associated data. Detach shared memory segment from
943  * server and process, then free it. If pointer is NULL, the image won't be
944  * destroyed (see vout_ManageOutputMethod())
945  *****************************************************************************/
946 static void X11DestroyShmImage( vout_thread_t *p_vout, XImage *p_ximage,
947                                 XShmSegmentInfo *p_shm_info )
948 {
949     /* If pointer is NULL, do nothing */
950     if( p_ximage == NULL )
951     {
952         return;
953     }
954
955     XShmDetach( p_vout->p_sys->p_display, p_shm_info );/* detach from server */
956     XDestroyImage( p_ximage );
957
958     if( shmdt( p_shm_info->shmaddr ) )  /* detach shared memory from process */
959     {                                   /* also automatic freeing...         */
960         intf_ErrMsg( "error: can't detach shared memory (%s)",
961                      strerror(errno) );
962     }
963 }
964
965
966 /* WAZAAAAAAAAAAA */
967
968 /*****************************************************************************
969  * X11EnableScreenSaver: enable screen saver
970  *****************************************************************************
971  * This function enable the screen saver on a display after it had been
972  * disabled by XDisableScreenSaver. Both functions use a counter mechanism to
973  * know wether the screen saver can be activated or not: if n successive calls
974  * are made to XDisableScreenSaver, n successive calls to XEnableScreenSaver
975  * will be required before the screen saver could effectively be activated.
976  *****************************************************************************/
977 void X11EnableScreenSaver( vout_thread_t *p_vout )
978 {
979     intf_DbgMsg( "intf: enabling screen saver" );
980     XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
981                      p_vout->p_sys->i_ss_interval,
982                      p_vout->p_sys->i_ss_blanking,
983                      p_vout->p_sys->i_ss_exposure );
984 }
985
986 /*****************************************************************************
987  * X11DisableScreenSaver: disable screen saver
988  *****************************************************************************
989  * See XEnableScreenSaver
990  *****************************************************************************/
991 void X11DisableScreenSaver( vout_thread_t *p_vout )
992 {
993     /* Save screen saver informations */
994     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
995                      &p_vout->p_sys->i_ss_interval,
996                      &p_vout->p_sys->i_ss_blanking,
997                      &p_vout->p_sys->i_ss_exposure );
998
999     /* Disable screen saver */
1000     intf_DbgMsg("intf: disabling screen saver");
1001     XSetScreenSaver( p_vout->p_sys->p_display, 0,
1002                      p_vout->p_sys->i_ss_interval,
1003                      p_vout->p_sys->i_ss_blanking,
1004                      p_vout->p_sys->i_ss_exposure );
1005 }
1006
1007 /*****************************************************************************
1008  * X11TogglePointer: hide or show the mouse pointer
1009  *****************************************************************************
1010  * This function hides the X pointer if it is visible by putting it at
1011  * coordinates (32,32) and setting the pointer sprite to a blank one. To
1012  * show it again, we disable the sprite and restore the original coordinates.
1013  *****************************************************************************/
1014 void X11TogglePointer( vout_thread_t *p_vout )
1015 {
1016     static Cursor cursor;
1017     static boolean_t b_cursor = 0;
1018
1019     if( p_vout->p_sys->b_mouse )
1020     {
1021         p_vout->p_sys->b_mouse = 0;
1022
1023         if( !b_cursor )
1024         {
1025             XColor color;
1026             Pixmap blank = XCreatePixmap( p_vout->p_sys->p_display,
1027                                DefaultRootWindow(p_vout->p_sys->p_display),
1028                                1, 1, 1 );
1029
1030             XParseColor( p_vout->p_sys->p_display,
1031                          XCreateColormap( p_vout->p_sys->p_display,
1032                                           DefaultRootWindow(
1033                                                   p_vout->p_sys->p_display ),
1034                                           DefaultVisual(
1035                                                   p_vout->p_sys->p_display,
1036                                                   p_vout->p_sys->i_screen ),
1037                                           AllocNone ),
1038                          "black", &color );
1039
1040             cursor = XCreatePixmapCursor( p_vout->p_sys->p_display,
1041                            blank, blank, &color, &color, 1, 1 );
1042
1043             b_cursor = 1;
1044         }
1045         XDefineCursor( p_vout->p_sys->p_display,
1046                        p_vout->p_sys->window, cursor );
1047     }
1048     else
1049     {
1050         p_vout->p_sys->b_mouse = 1;
1051
1052         XUndefineCursor( p_vout->p_sys->p_display, p_vout->p_sys->window );
1053     }
1054 }
1055