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