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