]> git.sesse.net Git - vlc/blob - plugins/x11/xcommon.c
Some heavy changes today:
[vlc] / plugins / x11 / xcommon.c
1 /*****************************************************************************
2  * xcommon.c: Functions common to the X11 and XVideo plugins
3  *****************************************************************************
4  * Copyright (C) 1998-2001 VideoLAN
5  * $Id: xcommon.c,v 1.1 2001/12/30 07:09:56 sam Exp $
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          David Kennedy <dkennedy@tinytoad.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <errno.h>                                                 /* ENOMEM */
30 #include <stdlib.h>                                                /* free() */
31 #include <string.h>                                            /* strerror() */
32
33 #include <videolan/vlc.h>
34
35 #ifdef HAVE_MACHINE_PARAM_H
36 /* BSD */
37 #include <machine/param.h>
38 #include <sys/types.h>                                     /* typedef ushort */
39 #include <sys/ipc.h>
40 #endif
41
42 #ifndef WIN32
43 #include <netinet/in.h>                               /* BSD: struct in_addr */
44 #endif
45
46 #include <sys/shm.h>                                   /* shmget(), shmctl() */
47 #include <X11/Xlib.h>
48 #include <X11/Xutil.h>
49 #include <X11/keysym.h>
50 #include <X11/extensions/XShm.h>
51
52 #ifdef MODULE_NAME_IS_xvideo
53 #   include <X11/extensions/Xv.h>
54 #   include <X11/extensions/Xvlib.h>
55 #   include <X11/extensions/dpms.h>
56 #endif
57
58 #include "video.h"
59 #include "video_output.h"
60 #include "xcommon.h"
61
62 #include "interface.h"
63 #include "netutils.h"                                 /* network_ChannelJoin */
64
65 #include "stream_control.h"                 /* needed by input_ext-intf.h... */
66 #include "input_ext-intf.h"
67
68 #ifdef MODULE_NAME_IS_xvideo
69 #   define IMAGE_TYPE     XvImage
70 #   define EXTRA_ARGS     int i_xvport, int i_format
71 #   define EXTRA_ARGS_SHM int i_xvport, int i_format, XShmSegmentInfo *p_shm
72 #   define DATA_SIZE      p_image->data_size
73     /* There is nothing like XvDestroyImage */
74 #   define IMAGE_FREE     XFree
75 #else
76 #   define IMAGE_TYPE     XImage
77 #   define EXTRA_ARGS     Visual *p_visual, int i_depth, int i_bytes_per_pixel
78 #   define EXTRA_ARGS_SHM Visual *p_visual, int i_depth, XShmSegmentInfo *p_shm
79 #   define DATA_SIZE      (p_image->bytes_per_line * p_image->height)
80 #   define IMAGE_FREE     XDestroyImage
81 #endif
82
83 /*****************************************************************************
84  * Local prototypes
85  *****************************************************************************/
86 static int  vout_Probe     ( probedata_t * );
87 static int  vout_Create    ( vout_thread_t * );
88 static void vout_Destroy   ( vout_thread_t * );
89 static void vout_Display   ( vout_thread_t *, picture_t * );
90 static int  vout_Manage    ( vout_thread_t * );
91 static int  vout_Init      ( vout_thread_t * );
92 static void vout_End       ( vout_thread_t * );
93
94 static int  InitDisplay    ( vout_thread_t * );
95
96 static int  CreateWindow   ( vout_thread_t * );
97 static void DestroyWindow  ( vout_thread_t * );
98
99 static int  NewPicture     ( vout_thread_t *, picture_t * );
100 static void FreePicture    ( vout_thread_t *, picture_t * );
101
102 static IMAGE_TYPE *CreateImage    ( Display *, EXTRA_ARGS, int, int );
103 static IMAGE_TYPE *CreateShmImage ( Display *, EXTRA_ARGS_SHM, int, int );
104
105 static void EnableXScreenSaver    ( vout_thread_t * );
106 static void DisableXScreenSaver   ( vout_thread_t * );
107
108 static void CreateCursor   ( vout_thread_t * );
109 static void DestroyCursor  ( vout_thread_t * );
110 static void ToggleCursor   ( vout_thread_t * );
111
112 #ifdef MODULE_NAME_IS_xvideo
113 static int  XVideoGetPort         ( Display *, int );
114 static void XVideoReleasePort     ( Display *, int );
115 #endif
116
117 /*****************************************************************************
118  * vout_sys_t: video output method descriptor
119  *****************************************************************************
120  * This structure is part of the video output thread descriptor.
121  * It describes the X11 and XVideo specific properties of an output thread.
122  *****************************************************************************/
123 typedef struct vout_sys_s
124 {
125     /* Internal settings and properties */
126     Display *           p_display;                        /* display pointer */
127
128     Visual *            p_visual;                          /* visual pointer */
129     int                 i_screen;                           /* screen number */
130     Window              window;                               /* root window */
131     GC                  gc;              /* graphic context instance handler */
132
133     boolean_t           b_shm;               /* shared memory extension flag */
134
135 #ifdef MODULE_NAME_IS_xvideo
136     Window              yuv_window;   /* sub-window for displaying yuv video
137                                                                         data */
138     GC                  yuv_gc;
139     int                 i_xvport;
140 #else
141     Colormap            colormap;               /* colormap used (8bpp only) */
142
143     int                 i_screen_depth;
144     int                 i_bytes_per_pixel;
145     int                 i_bytes_per_line;
146     int                 i_red_mask;
147     int                 i_green_mask;
148     int                 i_blue_mask;
149 #endif
150
151     /* X11 generic properties */
152     Atom                wm_protocols;
153     Atom                wm_delete_window;
154
155     int                 i_width;                     /* width of main window */
156     int                 i_height;                   /* height of main window */
157
158     /* Screen saver properties */
159     int                 i_ss_timeout;                             /* timeout */
160     int                 i_ss_interval;           /* interval between changes */
161     int                 i_ss_blanking;                      /* blanking mode */
162     int                 i_ss_exposure;                      /* exposure mode */
163
164     /* Mouse pointer properties */
165     boolean_t           b_mouse_pointer_visible;
166     mtime_t             i_time_mouse_last_moved; /* used to auto-hide pointer*/
167     Cursor              blank_cursor;                   /* the hidden cursor */
168     Pixmap              cursor_pixmap;
169
170 } vout_sys_t;
171
172 /*****************************************************************************
173  * picture_sys_t: direct buffer method descriptor
174  *****************************************************************************
175  * This structure is part of the picture descriptor, it describes the
176  * XVideo specific properties of a direct buffer.
177  *****************************************************************************/
178 typedef struct picture_sys_s
179 {
180     IMAGE_TYPE *        p_image;
181
182     XShmSegmentInfo     shminfo;       /* shared memory zone information */
183
184 } picture_sys_t;
185
186 /*****************************************************************************
187  * mwmhints_t: window manager hints
188  *****************************************************************************
189  * Fullscreen needs to be able to hide the wm decorations so we provide
190  * this structure to make it easier.
191  *****************************************************************************/
192 #define MWM_HINTS_DECORATIONS   (1L << 1)
193 #define PROP_MWM_HINTS_ELEMENTS 5
194 typedef struct mwmhints_s
195 {
196     u32 flags;
197     u32 functions;
198     u32 decorations;
199     s32 input_mode;
200     u32 status;
201 } mwmhints_t;
202
203 /*****************************************************************************
204  * Chroma defines
205  *****************************************************************************/
206 #ifdef MODULE_NAME_IS_xvideo
207 #   define GUID_YUV12_PLANAR 0x32315659
208 #   define MAX_DIRECTBUFFERS 5
209 #else
210 #   define MAX_DIRECTBUFFERS 2
211 #endif
212
213 /*****************************************************************************
214  * Seeking function TODO: put this in a generic location !
215  *****************************************************************************/
216 static __inline__ void vout_Seek( off_t i_seek )
217 {
218 #define area p_main->p_intf->p_input->stream.p_selected_area
219     off_t i_tell = area->i_tell;
220
221     i_tell += i_seek * (off_t)50 * p_main->p_intf->p_input->stream.i_mux_rate;
222
223     i_tell = ( i_tell <= 0/*area->i_start*/ ) ? 0/*area->i_start*/
224            : ( i_tell >= area->i_size ) ? area->i_size
225            : i_tell;
226
227     input_Seek( p_main->p_intf->p_input, i_tell );
228 #undef area
229 }
230
231 /*****************************************************************************
232  * Functions exported as capabilities. They are declared as static so that
233  * we don't pollute the namespace too much.
234  *****************************************************************************/
235 void _M( vout_getfunctions )( function_list_t * p_function_list )
236 {
237     p_function_list->pf_probe = vout_Probe;
238     p_function_list->functions.vout.pf_create     = vout_Create;
239     p_function_list->functions.vout.pf_init       = vout_Init;
240     p_function_list->functions.vout.pf_end        = vout_End;
241     p_function_list->functions.vout.pf_destroy    = vout_Destroy;
242     p_function_list->functions.vout.pf_manage     = vout_Manage;
243     p_function_list->functions.vout.pf_display    = vout_Display;
244     p_function_list->functions.vout.pf_setpalette = NULL;
245 }
246
247 /*****************************************************************************
248  * vout_Probe: probe the video driver and return a score
249  *****************************************************************************
250  * This function tries to initialize SDL and returns a score to the
251  * plugin manager so that it can select the best plugin.
252  *****************************************************************************/
253 static int vout_Probe( probedata_t *p_data )
254 {
255     Display *p_display;                                   /* display pointer */
256     char    *psz_display;
257 #ifdef MODULE_NAME_IS_xvideo
258     int      i_xvport;
259 #endif
260
261     /* Open display, unsing 'vlc_display' or DISPLAY environment variable */
262     psz_display = XDisplayName( main_GetPszVariable(VOUT_DISPLAY_VAR, NULL) );
263     p_display = XOpenDisplay( psz_display );
264     if( p_display == NULL )                                         /* error */
265     {
266         intf_WarnMsg( 3, "vout: cannot open display %s", psz_display );
267         return( 0 );
268     }
269
270 #ifdef MODULE_NAME_IS_xvideo 
271     /* Check that there is an available XVideo port */
272     i_xvport = XVideoGetPort( p_display, GUID_YUV12_PLANAR );
273     if( i_xvport < 0 )
274     {
275         intf_WarnMsg( 3, "vout: no XVideo port available" );
276         XCloseDisplay( p_display );
277         return( 0 );
278     }
279     XVideoReleasePort( p_display, i_xvport );
280 #endif
281
282     /* Clean-up everyting */
283     XCloseDisplay( p_display );
284
285 #ifdef MODULE_NAME_IS_xvideo 
286     return( 150 );
287 #else
288     return( 50 );
289 #endif
290 }
291
292 /*****************************************************************************
293  * vout_Create: allocate X11 video thread output method
294  *****************************************************************************
295  * This function allocate and initialize a X11 vout method. It uses some of the
296  * vout properties to choose the window size, and change them according to the
297  * actual properties of the display.
298  *****************************************************************************/
299 static int vout_Create( vout_thread_t *p_vout )
300 {
301     char *psz_display;
302
303     /* Allocate structure */
304     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
305     if( p_vout->p_sys == NULL )
306     {
307         intf_ErrMsg( "vout error: %s", strerror(ENOMEM) );
308         return( 1 );
309     }
310
311     /* Open display, unsing 'vlc_display' or DISPLAY environment variable */
312     psz_display = XDisplayName( main_GetPszVariable( VOUT_DISPLAY_VAR, NULL ) );
313     p_vout->p_sys->p_display = XOpenDisplay( psz_display );
314
315     if( p_vout->p_sys->p_display == NULL )                          /* error */
316     {
317         intf_ErrMsg( "vout error: cannot open display %s", psz_display );
318         free( p_vout->p_sys );
319         return( 1 );
320     }
321     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
322
323 #ifdef MODULE_NAME_IS_xvideo
324     /* Check that we have access to an XVideo port */
325     p_vout->p_sys->i_xvport = XVideoGetPort( p_vout->p_sys->p_display,
326                                              GUID_YUV12_PLANAR );
327     if( p_vout->p_sys->i_xvport < 0 )
328     {
329         intf_ErrMsg( "vout error: cannot get XVideo port" );
330         XCloseDisplay( p_vout->p_sys->p_display );
331         free( p_vout->p_sys );
332         return 1;
333     }
334 #endif
335
336     /* Spawn base window - this window will include the video output window,
337      * but also command buttons, subtitles and other indicators */
338     if( CreateWindow( p_vout ) )
339     {
340         intf_ErrMsg( "vout error: cannot create X11 window" );
341         XCloseDisplay( p_vout->p_sys->p_display );
342         free( p_vout->p_sys );
343         return( 1 );
344     }
345
346     /* Open and initialize device. */
347     if( InitDisplay( p_vout ) )
348     {
349         intf_ErrMsg( "vout error: cannot initialize X11 display" );
350         XCloseDisplay( p_vout->p_sys->p_display );
351         free( p_vout->p_sys );
352         return( 1 );
353     }
354
355     /* Create blank cursor (for mouse cursor autohiding) */
356     CreateCursor( p_vout );
357
358     p_vout->p_sys->b_mouse_pointer_visible = 1;
359
360     /* Disable screen saver and return */
361     DisableXScreenSaver( p_vout );
362
363     return( 0 );
364 }
365
366 /*****************************************************************************
367  * vout_Destroy: destroy X11 video thread output method
368  *****************************************************************************
369  * Terminate an output method created by vout_CreateOutputMethod
370  *****************************************************************************/
371 static void vout_Destroy( vout_thread_t *p_vout )
372 {
373     /* Restore cursor if it was blanked */
374     if( !p_vout->p_sys->b_mouse_pointer_visible )
375     {
376         ToggleCursor( p_vout );
377     }
378
379 #ifdef MODULE_NAME_IS_xvideo   
380     XVideoReleasePort( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport );
381 #else
382 #if 0
383     /* Destroy colormap */
384     if( p_vout->p_sys->i_screen_depth == 8 )
385     {
386         XFreeColormap( p_vout->p_sys->p_display, p_vout->p_sys->colormap );
387     }
388 #endif
389 #endif
390
391     DestroyCursor( p_vout );
392     EnableXScreenSaver( p_vout );
393     DestroyWindow( p_vout );
394
395     XCloseDisplay( p_vout->p_sys->p_display );
396
397     /* Destroy structure */
398     free( p_vout->p_sys );
399 }
400
401 /*****************************************************************************
402  * vout_Init: initialize X11 video thread output method
403  *****************************************************************************
404  * This function create the XImages needed by the output thread. It is called
405  * at the beginning of the thread, but also each time the window is resized.
406  *****************************************************************************/
407 static int vout_Init( vout_thread_t *p_vout )
408 {
409     int i_index;
410     picture_t *p_pic;
411
412     I_OUTPUTPICTURES = 0;
413
414 #ifdef MODULE_NAME_IS_xvideo
415     /* Initialize the output structure */
416     switch( p_vout->render.i_chroma )
417     {
418         case YUV_420_PICTURE:
419             p_vout->output.i_chroma = p_vout->render.i_chroma;
420             p_vout->output.i_width  = p_vout->render.i_width;
421             p_vout->output.i_height = p_vout->render.i_height;
422             p_vout->output.i_aspect = p_vout->render.i_aspect;
423             break;
424
425         default:
426             return( 0 );
427     }
428 #else
429     /* Initialize the output structure: RGB with square pixels, whatever
430      * the input format is, since it's the only format we know */
431     p_vout->output.i_chroma = RGB_16BPP_PICTURE;
432     p_vout->output.i_width = p_vout->p_sys->i_width;
433     p_vout->output.i_height = p_vout->p_sys->i_height;
434     p_vout->output.i_aspect = p_vout->p_sys->i_width
435                                * VOUT_ASPECT_FACTOR / p_vout->p_sys->i_height;
436 #endif
437
438     /* Try to initialize up to MAX_DIRECTBUFFERS direct buffers */
439     while( I_OUTPUTPICTURES < MAX_DIRECTBUFFERS )
440     {
441         p_pic = NULL;
442
443         /* Find an empty picture slot */
444         for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
445         {
446             if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
447             {
448                 p_pic = p_vout->p_picture + i_index;
449                 break;
450             }
451         }
452
453         /* Allocate the picture */
454         if( p_pic == NULL || NewPicture( p_vout, p_pic ) )
455         {
456             break;
457         }
458
459         p_pic->i_status        = DESTROYED_PICTURE;
460         p_pic->i_type          = DIRECT_PICTURE;
461
462         p_pic->i_left_margin   =
463         p_pic->i_right_margin  =
464         p_pic->i_top_margin    = 
465         p_pic->i_bottom_margin = 0;
466
467         PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
468
469         I_OUTPUTPICTURES++;
470     }
471
472     return( 0 );
473 }
474
475 /*****************************************************************************
476  * vout_Display: displays previously rendered output
477  *****************************************************************************
478  * This function sends the currently rendered image to X11 server.
479  * (The Xv extension takes care of "double-buffering".)
480  *****************************************************************************/
481 static void vout_Display( vout_thread_t *p_vout, picture_t *p_pic )
482 {
483     int i_width, i_height, i_x, i_y;
484
485     vout_PlacePicture( p_vout, p_vout->p_sys->i_width, p_vout->p_sys->i_height,
486                        &i_x, &i_y, &i_width, &i_height );
487
488     if( p_vout->p_sys->b_shm )
489     {
490         /* Display rendered image using shared memory extension */
491 #ifdef MODULE_NAME_IS_xvideo
492         XvShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
493                        p_vout->p_sys->yuv_window, p_vout->p_sys->gc,
494                        p_pic->p_sys->p_image, 0 /*src_x*/, 0 /*src_y*/,
495                        p_vout->output.i_width, p_vout->output.i_height,
496                        0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height,
497                        False /* Don't put True here or you'll waste your CPU */ );
498 #else
499         XShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->window,
500                       p_vout->p_sys->gc, p_pic->p_sys->p_image,
501                       0 /*src_x*/, 0 /*src_y*/, 0 /*dest_x*/, 0 /*dest_y*/,
502                       p_vout->output.i_width, p_vout->output.i_height,
503                       False /* Don't put True here ! */ );
504 #endif
505     }
506     else
507     {
508         /* Use standard XPutImage -- this is gonna be slow ! */
509 #ifdef MODULE_NAME_IS_xvideo
510         XvPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
511                     p_vout->p_sys->yuv_window, p_vout->p_sys->gc,
512                     p_pic->p_sys->p_image, 0 /*src_x*/, 0 /*src_y*/,
513                     p_vout->output.i_width, p_vout->output.i_height,
514                     0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height );
515 #else
516         XPutImage( p_vout->p_sys->p_display, p_vout->p_sys->window,
517                    p_vout->p_sys->gc, p_pic->p_sys->p_image,
518                    0 /*src_x*/, 0 /*src_y*/, 0 /*dest_x*/, 0 /*dest_y*/,
519                    p_vout->output.i_width, p_vout->output.i_height );
520 #endif
521     }
522
523 #ifdef MODULE_NAME_IS_xvideo
524     XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
525                    i_width, i_height );
526     XMoveWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
527                  i_x, i_y );
528 #endif
529
530     /* Force synchronization */
531     XSync( p_vout->p_sys->p_display, False );
532 }
533
534 /*****************************************************************************
535  * vout_Manage: handle X11 events
536  *****************************************************************************
537  * This function should be called regularly by video output thread. It manages
538  * X11 events and allows window resizing. It returns a non null value on
539  * error.
540  *****************************************************************************/
541 static int vout_Manage( vout_thread_t *p_vout )
542 {
543     XEvent      xevent;                                         /* X11 event */
544     boolean_t   b_resized;                        /* window has been resized */
545     char        i_key;                                    /* ISO Latin-1 key */
546     KeySym      x_key_symbol;
547
548     /* Handle X11 events: ConfigureNotify events are parsed to know if the
549      * output window's size changed, MapNotify and UnmapNotify to know if the
550      * window is mapped (and if the display is useful), and ClientMessages
551      * to intercept window destruction requests */
552
553     b_resized = 0;
554     while( XCheckWindowEvent( p_vout->p_sys->p_display, p_vout->p_sys->window,
555                               StructureNotifyMask | KeyPressMask |
556                               ButtonPressMask | ButtonReleaseMask | 
557                               PointerMotionMask | Button1MotionMask , &xevent )
558            == True )
559     {
560         /* ConfigureNotify event: prepare  */
561         if( (xevent.type == ConfigureNotify)
562           && ((xevent.xconfigure.width != p_vout->p_sys->i_width)
563              || (xevent.xconfigure.height != p_vout->p_sys->i_height)) )
564         {
565             /* Update dimensions */
566             b_resized = 1;
567             p_vout->p_sys->i_width = xevent.xconfigure.width;
568             p_vout->p_sys->i_height = xevent.xconfigure.height;
569         }
570         /* MapNotify event: change window status and disable screen saver */
571         else if( xevent.type == MapNotify)
572         {
573             if( (p_vout != NULL) && !p_vout->b_active )
574             {
575                 DisableXScreenSaver( p_vout );
576                 p_vout->b_active = 1;
577             }
578         }
579         /* UnmapNotify event: change window status and enable screen saver */
580         else if( xevent.type == UnmapNotify )
581         {
582             if( (p_vout != NULL) && p_vout->b_active )
583             {
584                 EnableXScreenSaver( p_vout );
585                 p_vout->b_active = 0;
586             }
587         }
588         /* Keyboard event */
589         else if( xevent.type == KeyPress )
590         {
591             /* We may have keys like F1 trough F12, ESC ... */
592             x_key_symbol = XKeycodeToKeysym( p_vout->p_sys->p_display,
593                                              xevent.xkey.keycode, 0 );
594             switch( x_key_symbol )
595             {
596                  case XK_Escape:
597                      p_main->p_intf->b_die = 1;
598                      break;
599                  case XK_Menu:
600                      p_main->p_intf->b_menu_change = 1;
601                      break;
602                  case XK_Left:
603                      vout_Seek( -5 );
604                      break;
605                  case XK_Right:
606                      vout_Seek( 5 );
607                      break;
608                  case XK_Up:
609                      vout_Seek( 60 );
610                      break;
611                  case XK_Down:
612                      vout_Seek( -60 );
613                      break;
614                  case XK_Home:
615                      input_Seek( p_main->p_intf->p_input,
616                      p_main->p_intf->p_input->stream.p_selected_area->i_start );
617                      break;
618                  case XK_End:
619                      input_Seek( p_main->p_intf->p_input,
620                      p_main->p_intf->p_input->stream.p_selected_area->i_size );
621                      break;
622                  case XK_Page_Up:
623                      vout_Seek( 900 );
624                      break;
625                  case XK_Page_Down:
626                      vout_Seek( -900 );
627                      break;
628                  case XK_space:
629                      input_SetStatus( p_main->p_intf->p_input,
630                                       INPUT_STATUS_PAUSE );
631                      break;
632
633                  default:
634                      /* "Normal Keys"
635                       * The reason why I use this instead of XK_0 is that 
636                       * with XLookupString, we don't have to care about
637                       * keymaps. */
638
639                     if( XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
640                     {
641                         /* FIXME: handle stuff here */
642                         switch( i_key )
643                         {
644                         case 'q':
645                         case 'Q':
646                             p_main->p_intf->b_die = 1;
647                             break;
648                         case 'f':
649                         case 'F':
650                             p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
651                             break;
652
653                         case '0': network_ChannelJoin( 0 ); break;
654                         case '1': network_ChannelJoin( 1 ); break;
655                         case '2': network_ChannelJoin( 2 ); break;
656                         case '3': network_ChannelJoin( 3 ); break;
657                         case '4': network_ChannelJoin( 4 ); break;
658                         case '5': network_ChannelJoin( 5 ); break;
659                         case '6': network_ChannelJoin( 6 ); break;
660                         case '7': network_ChannelJoin( 7 ); break;
661                         case '8': network_ChannelJoin( 8 ); break;
662                         case '9': network_ChannelJoin( 9 ); break;
663
664                         default:
665                             intf_DbgMsg( "vout: unhandled key '%c' (%i)", 
666                                          (char)i_key, i_key );
667                             break;
668                         }
669                     }
670                 break;
671             }
672         }
673         /* Mouse click */
674         else if( xevent.type == ButtonPress )
675         {
676             switch( ((XButtonEvent *)&xevent)->button )
677             {
678                 case Button1:
679                     /* In this part we will eventually manage
680                      * clicks for DVD navigation for instance. For the
681                      * moment just pause the stream. */
682                     input_SetStatus( p_main->p_intf->p_input,
683                                      INPUT_STATUS_PAUSE );
684                     break;
685
686                 case Button4:
687                     vout_Seek( 15 );
688                     break;
689
690                 case Button5:
691                     vout_Seek( -15 );
692                     break;
693             }
694         }
695         /* Mouse release */
696         else if( xevent.type == ButtonRelease )
697         {
698             switch( ((XButtonEvent *)&xevent)->button )
699             {
700                 case Button3:
701                     /* FIXME: need locking ! */
702                     p_main->p_intf->b_menu_change = 1;
703                     break;
704             }
705         }
706         /* Mouse move */
707         else if( xevent.type == MotionNotify )
708         {
709             p_vout->p_sys->i_time_mouse_last_moved = mdate();
710             if( ! p_vout->p_sys->b_mouse_pointer_visible )
711             {
712                 ToggleCursor( p_vout ); 
713             }
714         }
715         /* Other event */
716         else
717         {
718             intf_WarnMsg( 3, "vout: unhandled event %d received", xevent.type );
719         }
720     }
721
722 #ifdef MODULE_NAME_IS_xvideo
723     /* Handle events for YUV video output sub-window */
724     while( XCheckWindowEvent( p_vout->p_sys->p_display,
725                               p_vout->p_sys->yuv_window,
726                               ExposureMask, &xevent ) == True )
727     {
728         /* Window exposed (only handled if stream playback is paused) */
729         if( xevent.type == Expose )
730         {
731             if( ((XExposeEvent *)&xevent)->count == 0 )
732             {
733                 /* (if this is the last a collection of expose events...) */
734                 if( p_main->p_intf->p_input != NULL )
735                 {
736                     if( PAUSE_S ==
737                             p_main->p_intf->p_input->stream.control.i_status )
738                     {
739 /*                        XVideoDisplay( p_vout )*/;
740                     }
741                 }
742             }
743         }
744     }
745 #endif
746
747     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
748      * are handled - according to the man pages, the format is always 32
749      * in this case */
750     while( XCheckTypedEvent( p_vout->p_sys->p_display,
751                              ClientMessage, &xevent ) )
752     {
753         if( (xevent.xclient.message_type == p_vout->p_sys->wm_protocols)
754             && (xevent.xclient.data.l[0] == p_vout->p_sys->wm_delete_window ) )
755         {
756             p_main->p_intf->b_die = 1;
757         }
758         else
759         {
760             intf_DbgMsg( "vout: unhandled ClientMessage received" );
761         }
762     }
763
764     if ( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
765     {
766         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
767
768         p_vout->b_fullscreen = !p_vout->b_fullscreen;
769
770         /* Get rid of the old window */
771         DestroyWindow( p_vout );
772
773         /* And create a new one */
774         if( CreateWindow( p_vout ) )
775         {
776             intf_ErrMsg( "vout error: cannot create X11 window" );
777             XCloseDisplay( p_vout->p_sys->p_display );
778
779             free( p_vout->p_sys );
780             return( 1 );
781         }
782
783     }
784
785 #ifdef MODULE_NAME_IS_x11
786     /*
787      * Handle vout window resizing
788      */
789 #if 0
790     if( b_resized )
791     {
792         /* If interface window has been resized, change vout size */
793         intf_DbgMsg( "vout: resizing output window" );
794         p_vout->i_width =  p_vout->p_sys->i_width;
795         p_vout->i_height = p_vout->p_sys->i_height;
796         p_vout->i_changes |= VOUT_SIZE_CHANGE;
797     }
798     else if( (p_vout->i_width  != p_vout->p_sys->i_width) ||
799              (p_vout->i_height != p_vout->p_sys->i_height) )
800     {
801         /* If video output size has changed, change interface window size */
802         intf_DbgMsg( "vout: resizing output window" );
803         p_vout->p_sys->i_width =    p_vout->i_width;
804         p_vout->p_sys->i_height =   p_vout->i_height;
805         XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->window,
806                        p_vout->p_sys->i_width, p_vout->p_sys->i_height );
807     }
808     /*
809      * Color/Grayscale or gamma change: in 8bpp, just change the colormap
810      */
811     if( (p_vout->i_changes & VOUT_GRAYSCALE_CHANGE)
812         && (p_vout->i_screen_depth == 8) )
813     {
814         /* FIXME: clear flags ?? */
815     }
816
817     /*
818      * Size change
819      */
820     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
821     {
822         intf_DbgMsg( "vout info: resizing window" );
823         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
824
825         /* Resize window */
826         XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->window,
827                        p_vout->i_width, p_vout->i_height );
828
829         /* Destroy XImages to change their size */
830         vout_End( p_vout );
831
832         /* Recreate XImages. If SysInit failed, the thread can't go on. */
833         if( vout_Init( p_vout ) )
834         {
835             intf_ErrMsg( "vout error: cannot resize display" );
836             return( 1 );
837        }
838
839         /* Tell the video output thread that it will need to rebuild YUV
840          * tables. This is needed since conversion buffer size may have
841          * changed */
842         p_vout->i_changes |= VOUT_YUV_CHANGE;
843         intf_Msg( "vout: video display resized (%dx%d)",
844                   p_vout->i_width, p_vout->i_height);
845     }
846 #endif /* #if 0 */
847 #else
848     /*
849      * Size change
850      */
851     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
852     {
853         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
854
855         intf_WarnMsg( 3, "vout: video display resized (%dx%d)",
856                       p_vout->p_sys->i_width,
857                       p_vout->p_sys->i_height );
858     }
859 #endif
860
861     /* Autohide Cursour */
862     if( mdate() - p_vout->p_sys->i_time_mouse_last_moved > 2000000 )
863     {
864         /* Hide the mouse automatically */
865         if( p_vout->p_sys->b_mouse_pointer_visible )
866         {
867             ToggleCursor( p_vout ); 
868         }
869     }
870
871     return 0;
872 }
873
874 /*****************************************************************************
875  * vout_End: terminate X11 video thread output method
876  *****************************************************************************
877  * Destroy the X11 XImages created by vout_Init. It is called at the end of
878  * the thread, but also each time the window is resized.
879  *****************************************************************************/
880 static void vout_End( vout_thread_t *p_vout )
881 {
882     int i_index;
883
884     /* Free the direct buffers we allocated */
885     for( i_index = I_OUTPUTPICTURES ; i_index ; )
886     {
887         i_index--;
888         FreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
889     }
890 }
891
892 /* following functions are local */
893
894 /*****************************************************************************
895  * CreateWindow: open and set-up X11 main window
896  *****************************************************************************/
897 static int CreateWindow( vout_thread_t *p_vout )
898 {
899     XSizeHints              xsize_hints;
900     XSetWindowAttributes    xwindow_attributes;
901     XGCValues               xgcvalues;
902     XEvent                  xevent;
903     Atom                    prop;
904     mwmhints_t              mwmhints;
905
906     boolean_t               b_expose;
907     boolean_t               b_configure_notify;
908     boolean_t               b_map_notify;
909
910     /* If we're full screen, we're full screen! */
911     if( p_vout->b_fullscreen ) 
912     {
913         p_vout->p_sys->i_width =
914            DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
915         p_vout->p_sys->i_height =
916            DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen ); 
917     }
918     else
919     {
920         /* Set main window's size */
921         if( p_vout->render.i_height * p_vout->render.i_aspect
922              >= p_vout->render.i_width * VOUT_ASPECT_FACTOR )
923         {
924             p_vout->p_sys->i_width = p_vout->render.i_height
925                 * p_vout->render.i_aspect / VOUT_ASPECT_FACTOR;
926             p_vout->p_sys->i_height = p_vout->render.i_height;
927         }
928         else
929         {
930             p_vout->p_sys->i_width = p_vout->render.i_width;
931             p_vout->p_sys->i_height = p_vout->render.i_width
932                 * VOUT_ASPECT_FACTOR / p_vout->render.i_aspect;
933         }
934
935 #if 0
936         if( p_vout->p_sys->i_width <= 300 && p_vout->p_sys->i_height <= 300 )
937         {
938             p_vout->p_sys->i_width <<= 1;
939             p_vout->p_sys->i_height <<= 1;
940         }
941         else if( p_vout->p_sys->i_width <= 400
942                   && p_vout->p_sys->i_height <= 400 )
943         {
944             p_vout->p_sys->i_width += p_vout->p_sys->i_width >> 1;
945             p_vout->p_sys->i_height += p_vout->p_sys->i_height >> 1;
946         }
947 #endif
948     }
949
950     /* Prepare window manager hints and properties */
951     xsize_hints.base_width          = p_vout->p_sys->i_width;
952     xsize_hints.base_height         = p_vout->p_sys->i_height;
953     xsize_hints.flags               = PSize;
954     p_vout->p_sys->wm_protocols     = XInternAtom( p_vout->p_sys->p_display,
955                                                    "WM_PROTOCOLS", True );
956     p_vout->p_sys->wm_delete_window = XInternAtom( p_vout->p_sys->p_display,
957                                                    "WM_DELETE_WINDOW", True );
958
959     /* Prepare window attributes */
960     xwindow_attributes.backing_store = Always;       /* save the hidden part */
961     xwindow_attributes.background_pixel = BlackPixel( p_vout->p_sys->p_display,
962                                                       p_vout->p_sys->i_screen );
963     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
964     
965
966     /* Create the window and set hints - the window must receive ConfigureNotify
967      * events, and, until it is displayed, Expose and MapNotify events. */
968
969     p_vout->p_sys->window =
970         XCreateWindow( p_vout->p_sys->p_display,
971                        DefaultRootWindow( p_vout->p_sys->p_display ),
972                        0, 0,
973                        p_vout->p_sys->i_width,
974                        p_vout->p_sys->i_height,
975 #ifdef MODULE_NAME_IS_x11
976                        /* XXX - what's this ? */
977                        0,
978 #else
979                        1,
980 #endif
981                        0, InputOutput, 0,
982                        CWBackingStore | CWBackPixel | CWEventMask,
983                        &xwindow_attributes );
984
985     if ( p_vout->b_fullscreen )
986     {
987         prop = XInternAtom(p_vout->p_sys->p_display, "_MOTIF_WM_HINTS", False);
988         mwmhints.flags = MWM_HINTS_DECORATIONS;
989         mwmhints.decorations = 0;
990         XChangeProperty( p_vout->p_sys->p_display, p_vout->p_sys->window,
991                          prop, prop, 32, PropModeReplace,
992                          (unsigned char *)&mwmhints, PROP_MWM_HINTS_ELEMENTS );
993
994         XSetTransientForHint( p_vout->p_sys->p_display,
995                               p_vout->p_sys->window, None );
996         XRaiseWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
997     }
998
999     /* Set window manager hints and properties: size hints, command,
1000      * window's name, and accepted protocols */
1001     XSetWMNormalHints( p_vout->p_sys->p_display, p_vout->p_sys->window,
1002                        &xsize_hints );
1003     XSetCommand( p_vout->p_sys->p_display, p_vout->p_sys->window,
1004                  p_main->ppsz_argv, p_main->i_argc );
1005     XStoreName( p_vout->p_sys->p_display, p_vout->p_sys->window,
1006 #ifdef MODULE_NAME_IS_x11
1007                 VOUT_TITLE " (X11 output)"
1008 #else
1009                 VOUT_TITLE " (XVideo output)"
1010 #endif
1011               );
1012
1013     if( (p_vout->p_sys->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1014         || (p_vout->p_sys->wm_delete_window == None)
1015         || !XSetWMProtocols( p_vout->p_sys->p_display, p_vout->p_sys->window,
1016                              &p_vout->p_sys->wm_delete_window, 1 ) )
1017     {
1018         /* WM_DELETE_WINDOW is not supported by window manager */
1019         intf_Msg( "vout error: missing or bad window manager" );
1020     }
1021
1022     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1023      * event when using functions like XCopyArea */
1024     xgcvalues.graphics_exposures = False;
1025     p_vout->p_sys->gc = XCreateGC( p_vout->p_sys->p_display,
1026                                    p_vout->p_sys->window,
1027                                    GCGraphicsExposures, &xgcvalues);
1028
1029     /* Send orders to server, and wait until window is displayed - three
1030      * events must be received: a MapNotify event, an Expose event allowing
1031      * drawing in the window, and a ConfigureNotify to get the window
1032      * dimensions. Once those events have been received, only ConfigureNotify
1033      * events need to be received. */
1034     b_expose = 0;
1035     b_configure_notify = 0;
1036     b_map_notify = 0;
1037     XMapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window);
1038     do
1039     {
1040         XNextEvent( p_vout->p_sys->p_display, &xevent);
1041         if( (xevent.type == Expose)
1042             && (xevent.xexpose.window == p_vout->p_sys->window) )
1043         {
1044             b_expose = 1;
1045         }
1046         else if( (xevent.type == MapNotify)
1047                  && (xevent.xmap.window == p_vout->p_sys->window) )
1048         {
1049             b_map_notify = 1;
1050         }
1051         else if( (xevent.type == ConfigureNotify)
1052                  && (xevent.xconfigure.window == p_vout->p_sys->window) )
1053         {
1054             b_configure_notify = 1;
1055             p_vout->p_sys->i_width = xevent.xconfigure.width;
1056             p_vout->p_sys->i_height = xevent.xconfigure.height;
1057         }
1058     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1059
1060     XSelectInput( p_vout->p_sys->p_display, p_vout->p_sys->window,
1061                   StructureNotifyMask | KeyPressMask |
1062                   ButtonPressMask | ButtonReleaseMask | 
1063                   PointerMotionMask );
1064
1065     if( p_vout->b_fullscreen )
1066     {
1067         XSetInputFocus( p_vout->p_sys->p_display, p_vout->p_sys->window,
1068                         RevertToNone, CurrentTime );
1069         XMoveWindow( p_vout->p_sys->p_display, p_vout->p_sys->window, 0, 0 );
1070     }
1071
1072 #ifdef MODULE_NAME_IS_x11
1073     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1074     {
1075         /* Allocate a new palette */
1076         p_vout->p_sys->colormap =
1077             XCreateColormap( p_vout->p_sys->p_display,
1078                              DefaultRootWindow( p_vout->p_sys->p_display ),
1079                              DefaultVisual( p_vout->p_sys->p_display,
1080                                             p_vout->p_sys->i_screen ),
1081                              AllocAll );
1082
1083         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1084         XChangeWindowAttributes( p_vout->p_sys->p_display,
1085                                  p_vout->p_sys->window,
1086                                  CWColormap, &xwindow_attributes );
1087     }
1088
1089 #else
1090     /* Create YUV output sub-window. */
1091     p_vout->p_sys->yuv_window = XCreateSimpleWindow( p_vout->p_sys->p_display,
1092                          p_vout->p_sys->window, 0, 0, 1, 1, 0,
1093                          BlackPixel( p_vout->p_sys->p_display,
1094                                          p_vout->p_sys->i_screen ),
1095                          WhitePixel( p_vout->p_sys->p_display,
1096                                          p_vout->p_sys->i_screen ) );
1097
1098     p_vout->p_sys->yuv_gc = XCreateGC( p_vout->p_sys->p_display,
1099                                        p_vout->p_sys->yuv_window,
1100                                        GCGraphicsExposures, &xgcvalues );
1101     
1102     XSetWindowBackground( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
1103              BlackPixel(p_vout->p_sys->p_display, p_vout->p_sys->i_screen ) );
1104     
1105     XMapWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window );
1106     XSelectInput( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
1107                   ExposureMask );
1108 #endif
1109
1110     /* If the cursor was formerly blank than blank it again */
1111     if( !p_vout->p_sys->b_mouse_pointer_visible )
1112     {
1113         ToggleCursor( p_vout );
1114         ToggleCursor( p_vout );
1115     }
1116
1117     XSync( p_vout->p_sys->p_display, False );
1118
1119     /* At this stage, the window is open, displayed, and ready to
1120      * receive data */
1121
1122     return( 0 );
1123 }
1124
1125 static void DestroyWindow( vout_thread_t *p_vout )
1126 {
1127     XSync( p_vout->p_sys->p_display, False );
1128
1129 #ifdef MODULE_NAME_IS_xvideo
1130     XFreeGC( p_vout->p_sys->p_display, p_vout->p_sys->yuv_gc );
1131     XDestroyWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window );
1132 #endif
1133
1134     XUnmapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
1135     XFreeGC( p_vout->p_sys->p_display, p_vout->p_sys->gc );
1136     XDestroyWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
1137 }
1138
1139 /*****************************************************************************
1140  * NewPicture: allocate a picture
1141  *****************************************************************************
1142  * Returns 0 on success, -1 otherwise
1143  *****************************************************************************/
1144 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1145 {
1146 #define P p_pic->planes
1147     int i_width  = p_vout->output.i_width;
1148     int i_height = p_vout->output.i_height;
1149     
1150     switch( p_vout->output.i_chroma )
1151     {
1152 #ifdef MODULE_NAME_IS_xvideo
1153         case YUV_420_PICTURE:
1154             /* We know this chroma, allocate a buffer which will be used
1155              * directly by the decoder */
1156             p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1157
1158             if( p_pic->p_sys == NULL )
1159             {
1160                 return -1;
1161             }
1162
1163             if( p_vout->p_sys->b_shm )
1164             {
1165                 /* Create XvImage using XShm extension */
1166                 p_pic->p_sys->p_image =
1167                     CreateShmImage( p_vout->p_sys->p_display,
1168                                     p_vout->p_sys->i_xvport,
1169                                     GUID_YUV12_PLANAR,
1170                                     &p_pic->p_sys->shminfo,
1171                                     p_vout->output.i_width,
1172                                     p_vout->output.i_height );
1173             }
1174             else
1175             {
1176                 /* Create XvImage using XShm extension */
1177                 p_pic->p_sys->p_image =
1178                     CreateImage( p_vout->p_sys->p_display,
1179                                  p_vout->p_sys->i_xvport,
1180                                  GUID_YUV12_PLANAR,
1181                                  p_vout->output.i_width,
1182                                  p_vout->output.i_height );
1183             }
1184
1185             if( p_pic->p_sys->p_image == NULL )
1186             {
1187                 free( p_pic->p_sys );
1188                 return -1;
1189             }
1190
1191             /* FIXME: try to get the right i_bytes value from p_image */
1192             P[Y_PLANE].p_data = p_pic->p_sys->p_image->data;
1193             P[Y_PLANE].i_bytes = i_width * i_height;
1194             P[Y_PLANE].i_line_bytes = i_width;
1195
1196             P[U_PLANE].p_data = P[Y_PLANE].p_data + i_width * i_height * 5 / 4;
1197             P[U_PLANE].i_bytes = i_width * i_height / 4;
1198             P[U_PLANE].i_line_bytes = i_width / 2;
1199
1200             P[V_PLANE].p_data = P[Y_PLANE].p_data + i_width * i_height;
1201             P[V_PLANE].i_bytes = i_width * i_height / 4;
1202             P[V_PLANE].i_line_bytes = i_width / 2;
1203
1204             p_pic->i_planes = 3;
1205
1206             return 0;
1207 #endif
1208
1209 #ifdef MODULE_NAME_IS_x11
1210         case RGB_16BPP_PICTURE:
1211             p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1212
1213             if( p_pic->p_sys == NULL )
1214             {
1215                 return -1;
1216             }
1217
1218             if( p_vout->p_sys->b_shm )
1219             {
1220                 p_pic->p_sys->p_image =
1221                     CreateShmImage( p_vout->p_sys->p_display,
1222                                     p_vout->p_sys->p_visual,
1223                                     p_vout->p_sys->i_screen_depth,
1224                                     &p_pic->p_sys->shminfo,
1225                                     i_width, i_height );
1226             }
1227             else
1228             {
1229                 p_pic->p_sys->p_image =
1230                     CreateImage( p_vout->p_sys->p_display,
1231                                  p_vout->p_sys->p_visual,
1232                                  p_vout->p_sys->i_screen_depth, 
1233                                  p_vout->p_sys->i_bytes_per_pixel,
1234                                  i_width, i_height );
1235             }
1236
1237             if( p_pic->p_sys->p_image == NULL )
1238             {
1239                 free( p_pic->p_sys );
1240                 return -1;
1241             }
1242
1243             /* FIXME: try to get the right i_bytes value from p_image */
1244             P[ RGB_PLANE ].p_data = p_pic->p_sys->p_image->data;
1245             P[ RGB_PLANE ].i_bytes = 2 * i_width * i_height;
1246             P[ RGB_PLANE ].i_line_bytes = 2 * i_width;
1247
1248             p_pic->i_planes = 1;
1249
1250             return 0;
1251 #endif
1252
1253         default:
1254             /* Unknown chroma, tell the guy to get lost */
1255             p_pic->i_planes = 0;
1256
1257             return -1;
1258     }
1259 #undef P
1260 }
1261
1262 /*****************************************************************************
1263  * FreePicture: destroy a picture allocated with NewPicture
1264  *****************************************************************************
1265  * Destroy XImage AND associated data. If using Shm, detach shared memory
1266  * segment from server and process, then free it. The XDestroyImage manpage
1267  * says that both the image structure _and_ the data pointed to by the
1268  * image structure are freed, so no need to free p_image->data.
1269  *****************************************************************************/
1270 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
1271 {
1272     /* FIXME: check the operation order */
1273
1274     if( p_vout->p_sys->b_shm )
1275     {
1276         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
1277
1278         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
1279         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
1280         {
1281             intf_ErrMsg( "vout error: cannot detach shared memory (%s)",
1282                          strerror(errno) );
1283         }
1284     }
1285
1286     XSync( p_vout->p_sys->p_display, False );
1287     IMAGE_FREE( p_pic->p_sys->p_image );
1288
1289     free( p_pic->p_sys );
1290 }
1291
1292 /*****************************************************************************
1293  * EnableXScreenSaver: enable screen saver
1294  *****************************************************************************
1295  * This function enable the screen saver on a display after it had been
1296  * disabled by XDisableXScreenSaver. Both functions use a counter mechanism to
1297  * know wether the screen saver can be activated or not: if n successive calls
1298  * are made to XDisableXScreenSaver, n successive calls to XEnableXScreenSaver
1299  * will be required before the screen saver could effectively be activated.
1300  *****************************************************************************/
1301 static void EnableXScreenSaver( vout_thread_t *p_vout )
1302 {
1303     intf_DbgMsg( "vout: enabling screen saver" );
1304     XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
1305                      p_vout->p_sys->i_ss_interval,
1306                      p_vout->p_sys->i_ss_blanking,
1307                      p_vout->p_sys->i_ss_exposure );
1308 }
1309
1310 /*****************************************************************************
1311  * DisableXScreenSaver: disable screen saver
1312  *****************************************************************************
1313  * See XEnableXScreenSaver
1314  *****************************************************************************/
1315 static void DisableXScreenSaver( vout_thread_t *p_vout )
1316 {
1317     /* Save screen saver informations */
1318     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
1319                      &p_vout->p_sys->i_ss_interval,
1320                      &p_vout->p_sys->i_ss_blanking,
1321                      &p_vout->p_sys->i_ss_exposure );
1322
1323     /* Disable screen saver */
1324     intf_DbgMsg( "vout: disabling screen saver" );
1325     XSetScreenSaver( p_vout->p_sys->p_display, 0,
1326                      p_vout->p_sys->i_ss_interval,
1327                      p_vout->p_sys->i_ss_blanking,
1328                      p_vout->p_sys->i_ss_exposure );
1329
1330 #ifdef MODULE_NAME_IS_xvideo
1331     DPMSDisable( p_vout->p_sys->p_display );
1332 #endif
1333 }
1334
1335 /*****************************************************************************
1336  * CreateCursor: create a blank mouse pointer
1337  *****************************************************************************/
1338 static void CreateCursor( vout_thread_t *p_vout )
1339 {
1340     XColor cursor_color;
1341
1342     p_vout->p_sys->cursor_pixmap =
1343         XCreatePixmap( p_vout->p_sys->p_display,
1344                        DefaultRootWindow( p_vout->p_sys->p_display ),
1345                        1, 1, 1 );
1346
1347     XParseColor( p_vout->p_sys->p_display,
1348                  XCreateColormap( p_vout->p_sys->p_display,
1349                                   DefaultRootWindow( p_vout->p_sys->p_display ),
1350                                   DefaultVisual( p_vout->p_sys->p_display,
1351                                                  p_vout->p_sys->i_screen ),
1352                                   AllocNone ),
1353                  "black", &cursor_color );
1354
1355     p_vout->p_sys->blank_cursor =
1356         XCreatePixmapCursor( p_vout->p_sys->p_display,
1357                              p_vout->p_sys->cursor_pixmap,
1358                              p_vout->p_sys->cursor_pixmap,
1359                              &cursor_color, &cursor_color, 1, 1 );
1360 }
1361
1362 /*****************************************************************************
1363  * DestroyCursor: destroy the blank mouse pointer
1364  *****************************************************************************/
1365 static void DestroyCursor( vout_thread_t *p_vout )
1366 {
1367     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
1368 }
1369
1370 /*****************************************************************************
1371  * ToggleCursor: hide or show the mouse pointer
1372  *****************************************************************************
1373  * This function hides the X pointer if it is visible by putting it at
1374  * coordinates (32,32) and setting the pointer sprite to a blank one. To
1375  * show it again, we disable the sprite and restore the original coordinates.
1376  *****************************************************************************/
1377 static void ToggleCursor( vout_thread_t *p_vout )
1378 {
1379     if( p_vout->p_sys->b_mouse_pointer_visible )
1380     {
1381         XDefineCursor( p_vout->p_sys->p_display,
1382                        p_vout->p_sys->window,
1383                        p_vout->p_sys->blank_cursor );
1384         p_vout->p_sys->b_mouse_pointer_visible = 0;
1385     }
1386     else
1387     {
1388         XUndefineCursor( p_vout->p_sys->p_display, p_vout->p_sys->window );
1389         p_vout->p_sys->b_mouse_pointer_visible = 1;
1390     }
1391 }
1392
1393 #ifdef MODULE_NAME_IS_xvideo
1394 /*****************************************************************************
1395  * XVideoGetPort: get YUV12 port
1396  *****************************************************************************/
1397 static int XVideoGetPort( Display *dpy, int i_id )
1398 {
1399     XvAdaptorInfo *p_adaptor;
1400     unsigned int i;
1401     int i_adaptor, i_num_adaptors, i_requested_adaptor;
1402     int i_selected_port;
1403
1404     switch( XvQueryExtension( dpy, &i, &i, &i, &i, &i ) )
1405     {
1406         case Success:
1407             break;
1408
1409         case XvBadExtension:
1410             intf_WarnMsg( 3, "vout error: XvBadExtension" );
1411             return( -1 );
1412
1413         case XvBadAlloc:
1414             intf_WarnMsg( 3, "vout error: XvBadAlloc" );
1415             return( -1 );
1416
1417         default:
1418             intf_WarnMsg( 3, "vout error: XvQueryExtension failed" );
1419             return( -1 );
1420     }
1421
1422     switch( XvQueryAdaptors( dpy, DefaultRootWindow( dpy ),
1423                              &i_num_adaptors, &p_adaptor ) )
1424     {
1425         case Success:
1426             break;
1427
1428         case XvBadExtension:
1429             intf_WarnMsg( 3, "vout error: XvBadExtension for XvQueryAdaptors" );
1430             return( -1 );
1431
1432         case XvBadAlloc:
1433             intf_WarnMsg( 3, "vout error: XvBadAlloc for XvQueryAdaptors" );
1434             return( -1 );
1435
1436         default:
1437             intf_WarnMsg( 3, "vout error: XvQueryAdaptors failed" );
1438             return( -1 );
1439     }
1440
1441     i_selected_port = -1;
1442     i_requested_adaptor = main_GetIntVariable( VOUT_XVADAPTOR_VAR, -1 );
1443
1444     /* No special xv port has been requested so try all of them */
1445     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
1446     {
1447         XvImageFormatValues *p_formats;
1448         int i_format, i_num_formats;
1449         int i_port;
1450
1451         /* If we requested an adaptor and it's not this one, we aren't
1452          * interested */
1453         if( i_requested_adaptor != -1 && i_adaptor != i_requested_adaptor )
1454         {
1455             continue;
1456         }
1457
1458         /* If the adaptor doesn't have the required properties, skip it */
1459         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
1460             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
1461         {
1462             continue;
1463         }
1464
1465         /* Check that port supports YUV12 planar format... */
1466         p_formats = XvListImageFormats( dpy, p_adaptor[i_adaptor].base_id,
1467                                         &i_num_formats );
1468
1469         for( i_format = 0; i_format < i_num_formats; i_format++ )
1470         {
1471             XvEncodingInfo  *p_enc;
1472             int             i_enc, i_num_encodings;
1473             XvAttribute     *p_attr;
1474             int             i_attr, i_num_attributes;
1475
1476             /* If this is not the format we want, forget it */
1477             if( p_formats[ i_format ].id != i_id )
1478             {
1479                 continue;
1480             }
1481
1482             /* Look for the first available port supporting this format */
1483             for( i_port = p_adaptor[i_adaptor].base_id;
1484                  ( i_port < p_adaptor[i_adaptor].base_id
1485                              + p_adaptor[i_adaptor].num_ports )
1486                    && ( i_selected_port == -1 );
1487                  i_port++ )
1488             {
1489                 if( XvGrabPort( dpy, i_port, CurrentTime ) == Success )
1490                 {
1491                     i_selected_port = i_port;
1492                 }
1493             }
1494
1495             /* If no free port was found, forget it */
1496             if( i_selected_port == -1 )
1497             {
1498                 continue;
1499             }
1500
1501             /* If we found a port, print information about it */
1502             intf_WarnMsg( 3, "vout: found adaptor %i, port %i, "
1503                              "image format 0x%x (%4.4s) %s",
1504                              i_adaptor, i_selected_port,
1505                              p_formats[ i_format ].id,
1506                              (char *)&p_formats[ i_format ].id,
1507                              ( p_formats[ i_format ].format
1508                                 == XvPacked ) ? "packed" : "planar" );
1509
1510             intf_WarnMsg( 10, " encoding list:" );
1511
1512             if( XvQueryEncodings( dpy, i_selected_port,
1513                                   &i_num_encodings, &p_enc )
1514                  != Success )
1515             {
1516                 intf_WarnMsg( 10, "  XvQueryEncodings failed" );
1517                 continue;
1518             }
1519
1520             for( i_enc = 0; i_enc < i_num_encodings; i_enc++ )
1521             {
1522                 intf_WarnMsg( 10, "  id=%ld, name=%s, size=%ldx%ld,"
1523                                   " numerator=%d, denominator=%d",
1524                               p_enc[i_enc].encoding_id, p_enc[i_enc].name,
1525                               p_enc[i_enc].width, p_enc[i_enc].height,
1526                               p_enc[i_enc].rate.numerator,
1527                               p_enc[i_enc].rate.denominator );
1528             }
1529
1530             if( p_enc != NULL )
1531             {
1532                 XvFreeEncodingInfo( p_enc );
1533             }
1534
1535             intf_WarnMsg( 10, " attribute list:" );
1536             p_attr = XvQueryPortAttributes( dpy, i_selected_port,
1537                                             &i_num_attributes );
1538             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
1539             {
1540                 intf_WarnMsg( 10,
1541                       "  name=%s, flags=[%s%s ], min=%i, max=%i",
1542                       p_attr[i_attr].name,
1543                       (p_attr[i_attr].flags & XvGettable) ? " get" : "",
1544                       (p_attr[i_attr].flags & XvSettable) ? " set" : "",
1545                       p_attr[i_attr].min_value, p_attr[i_attr].max_value );
1546             }
1547
1548             if( p_attr != NULL )
1549             {
1550                 XFree( p_attr );
1551             }
1552         }
1553
1554         if( p_formats != NULL )
1555         {
1556             XFree( p_formats );
1557         }
1558
1559     }
1560
1561     if( i_num_adaptors > 0 )
1562     {
1563         XvFreeAdaptorInfo( p_adaptor );
1564     }
1565
1566     if( i_selected_port == -1 )
1567     {
1568         if( i_requested_adaptor == -1 )
1569         {
1570             intf_WarnMsg( 3, "vout: no free XVideo port found for YV12" );
1571         }
1572         else
1573         {
1574             intf_WarnMsg( 3, "vout: XVideo adaptor %i does not have a free "
1575                              "XVideo port for YV12", i_requested_adaptor );
1576         }
1577     }
1578
1579     return( i_selected_port );
1580 }
1581
1582 /*****************************************************************************
1583  * XVideoReleasePort: release YUV12 port
1584  *****************************************************************************/
1585 static void XVideoReleasePort( Display *dpy, int i_port )
1586 {
1587     XvGrabPort( dpy, i_port, CurrentTime );
1588 }
1589 #endif
1590
1591 /*****************************************************************************
1592  * InitDisplay: open and initialize X11 device
1593  *****************************************************************************
1594  * Create a window according to video output given size, and set other
1595  * properties according to the display properties.
1596  *****************************************************************************/
1597 static int InitDisplay( vout_thread_t *p_vout )
1598 {
1599 #ifdef MODULE_NAME_IS_x11
1600     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
1601     XVisualInfo *               p_xvisual;           /* visuals informations */
1602     XVisualInfo                 xvisual_template;         /* visual template */
1603     int                         i_count;                       /* array size */
1604 #endif
1605
1606 #ifdef SYS_DARWIN
1607     /* FIXME : As of 2001-03-16, XFree4 for MacOS X does not support Xshm. */
1608     p_vout->p_sys->b_shm = 0;
1609 #else
1610     p_vout->p_sys->b_shm = ( XShmQueryExtension( p_vout->p_sys->p_display )
1611                               == True );
1612 #endif
1613     if( !p_vout->p_sys->b_shm )
1614     {
1615         intf_WarnMsg( 1, "vout warning: XShm video extension is unavailable" );
1616     }
1617
1618 #ifdef MODULE_NAME_IS_xvideo
1619     /* XXX The brightness and contrast values should be read from environment
1620      * XXX variables... */
1621 #if 0
1622     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
1623     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
1624 #endif
1625 #endif
1626
1627 #ifdef MODULE_NAME_IS_x11
1628     /* Initialize structure */
1629     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
1630
1631     /* Get screen depth */
1632     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
1633                                                    p_vout->p_sys->i_screen );
1634     switch( p_vout->p_sys->i_screen_depth )
1635     {
1636     case 8:
1637         /*
1638          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
1639          */
1640         xvisual_template.screen =   p_vout->p_sys->i_screen;
1641         xvisual_template.class =    DirectColor;
1642         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
1643                                     VisualScreenMask | VisualClassMask,
1644                                     &xvisual_template, &i_count );
1645         if( p_xvisual == NULL )
1646         {
1647             intf_ErrMsg( "vout error: no PseudoColor visual available" );
1648             return( 1 );
1649         }
1650         p_vout->p_sys->i_bytes_per_pixel = 1;
1651         break;
1652     case 15:
1653     case 16:
1654     case 24:
1655     default:
1656         /*
1657          * Screen depth is higher than 8bpp. TrueColor visual is used.
1658          */
1659         xvisual_template.screen =   p_vout->p_sys->i_screen;
1660         xvisual_template.class =    TrueColor;
1661         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
1662                                     VisualScreenMask | VisualClassMask,
1663                                     &xvisual_template, &i_count );
1664         if( p_xvisual == NULL )
1665         {
1666             intf_ErrMsg( "vout error: no TrueColor visual available" );
1667             return( 1 );
1668         }
1669         p_vout->p_sys->i_red_mask =        p_xvisual->red_mask;
1670         p_vout->p_sys->i_green_mask =      p_xvisual->green_mask;
1671         p_vout->p_sys->i_blue_mask =       p_xvisual->blue_mask;
1672
1673         /* There is no difference yet between 3 and 4 Bpp. The only way
1674          * to find the actual number of bytes per pixel is to list supported
1675          * pixmap formats. */
1676         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
1677         p_vout->p_sys->i_bytes_per_pixel = 0;
1678
1679         for( ; i_count-- ; p_formats++ )
1680         {
1681             /* Under XFree4.0, the list contains pixmap formats available
1682              * through all video depths ; so we have to check against current
1683              * depth. */
1684             if( p_formats->depth == p_vout->p_sys->i_screen_depth )
1685             {
1686                 if( p_formats->bits_per_pixel / 8
1687                         > p_vout->p_sys->i_bytes_per_pixel )
1688                 {
1689                     p_vout->p_sys->i_bytes_per_pixel = p_formats->bits_per_pixel / 8;
1690                 }
1691             }
1692         }
1693         break;
1694     }
1695     p_vout->p_sys->p_visual = p_xvisual->visual;
1696     XFree( p_xvisual );
1697 #endif
1698
1699     return( 0 );
1700 }
1701
1702 /*****************************************************************************
1703  * CreateShmImage: create an XImage or XvImage using shared memory extension
1704  *****************************************************************************
1705  * Prepare an XImage or XvImage for display function.
1706  * The order of the operations respects the recommandations of the mit-shm
1707  * document by J.Corbet and K.Packard. Most of the parameters were copied from
1708  * there.
1709  *****************************************************************************/
1710 static IMAGE_TYPE * CreateShmImage( Display* p_display, EXTRA_ARGS_SHM,
1711                                     int i_width, int i_height )
1712 {
1713     IMAGE_TYPE *p_image;
1714
1715     /* Create XImage / XvImage */
1716 #ifdef MODULE_NAME_IS_xvideo
1717     p_image = XvShmCreateImage( p_display, i_xvport, i_format, 0,
1718                                 i_width, i_height, p_shm );
1719 #else
1720     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
1721                                p_shm, i_width, i_height );
1722 #endif
1723     if( p_image == NULL )
1724     {
1725         intf_ErrMsg( "vout error: image creation failed." );
1726         return( NULL );
1727     }
1728
1729     /* Allocate shared memory segment - 0776 set the access permission
1730      * rights (like umask), they are not yet supported by all X servers */
1731     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE, IPC_CREAT | 0776 );
1732     if( p_shm->shmid < 0 )
1733     {
1734         intf_ErrMsg( "vout error: cannot allocate shared image data (%s)",
1735                      strerror( errno ) );
1736         IMAGE_FREE( p_image );
1737         return( NULL );
1738     }
1739
1740     /* Attach shared memory segment to process (read/write) */
1741     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
1742     if(! p_shm->shmaddr )
1743     {                                                               /* error */
1744         intf_ErrMsg( "vout error: cannot attach shared memory (%s)",
1745                     strerror(errno));
1746         shmctl( p_shm->shmid, IPC_RMID, 0 );      /* free shared memory */
1747         IMAGE_FREE( p_image );
1748         return( NULL );
1749     }
1750
1751     /* Attach shared memory segment to X server */
1752 #ifdef MODULE_NAME_IS_xvideo
1753     p_shm->readOnly = False; /* XXX: What's this ? */
1754 #else
1755     p_shm->readOnly = True;
1756 #endif
1757     if( XShmAttach( p_display, p_shm ) == False )
1758     {
1759         intf_ErrMsg( "vout error: cannot attach shared memory to X server" );
1760         shmctl( p_shm->shmid, IPC_RMID, 0 );
1761         shmdt( p_shm->shmaddr );
1762         IMAGE_FREE( p_image );
1763         return( NULL );
1764     }
1765
1766     /* Send image to X server. This instruction is required, since having
1767      * built a Shm XImage and not using it causes an error on XCloseDisplay */
1768     XSync( p_display, False );
1769
1770 #if 0
1771     /* Mark the shm segment to be removed when there are no more
1772      * attachements, so it is automatic on process exit or after shmdt */
1773     shmctl( p_shm->shmid, IPC_RMID, 0 );
1774 #endif
1775
1776     return( p_image );
1777 }
1778
1779 /*****************************************************************************
1780  * CreateImage: create an XImage or XvImage
1781  *****************************************************************************
1782  * Create a simple image used as a buffer.
1783  *****************************************************************************/
1784 static IMAGE_TYPE * CreateImage( Display *p_display, EXTRA_ARGS,
1785                                  int i_width, int i_height )
1786 {
1787     byte_t *    p_data;                           /* image data storage zone */
1788     IMAGE_TYPE *p_image;
1789 #ifdef MODULE_NAME_IS_x11
1790     int         i_quantum;                     /* XImage quantum (see below) */
1791     int         i_bytes_per_line;
1792 #endif
1793
1794     /* Allocate memory for image */
1795 #ifdef MODULE_NAME_IS_xvideo
1796     p_data = (byte_t *) malloc( i_width * i_height * 2 ); /* XXX */
1797 #else
1798     i_bytes_per_line = i_width * i_bytes_per_pixel;
1799     p_data = (byte_t *) malloc( i_bytes_per_line * i_height );
1800 #endif
1801     if( !p_data )
1802     {
1803         intf_ErrMsg( "vout error: %s", strerror(ENOMEM));
1804         return( NULL );
1805     }
1806
1807 #ifdef MODULE_NAME_IS_x11
1808     /* Optimize the quantum of a scanline regarding its size - the quantum is
1809        a diviser of the number of bits between the start of two scanlines. */
1810     if( i_bytes_per_line & 0xf )
1811     {
1812         i_quantum = 0x8;
1813     }
1814     else if( i_bytes_per_line & 0x10 )
1815     {
1816         i_quantum = 0x10;
1817     }
1818     else
1819     {
1820         i_quantum = 0x20;
1821     }
1822 #endif
1823
1824     /* Create XImage. p_data will be automatically freed */
1825 #ifdef MODULE_NAME_IS_xvideo
1826     p_image = XvCreateImage( p_display, i_xvport, i_format,
1827                              p_data, i_width, i_height );
1828 #else
1829     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
1830                             p_data, i_width, i_height, i_quantum, 0 );
1831 #endif
1832     if( p_image == NULL )
1833     {
1834         intf_ErrMsg( "vout error: XCreateImage() failed" );
1835         free( p_data );
1836         return( NULL );
1837     }
1838
1839     return p_image;
1840 }
1841