]> git.sesse.net Git - vlc/blob - plugins/x11/vout_xvideo.c
* Compile fix for newer versions of MacOS X by Colin Simmonds
[vlc] / plugins / x11 / vout_xvideo.c
1 /*****************************************************************************
2  * vout_xvideo.c: Xvideo video output display method
3  *****************************************************************************
4  * Copyright (C) 1998, 1999, 2000, 2001 VideoLAN
5  * $Id: vout_xvideo.c,v 1.20 2001/06/25 11:34:08 sam Exp $
6  *
7  * Authors: Shane Harper <shanegh@optusnet.com.au>
8  *          Vincent Seguin <seguin@via.ecp.fr>
9  *          Samuel Hocevar <sam@zoy.org>
10  *          David Kennedy <dkennedy@tinytoad.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 #define MODULE_NAME xvideo
28 #include "modules_inner.h"
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #include "defs.h"
34
35 #include <errno.h>                                                 /* ENOMEM */
36 #include <stdlib.h>                                                /* free() */
37 #include <string.h>                                            /* strerror() */
38
39 #ifdef HAVE_MACHINE_PARAM_H
40 /* BSD */
41 #include <machine/param.h>
42 #include <sys/types.h>                                     /* typedef ushort */
43 #include <sys/ipc.h>
44 #endif
45
46 #ifndef WIN32
47 #include <netinet/in.h>                               /* BSD: struct in_addr */
48 #endif
49
50 #include <sys/shm.h>                                   /* shmget(), shmctl() */
51 #include <X11/Xlib.h>
52 #include <X11/Xutil.h>
53 #include <X11/keysym.h>
54 #include <X11/extensions/XShm.h>
55 #include <X11/extensions/Xv.h>
56 #include <X11/extensions/Xvlib.h>
57
58 #include "config.h"
59 #include "common.h"
60 #include "threads.h"
61 #include "mtime.h"
62 #include "tests.h"
63
64 #include "video.h"
65 #include "video_output.h"
66
67 #include "interface.h"
68 #include "intf_msg.h"
69
70 #include "netutils.h"                                 /* network_ChannelJoin */
71
72 #include "main.h"
73
74 #include "stream_control.h"                 /* needed by input_ext-intf.h... */
75 #include "input_ext-intf.h"
76
77 #include "modules.h"
78 #include "modules_export.h"
79
80 #define GUID_YUV12_PLANAR 0x32315659
81
82
83 /*****************************************************************************
84  * vout_sys_t: video output X11 method descriptor
85  *****************************************************************************
86  * This structure is part of the video output thread descriptor.
87  * It describes the XVideo specific properties of an output thread.
88  *****************************************************************************/
89 typedef struct vout_sys_s
90 {
91     /* User settings */
92 #if 0
93     /* this plugin (currently) requires the SHM Ext... */
94     boolean_t           b_shm;               /* shared memory extension flag */
95 #endif
96
97     /* Internal settings and properties */
98     Display *           p_display;                        /* display pointer */
99     int                 i_screen;                           /* screen number */
100     Window              window;                               /* root window */
101     GC                  gc;              /* graphic context instance handler */
102     Window              yuv_window;   /* sub-window for displaying yuv video
103                                                                         data */
104     GC                  yuv_gc;
105     int                 xv_port;
106
107     /* Display buffers and shared memory information */
108     /* Note: only 1 buffer... Xv ext does double buffering. */
109     XvImage *           p_xvimage;
110     int                 i_image_width;
111     int                 i_image_height;
112                                 /* i_image_width & i_image_height reflect the
113                                  * size of the XvImage. They are used by
114                                  * vout_Display() to check if the image to be
115                                  * displayed can use the current XvImage. */
116     XShmSegmentInfo     shm_info;       /* shared memory zone information */
117
118     /* X11 generic properties */
119     Atom                wm_protocols;
120     Atom                wm_delete_window;
121
122     int                 i_window_width;              /* width of main window */
123     int                 i_window_height;            /* height of main window */
124
125
126     /* Screen saver properties */
127     int                 i_ss_timeout;                             /* timeout */
128     int                 i_ss_interval;           /* interval between changes */
129     int                 i_ss_blanking;                      /* blanking mode */
130     int                 i_ss_exposure;                      /* exposure mode */
131     
132     /* Mouse pointer properties */
133     boolean_t           b_mouse_pointer_visible;
134     mtime_t             i_time_mouse_last_moved; /* used to auto-hide pointer*/
135
136 } vout_sys_t;
137
138 /* Fullscreen needs to be able to hide the wm decorations */
139 #define MWM_HINTS_DECORATIONS   (1L << 1)
140 #define PROP_MWM_HINTS_ELEMENTS 5
141 typedef struct mwmhints_s
142 {
143     u32 flags;
144     u32 functions;
145     u32 decorations;
146     s32 input_mode;
147     u32 status;
148 } mwmhints_t;
149
150 /*****************************************************************************
151  * Local prototypes
152  *****************************************************************************/
153 static int  vout_Probe     ( probedata_t * );
154 static int  vout_Create    ( vout_thread_t * );
155 static int  vout_Init      ( vout_thread_t * );
156 static void vout_End       ( vout_thread_t * );
157 static void vout_Destroy   ( vout_thread_t * );
158 static int  vout_Manage    ( vout_thread_t * );
159 static void vout_Display   ( vout_thread_t * );
160 static void vout_SetPalette( vout_thread_t *, u16 *, u16 *, u16 *, u16 * );
161
162 static int  XVideoCreateWindow       ( vout_thread_t * );
163 static void XVideoDestroyWindow      ( vout_thread_t *p_vout );
164 static int  XVideoUpdateImgSizeIfRequired( vout_thread_t *p_vout );
165 static int  XVideoCreateShmImage     ( Display* dpy, int xv_port,
166                                        XvImage **pp_xvimage,
167                                        XShmSegmentInfo *p_shm_info,
168                                        int i_width, int i_height );
169 static void XVideoDestroyShmImage    ( vout_thread_t *, XvImage *,
170                                        XShmSegmentInfo * );
171 static void XVideoSetMousePointer    ( const vout_thread_t * );
172 static void XVideoEnableScreenSaver  ( vout_thread_t * );
173 static void XVideoDisableScreenSaver ( vout_thread_t * );
174 /*static void XVideoSetAttribute       ( vout_thread_t *, char *, float );*/
175
176 static int  XVideoCheckForXv         ( Display * );
177 static int  XVideoGetPort            ( Display * );
178 static void XVideoOutputCoords       ( const picture_t *, const boolean_t,
179                                        const int, const int,
180                                        int *, int *, int *, int * );
181 static void XVideoDisplay            ( vout_thread_t * );
182
183 /*****************************************************************************
184  * Functions exported as capabilities. They are declared as static so that
185  * we don't pollute the namespace too much.
186  *****************************************************************************/
187 void _M( vout_getfunctions )( function_list_t * p_function_list )
188 {
189     p_function_list->pf_probe = vout_Probe;
190     p_function_list->functions.vout.pf_create     = vout_Create;
191     p_function_list->functions.vout.pf_init       = vout_Init;
192     p_function_list->functions.vout.pf_end        = vout_End;
193     p_function_list->functions.vout.pf_destroy    = vout_Destroy;
194     p_function_list->functions.vout.pf_manage     = vout_Manage;
195     p_function_list->functions.vout.pf_display    = vout_Display;
196     p_function_list->functions.vout.pf_setpalette = vout_SetPalette;
197 }
198
199 /*****************************************************************************
200  * vout_Probe: probe the video driver and return a score
201  *****************************************************************************
202  * This returns a score to the plugin manager so that it can select the best
203  * plugin.
204  *****************************************************************************/
205 static int vout_Probe( probedata_t *p_data )
206 {
207     if( TestMethod( VOUT_METHOD_VAR, "xvideo" ) )
208     {
209         return( 999 );
210     }
211
212     return( 60 );
213 }
214
215 /*****************************************************************************
216  * vout_Create: allocate XVideo video thread output method
217  *****************************************************************************
218  * This function allocate and initialize a XVideo vout method. It uses some of
219  * the vout properties to choose the window size, and change them according to
220  * the actual properties of the display.
221  *****************************************************************************/
222 static int vout_Create( vout_thread_t *p_vout )
223 {
224     char *psz_display;
225
226     /* Allocate structure */
227     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
228     if( p_vout->p_sys == NULL )
229     {
230         intf_ErrMsg( "vout error: %s", strerror(ENOMEM) );
231         return( 1 );
232     }
233
234     /* Open display, unsing 'vlc_display' or DISPLAY environment variable */
235     psz_display = XDisplayName( main_GetPszVariable( VOUT_DISPLAY_VAR, NULL ) );
236     p_vout->p_sys->p_display = XOpenDisplay( psz_display );
237
238     if( p_vout->p_sys->p_display == NULL )                          /* error */
239     {
240         intf_ErrMsg( "vout error: cannot open display %s", psz_display );
241         free( p_vout->p_sys );
242         return( 1 );
243     }
244     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
245
246     p_vout->b_fullscreen
247         = main_GetIntVariable( VOUT_FULLSCREEN_VAR, VOUT_FULLSCREEN_DEFAULT );
248     
249     if( !XVideoCheckForXv( p_vout->p_sys->p_display ) )
250     {
251         intf_ErrMsg( "vout error: no XVideo extension" );
252         XCloseDisplay( p_vout->p_sys->p_display );
253         free( p_vout->p_sys );
254         return( 1 );
255     }
256
257     /* Spawn base window - this window will include the video output window,
258      * but also command buttons, subtitles and other indicators */
259     if( XVideoCreateWindow( p_vout ) )
260     {
261         intf_ErrMsg( "vout error: cannot create XVideo window" );
262         XCloseDisplay( p_vout->p_sys->p_display );
263         free( p_vout->p_sys );
264         return( 1 );
265     }
266
267     if( (p_vout->p_sys->xv_port = XVideoGetPort( p_vout->p_sys->p_display ))<0 )
268         return 1;
269     intf_DbgMsg( "Using xv port %d" , p_vout->p_sys->xv_port );
270
271 #if 0
272     /* XXX The brightness and contrast values should be read from environment
273      * XXX variables... */
274     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
275     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
276 #endif
277
278     p_vout->p_sys->b_mouse_pointer_visible = 1;
279
280     /* Disable screen saver and return */
281     XVideoDisableScreenSaver( p_vout );
282
283     return( 0 );
284 }
285
286 /*****************************************************************************
287  * vout_Init: initialize XVideo video thread output method
288  *****************************************************************************/
289 static int vout_Init( vout_thread_t *p_vout )
290 {
291 #ifdef SYS_DARWIN
292     /* FIXME : As of 2001-03-16, XFree4 for MacOS X does not support Xshm. */
293     p_vout->p_sys->b_shm = 0;
294 #endif
295     p_vout->b_need_render = 0;
296     p_vout->p_sys->i_image_width = p_vout->p_sys->i_image_height = 0;
297
298     return( 0 );
299 }
300
301 /*****************************************************************************
302  * vout_End: terminate XVideo video thread output method
303  *****************************************************************************
304  * Destroy the XvImage. It is called at the end of the thread, but also each
305  * time the image is resized.
306  *****************************************************************************/
307 static void vout_End( vout_thread_t *p_vout )
308 {
309     XVideoDestroyShmImage( p_vout, p_vout->p_sys->p_xvimage,
310                            &p_vout->p_sys->shm_info );
311 }
312
313 /*****************************************************************************
314  * vout_Destroy: destroy XVideo video thread output method
315  *****************************************************************************
316  * Terminate an output method created by vout_Create
317  *****************************************************************************/
318 static void vout_Destroy( vout_thread_t *p_vout )
319 {
320     XVideoEnableScreenSaver( p_vout );
321     XVideoDestroyWindow( p_vout );
322     XCloseDisplay( p_vout->p_sys->p_display );
323
324     /* Destroy structure */
325     free( p_vout->p_sys );
326 }
327
328 /*****************************************************************************
329  * vout_Manage: handle X11 events
330  *****************************************************************************
331  * This function should be called regularly by video output thread. It manages
332  * X11 events and allows window resizing. It returns a non null value on
333  * error.
334  *
335  * XXX  Should "factor-out" common code in this and the "same" fn in the x11
336  * XXX  plugin!
337  *****************************************************************************/
338 static int vout_Manage( vout_thread_t *p_vout )
339 {
340     XEvent      xevent;                                         /* X11 event */
341     char        i_key;                                    /* ISO Latin-1 key */
342     KeySym      x_key_symbol;
343
344     /* Handle X11 events: ConfigureNotify events are parsed to know if the
345      * output window's size changed, MapNotify and UnmapNotify to know if the
346      * window is mapped (and if the display is useful), and ClientMessages
347      * to intercept window destruction requests */
348     while( XCheckWindowEvent( p_vout->p_sys->p_display, p_vout->p_sys->window,
349                               StructureNotifyMask | KeyPressMask |
350                               ButtonPressMask | ButtonReleaseMask | 
351                               PointerMotionMask, &xevent )
352            == True )
353     {
354         /* ConfigureNotify event: prepare  */
355         if( (xevent.type == ConfigureNotify)
356             /*&& ((xevent.xconfigure.width != p_vout->p_sys->i_window_width)
357                 || (xevent.xconfigure.height != p_vout->p_sys->i_window_height))*/ )
358         {
359             /* Update dimensions */
360             p_vout->p_sys->i_window_width = xevent.xconfigure.width;
361             p_vout->p_sys->i_window_height = xevent.xconfigure.height;
362         }
363         /* MapNotify event: change window status and disable screen saver */
364         else if( xevent.type == MapNotify)
365         {
366             if( (p_vout != NULL) && !p_vout->b_active )
367             {
368                 XVideoDisableScreenSaver( p_vout );
369                 p_vout->b_active = 1;
370             }
371         }
372         /* UnmapNotify event: change window status and enable screen saver */
373         else if( xevent.type == UnmapNotify )
374         {
375             if( (p_vout != NULL) && p_vout->b_active )
376             {
377                 XVideoEnableScreenSaver( p_vout );
378                 p_vout->b_active = 0;
379             }
380         }
381         /* Keyboard event */
382         else if( xevent.type == KeyPress )
383         {
384             /* We may have keys like F1 trough F12, ESC ... */
385             x_key_symbol = XKeycodeToKeysym( p_vout->p_sys->p_display,
386                                              xevent.xkey.keycode, 0 );
387             switch( x_key_symbol )
388             {
389                  case XK_Escape:
390                      p_main->p_intf->b_die = 1;
391                      break;
392                  case XK_Menu:
393                      p_main->p_intf->b_menu_change = 1;
394                      break;
395                  default:
396                      /* "Normal Keys"
397                       * The reason why I use this instead of XK_0 is that 
398                       * with XLookupString, we don't have to care about
399                       * keymaps. */
400
401                     if( XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
402                     {
403                         switch( i_key )
404                         {
405                         case 'q':
406                         case 'Q':
407                             p_main->p_intf->b_die = 1;
408                             break;
409                         case 'f':
410                         case 'F':
411                             p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
412                             break;
413                         case '0':
414                             network_ChannelJoin( 0 );
415                             break;
416                         case '1':
417                             network_ChannelJoin( 1 );
418                             break;
419                         case '2':
420                             network_ChannelJoin( 2 );
421                             break;
422                         case '3':
423                             network_ChannelJoin( 3 );
424                             break;
425                         case '4':
426                             network_ChannelJoin( 4 );
427                             break;
428                         case '5':
429                             network_ChannelJoin( 5 );
430                             break;
431                         case '6':
432                             network_ChannelJoin( 6 );
433                             break;
434                         case '7':
435                             network_ChannelJoin( 7 );
436                             break;
437                         case '8':
438                             network_ChannelJoin( 8 );
439                             break;
440                         case '9':
441                             network_ChannelJoin( 9 );
442                             break;
443                         default:
444                             if( intf_ProcessKey( p_main->p_intf, 
445                                                  (char )i_key ) )
446                             {
447                                intf_DbgMsg( "unhandled key '%c' (%i)", 
448                                             (char)i_key, i_key );
449                             }
450                             break;
451                         }
452                     }
453                 break;
454             }
455         }
456         /* Mouse click */
457         else if( xevent.type == ButtonPress )
458         {
459             switch( ((XButtonEvent *)&xevent)->button )
460             {
461                 case Button1:
462                     /* in this part we will eventually manage
463                      * clicks for DVD navigation for instance */
464                     break;
465             }
466         }
467         /* Mouse release */
468         else if( xevent.type == ButtonRelease )
469         {
470             switch( ((XButtonEvent *)&xevent)->button )
471             {
472                 case Button3:
473                     /* FIXME: need locking ! */
474                     p_main->p_intf->b_menu_change = 1;
475                     break;
476             }
477         }
478         /* Mouse move */
479         else if( xevent.type == MotionNotify )
480         {
481             p_vout->p_sys->i_time_mouse_last_moved = mdate();
482             p_vout->p_sys->b_mouse_pointer_visible = 1; 
483             XVideoSetMousePointer( p_vout ); 
484         }
485         /* Other event */
486         else
487         {
488             intf_WarnMsg( 3, "%p -> unhandled event type %d received",
489                          p_vout, xevent.type );
490         }
491     }
492
493     /* Handle events for YUV video output sub-window */
494     while( XCheckWindowEvent( p_vout->p_sys->p_display,
495                               p_vout->p_sys->yuv_window,
496                               ExposureMask, &xevent ) == True )
497     {
498         /* Window exposed (only handled if stream playback is paused) */
499         if( xevent.type == Expose )
500         {
501             if( ((XExposeEvent *)&xevent)->count == 0 )
502                 /* (if this is the last a collection of expose events...) */
503                 if( p_main->p_intf->p_input )
504                     if( PAUSE_S ==
505                             p_main->p_intf->p_input->stream.control.i_status )
506                         XVideoDisplay( p_vout );
507         }
508     }
509         
510     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
511      * are handled - according to the man pages, the format is always 32
512      * in this case */
513     while( XCheckTypedEvent( p_vout->p_sys->p_display,
514                              ClientMessage, &xevent ) )
515     {
516         if( (xevent.xclient.message_type == p_vout->p_sys->wm_protocols)
517             && (xevent.xclient.data.l[0] == p_vout->p_sys->wm_delete_window ) )
518         {
519             p_main->p_intf->b_die = 1;
520         }
521         else
522         {
523             intf_DbgMsg( "%p -> unhandled ClientMessage received", p_vout );
524         }
525     }
526
527     if ( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
528     {
529         intf_DbgMsg( "vout: changing full-screen status" );
530
531         p_vout->b_fullscreen = !p_vout->b_fullscreen;
532
533         /* Get rid of the old window */
534         XVideoDestroyWindow( p_vout );
535
536         /* And create a new one */
537         if( XVideoCreateWindow( p_vout ) )
538         {
539             intf_ErrMsg( "vout error: cannot create X11 window" );
540             XCloseDisplay( p_vout->p_sys->p_display );
541
542             free( p_vout->p_sys );
543             return( 1 );
544         }
545     }
546
547     
548     if( (p_vout->i_changes & VOUT_GRAYSCALE_CHANGE))
549     {
550         /* FIXME: clear flags ?? */
551     }
552
553     /*
554      * Size change
555      */
556     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
557     {
558         intf_DbgMsg( "vout: resizing window" );
559         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
560         /* Nothing to do here...
561          * vout_Display() detects size changes of the image to be displayed and
562          * re-creates the XvImage.*/
563         intf_Msg( "vout: video display resized (%dx%d)",
564                   p_vout->i_width, p_vout->i_height );
565     }
566
567     /* Autohide Cursor */
568     if( p_vout->p_sys->b_mouse_pointer_visible &&
569         mdate() - p_vout->p_sys->i_time_mouse_last_moved > 2000000 )
570     {
571         p_vout->p_sys->b_mouse_pointer_visible = 0; 
572         XVideoSetMousePointer( p_vout );
573     }
574     
575     return 0;
576 }
577
578 /*****************************************************************************
579  * vout_Display: displays previously rendered output
580  *****************************************************************************
581  * This function sends the currently rendered image to X11 server.
582  * (The Xv extension takes care of "double-buffering".)
583  *****************************************************************************/
584 static void vout_Display( vout_thread_t *p_vout )
585 {
586     boolean_t b_draw = 1;
587     int i_size = p_vout->p_rendered_pic->i_width *
588                    p_vout->p_rendered_pic->i_height;
589
590     if( XVideoUpdateImgSizeIfRequired( p_vout ) )
591     {
592         return;
593     }
594
595     switch( p_vout->p_rendered_pic->i_type )
596     {
597     case YUV_422_PICTURE:
598         intf_ErrMsg( "vout error: YUV_422_PICTURE not (yet) supported" );
599         b_draw = 0;
600         break;
601
602     case YUV_444_PICTURE:
603         intf_ErrMsg( "vout error: YUV_444_PICTURE not (yet) supported" );
604         b_draw = 0;
605         break;
606
607     case YUV_420_PICTURE:
608         memcpy( p_vout->p_sys->p_xvimage->data,
609                 p_vout->p_rendered_pic->p_y, i_size );
610         memcpy( p_vout->p_sys->p_xvimage->data + ( i_size ),
611                 p_vout->p_rendered_pic->p_v, i_size / 4 );
612         memcpy( p_vout->p_sys->p_xvimage->data + ( i_size ) + ( i_size / 4 ),
613                 p_vout->p_rendered_pic->p_u, i_size / 4 );
614         break;
615     }
616
617     if( b_draw )
618     {
619         XVideoDisplay( p_vout );
620     }
621 }
622
623 static void vout_SetPalette( p_vout_thread_t p_vout,
624                              u16 *red, u16 *green, u16 *blue, u16 *transp )
625 {
626     return;
627 }
628
629 /* following functions are local */
630
631 /*****************************************************************************
632  * XVideoUpdateImgSizeIfRequired 
633  *****************************************************************************
634  * This function checks to see if the image to be displayed is of a different
635  * size to the last image displayed. If so, the old shm block must be
636  * destroyed and a new one created.
637  * Note: the "image size" is the size of the image to be passed to the Xv
638  * extension (which is probably different to the size of the output window).
639  *****************************************************************************/
640 static int XVideoUpdateImgSizeIfRequired( vout_thread_t *p_vout )
641 {
642     int i_img_width         = p_vout->p_rendered_pic->i_width;
643     int i_img_height        = p_vout->p_rendered_pic->i_height;
644
645     if( p_vout->p_sys->i_image_width != i_img_width
646             || p_vout->p_sys->i_image_height != i_img_height )
647     {
648         if( p_vout->p_sys->i_image_width != 0
649              && p_vout->p_sys->i_image_height != 0 )
650         {
651             /* Destroy XvImage to change its size */
652             vout_End( p_vout );
653         }
654
655         p_vout->p_sys->i_image_width  = i_img_width;
656         p_vout->p_sys->i_image_height = i_img_height;
657
658         /* Create XvImage using XShm extension */
659         if( XVideoCreateShmImage( p_vout->p_sys->p_display,
660                                   p_vout->p_sys->xv_port,
661                                   &p_vout->p_sys->p_xvimage,
662                                   &p_vout->p_sys->shm_info,
663                                   i_img_width, i_img_height ) )
664         {
665             intf_ErrMsg( "vout: failed to create xvimage." );
666             p_vout->p_sys->i_image_width = 0;
667             return( 1 );
668         }
669
670         /* Set bytes per line and initialize buffers */
671         p_vout->i_bytes_per_line =
672             (p_vout->p_sys->p_xvimage->data_size) /
673             (p_vout->p_sys->p_xvimage->height);
674
675         /* p_vout->pf_setbuffers( p_vout, p_vout->p_sys->p_xvimage->data ); */
676     }
677
678     return( 0 );
679 }
680
681 /*****************************************************************************
682  * XVideoCheckForXv: check for the XVideo extension
683  *****************************************************************************/
684 static int XVideoCheckForXv( Display *dpy )
685 {
686     unsigned int i;
687
688     switch( XvQueryExtension( dpy, &i, &i, &i, &i, &i ) )
689     {
690         case Success:
691             return( 1 );
692
693         case XvBadExtension:
694             intf_ErrMsg( "vout error: XvBadExtension" );
695             return( 0 );
696
697         case XvBadAlloc:
698             intf_ErrMsg( "vout error: XvBadAlloc" );
699             return( 0 );
700
701         default:
702             intf_ErrMsg( "vout error: XvQueryExtension failed" );
703             return( 0 );
704     }
705 }
706
707 /*****************************************************************************
708  * XVideoCreateWindow: open and set-up XVideo main window
709  *****************************************************************************/
710 static int XVideoCreateWindow( vout_thread_t *p_vout )
711 {
712     XSizeHints              xsize_hints;
713     XSetWindowAttributes    xwindow_attributes;
714     XGCValues               xgcvalues;
715     XEvent                  xevent;
716     Atom                    prop;
717     mwmhints_t              mwmhints;
718     
719     boolean_t               b_expose;
720     boolean_t               b_configure_notify;
721     boolean_t               b_map_notify;
722
723
724     /* Set main window's size */
725     /* If we're full screen, we're full screen! */
726     if( p_vout->b_fullscreen )
727     {
728         p_vout->p_sys->i_window_width = DisplayWidth( p_vout->p_sys->p_display,
729                                                       p_vout->p_sys->i_screen );
730         p_vout->p_sys->i_window_height =  DisplayHeight( p_vout->p_sys->p_display,
731                                                          p_vout->p_sys->i_screen );
732 /*      p_vout->i_width =  p_vout->p_sys->i_window_width;
733         p_vout->i_height = p_vout->p_sys->i_window_height; */
734     }
735     else
736     {
737         p_vout->p_sys->i_window_width =  main_GetIntVariable( VOUT_WIDTH_VAR,
738                                                        VOUT_WIDTH_DEFAULT );
739         p_vout->p_sys->i_window_height = main_GetIntVariable( VOUT_HEIGHT_VAR,
740                                                        VOUT_HEIGHT_DEFAULT );
741     }
742
743     /* Prepare window manager hints and properties */
744     xsize_hints.base_width          = p_vout->p_sys->i_window_width;
745     xsize_hints.base_height         = p_vout->p_sys->i_window_height;
746     xsize_hints.flags               = PSize;
747     p_vout->p_sys->wm_protocols     = XInternAtom( p_vout->p_sys->p_display,
748                                                    "WM_PROTOCOLS", True );
749     p_vout->p_sys->wm_delete_window = XInternAtom( p_vout->p_sys->p_display,
750                                                    "WM_DELETE_WINDOW", True );
751
752     /* Prepare window attributes */
753     xwindow_attributes.background_pixel = BlackPixel( p_vout->p_sys->p_display,
754                                                       p_vout->p_sys->i_screen );
755
756     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
757
758     /* Create the window and set hints - the window must receive ConfigureNotify
759      * events, and, until it is displayed, Expose and MapNotify events. */
760     p_vout->p_sys->window =
761             XCreateWindow( p_vout->p_sys->p_display,
762                            DefaultRootWindow( p_vout->p_sys->p_display ),
763                            0, 0,
764                            p_vout->p_sys->i_window_width,
765                            p_vout->p_sys->i_window_height, 1,
766                            0, InputOutput, 0,
767                            CWBackPixel | CWEventMask,
768                            &xwindow_attributes );
769
770     if ( p_vout->b_fullscreen )
771     {
772         prop = XInternAtom(p_vout->p_sys->p_display, "_MOTIF_WM_HINTS", False);
773         mwmhints.flags = MWM_HINTS_DECORATIONS;
774         mwmhints.decorations = 0;
775         XChangeProperty( p_vout->p_sys->p_display, p_vout->p_sys->window,
776                          prop, prop, 32, PropModeReplace,
777                          (unsigned char *)&mwmhints, PROP_MWM_HINTS_ELEMENTS );
778
779         XSetTransientForHint( p_vout->p_sys->p_display,
780                               p_vout->p_sys->window, None );
781         XRaiseWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
782     }
783
784     
785     /* Set window manager hints and properties: size hints, command,
786      * window's name, and accepted protocols */
787     XSetWMNormalHints( p_vout->p_sys->p_display, p_vout->p_sys->window,
788                        &xsize_hints );
789     XSetCommand( p_vout->p_sys->p_display, p_vout->p_sys->window,
790                  p_main->ppsz_argv, p_main->i_argc );
791     XStoreName( p_vout->p_sys->p_display, p_vout->p_sys->window,
792                 VOUT_TITLE " (XVideo output)" );
793
794     if( (p_vout->p_sys->wm_protocols == None)        /* use WM_DELETE_WINDOW */
795         || (p_vout->p_sys->wm_delete_window == None)
796         || !XSetWMProtocols( p_vout->p_sys->p_display, p_vout->p_sys->window,
797                              &p_vout->p_sys->wm_delete_window, 1 ) )
798     {
799         /* WM_DELETE_WINDOW is not supported by window manager */
800         intf_Msg( "vout error: missing or bad window manager" );
801     }
802
803     /* Creation of a graphic context that doesn't generate a GraphicsExpose
804      * event when using functions like XCopyArea */
805     xgcvalues.graphics_exposures = False;
806     p_vout->p_sys->gc = XCreateGC( p_vout->p_sys->p_display,
807                                    p_vout->p_sys->window,
808                                    GCGraphicsExposures, &xgcvalues);
809
810     /* Send orders to server, and wait until window is displayed - three
811      * events must be received: a MapNotify event, an Expose event allowing
812      * drawing in the window, and a ConfigureNotify to get the window
813      * dimensions. Once those events have been received, only ConfigureNotify
814      * events need to be received. */
815     b_expose = 0;
816     b_configure_notify = 0;
817     b_map_notify = 0;
818     XMapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window);
819     do
820     {
821         XNextEvent( p_vout->p_sys->p_display, &xevent);
822         if( (xevent.type == Expose)
823             && (xevent.xexpose.window == p_vout->p_sys->window) )
824         {
825             b_expose = 1;
826         }
827         else if( (xevent.type == MapNotify)
828                  && (xevent.xmap.window == p_vout->p_sys->window) )
829         {
830             b_map_notify = 1;
831         }
832         else if( (xevent.type == ConfigureNotify)
833                  && (xevent.xconfigure.window == p_vout->p_sys->window) )
834         {
835             b_configure_notify = 1;
836             p_vout->p_sys->i_window_width = xevent.xconfigure.width;
837             p_vout->p_sys->i_window_height = xevent.xconfigure.height;
838         }
839     } while( !( b_expose && b_configure_notify && b_map_notify ) );
840
841     XSelectInput( p_vout->p_sys->p_display, p_vout->p_sys->window,
842                   StructureNotifyMask | KeyPressMask |
843                   ButtonPressMask | ButtonReleaseMask | 
844                   PointerMotionMask );
845
846     if( p_vout->b_fullscreen )
847     {
848         XSetInputFocus( p_vout->p_sys->p_display, p_vout->p_sys->window,
849                         RevertToNone, CurrentTime );
850         XMoveWindow( p_vout->p_sys->p_display, p_vout->p_sys->window, 0, 0 );
851     }
852
853     /* Create YUV output sub-window. */
854     p_vout->p_sys->yuv_window=XCreateSimpleWindow( p_vout->p_sys->p_display,
855                          p_vout->p_sys->window, 0, 0, 1, 1, 0,
856                          BlackPixel( p_vout->p_sys->p_display,
857                                          p_vout->p_sys->i_screen ),
858                          WhitePixel( p_vout->p_sys->p_display,
859                                          p_vout->p_sys->i_screen ) );
860  
861     p_vout->p_sys->yuv_gc = XCreateGC( p_vout->p_sys->p_display,
862                                         p_vout->p_sys->yuv_window,
863                                         GCGraphicsExposures, &xgcvalues );
864
865     XSetWindowBackground( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
866              BlackPixel(p_vout->p_sys->p_display, p_vout->p_sys->i_screen ) );
867
868     XMapWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window );
869     XSelectInput( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
870                   ExposureMask );
871
872
873     XVideoSetMousePointer( p_vout );
874
875     return( 0 );
876 }
877
878 static void XVideoDestroyWindow( vout_thread_t *p_vout )
879 {
880     XFreeGC( p_vout->p_sys->p_display, p_vout->p_sys->yuv_gc );
881     XDestroyWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window );
882
883     XUnmapWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
884     XFreeGC( p_vout->p_sys->p_display, p_vout->p_sys->gc );
885     XDestroyWindow( p_vout->p_sys->p_display, p_vout->p_sys->window );
886 }
887
888 /*****************************************************************************
889  * XVideoCreateShmImage: create an XvImage using shared memory extension
890  *****************************************************************************
891  * Prepare an XvImage for display function.
892  * The order of the operations respects the recommandations of the mit-shm
893  * document by J.Corbet and K.Packard. Most of the parameters were copied from
894  * there.
895  *****************************************************************************/
896 static int XVideoCreateShmImage( Display* dpy, int xv_port,
897                                     XvImage **pp_xvimage,
898                                     XShmSegmentInfo *p_shm_info,
899                                     int i_width, int i_height )
900 {
901     *pp_xvimage = XvShmCreateImage( dpy, xv_port,
902                                     GUID_YUV12_PLANAR, 0,
903                                     i_width, i_height,
904                                     p_shm_info );
905     if( !(*pp_xvimage) )
906     {
907         intf_ErrMsg( "vout error: XvShmCreateImage failed." );
908         return( -1 );
909     }
910
911     p_shm_info->shmid    = shmget( IPC_PRIVATE, (*pp_xvimage)->data_size,
912                                    IPC_CREAT | 0777 );
913     if( p_shm_info->shmid < 0)                                      /* error */
914     {
915         intf_ErrMsg( "vout error: cannot allocate shared image data (%s)",
916                     strerror(errno));
917         return( 1 );
918     }
919
920     p_shm_info->shmaddr  = (*pp_xvimage)->data = shmat( p_shm_info->shmid,
921                                                         0, 0 );
922     p_shm_info->readOnly = False;
923
924 #if 0
925     /* Mark the shm segment to be removed when there will be no more
926      * attachements, so it is automatic on process exit or after shmdt */
927     shmctl( p_shm_info->shmid, IPC_RMID, 0 );
928 #endif
929
930     if( !XShmAttach( dpy, p_shm_info ) )
931     {
932         intf_ErrMsg( "vout error: XShmAttach failed" );
933         shmctl( p_shm_info->shmid, IPC_RMID, 0 );
934         shmdt( p_shm_info->shmaddr );
935         return( -1 );
936     }
937
938     /* Send image to X server. This instruction is required, since having
939      * built a Shm XImage and not using it causes an error on XCloseDisplay */
940     XFlush( dpy );
941
942     return( 0 );
943 }
944
945 /*****************************************************************************
946  * XVideoDestroyShmImage
947  *****************************************************************************
948  * Destroy XImage AND associated data. Detach shared memory segment from
949  * server and process, then free it. If pointer is NULL, the image won't be
950  * destroyed (see vout_ManageOutputMethod())
951  *****************************************************************************/
952 static void XVideoDestroyShmImage( vout_thread_t *p_vout, XvImage *p_xvimage,
953                                    XShmSegmentInfo *p_shm_info )
954 {
955     /* If pointer is NULL, do nothing */
956     if( p_xvimage == NULL )
957     {
958         return;
959     }
960
961     XShmDetach( p_vout->p_sys->p_display, p_shm_info );/* detach from server */
962 #if 0
963     XDestroyImage( p_ximage ); /* XXX */
964 #endif
965
966     shmctl( p_shm_info->shmid, IPC_RMID, 0 );
967
968     if( shmdt( p_shm_info->shmaddr ) )  /* detach shared memory from process */
969     {
970         intf_ErrMsg( "vout error: cannot detach shared memory (%s)",
971                      strerror(errno) );
972     }
973 }
974
975 /*****************************************************************************
976  * XVideoEnableScreenSaver: enable screen saver
977  *****************************************************************************
978  * This function enable the screen saver on a display after it had been
979  * disabled by XDisableScreenSaver. Both functions use a counter mechanism to
980  * know wether the screen saver can be activated or not: if n successive calls
981  * are made to XDisableScreenSaver, n successive calls to XEnableScreenSaver
982  * will be required before the screen saver could effectively be activated.
983  *****************************************************************************/
984 void XVideoEnableScreenSaver( vout_thread_t *p_vout )
985 {
986     intf_DbgMsg( "intf: enabling screen saver" );
987     XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
988                      p_vout->p_sys->i_ss_interval,
989                      p_vout->p_sys->i_ss_blanking,
990                      p_vout->p_sys->i_ss_exposure );
991 }
992
993 /*****************************************************************************
994  * XVideoDisableScreenSaver: disable screen saver
995  *****************************************************************************
996  * See XEnableScreenSaver
997  *****************************************************************************/
998 void XVideoDisableScreenSaver( vout_thread_t *p_vout )
999 {
1000     /* Save screen saver informations */
1001     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
1002                      &p_vout->p_sys->i_ss_interval,
1003                      &p_vout->p_sys->i_ss_blanking,
1004                      &p_vout->p_sys->i_ss_exposure );
1005
1006     /* Disable screen saver */
1007     intf_DbgMsg( "intf: disabling screen saver" );
1008     XSetScreenSaver( p_vout->p_sys->p_display, 0,
1009                      p_vout->p_sys->i_ss_interval,
1010                      p_vout->p_sys->i_ss_blanking,
1011                      p_vout->p_sys->i_ss_exposure );
1012 }
1013
1014 /*****************************************************************************
1015  * XVideoSetMousePointer: hide or show the mouse pointer
1016  *****************************************************************************
1017  * This function hides the X pointer if requested.
1018  *****************************************************************************/
1019 void XVideoSetMousePointer( const vout_thread_t *p_vout )
1020 {
1021     static Cursor blank_cursor;
1022     static boolean_t b_created_blank_cursor = 0;
1023
1024     if( !p_vout->p_sys->b_mouse_pointer_visible )
1025     {
1026         if( !b_created_blank_cursor )
1027         {
1028             XColor color;
1029             Pixmap blank = XCreatePixmap( p_vout->p_sys->p_display,
1030                                DefaultRootWindow(p_vout->p_sys->p_display),
1031                                1, 1, 1 );
1032
1033             XParseColor( p_vout->p_sys->p_display,
1034                          XCreateColormap( p_vout->p_sys->p_display,
1035                                           DefaultRootWindow(
1036                                                   p_vout->p_sys->p_display ),
1037                                           DefaultVisual(
1038                                                   p_vout->p_sys->p_display,
1039                                                   p_vout->p_sys->i_screen ),
1040                                           AllocNone ),
1041                          "black", &color );
1042
1043             blank_cursor = XCreatePixmapCursor( p_vout->p_sys->p_display,
1044                            blank, blank, &color, &color, 1, 1 );
1045
1046             b_created_blank_cursor = 1;
1047         }
1048         XDefineCursor( p_vout->p_sys->p_display,
1049                        p_vout->p_sys->window, blank_cursor );
1050     }
1051     else
1052     {
1053         XUndefineCursor( p_vout->p_sys->p_display, p_vout->p_sys->window );
1054     }
1055 }
1056
1057 /* This based on some code in SetBufferPicture... At the moment it's only
1058  * used by the xvideo plugin, but others may want to use it. */
1059 static void XVideoOutputCoords( const picture_t *p_pic, const boolean_t scale,
1060                                 const int win_w, const int win_h,
1061                                 int *dx, int *dy, int *w, int *h)
1062 {
1063     if( !scale )
1064     {
1065         *w = p_pic->i_width; *h = p_pic->i_height;
1066     }
1067     else
1068     {
1069         *w = win_w;
1070         switch( p_pic->i_aspect_ratio )
1071         {
1072             case AR_3_4_PICTURE:
1073                 *h = win_w * 3 / 4;
1074                 break;
1075
1076             case AR_16_9_PICTURE:
1077                 *h = win_w * 9 / 16;
1078                 break;
1079
1080             case AR_221_1_PICTURE:
1081                 *h = win_w * 100 / 221;
1082                 break;
1083
1084             case AR_SQUARE_PICTURE:
1085             default:
1086                 *h = win_w * p_pic->i_height / p_pic->i_width;
1087                 break;
1088         }
1089
1090         if( *h > win_h )
1091         {
1092             *h = win_h;
1093             switch( p_pic->i_aspect_ratio )
1094             {
1095                 case AR_3_4_PICTURE:
1096                     *w = win_h * 4 / 3;
1097                     break;
1098
1099                 case AR_16_9_PICTURE:
1100                     *w = win_h * 16 / 9;
1101                     break;
1102
1103                 case AR_221_1_PICTURE:
1104                     *w = win_h * 221 / 100;
1105                     break;
1106
1107                 case AR_SQUARE_PICTURE:
1108                 default:
1109                     *w = win_h * p_pic->i_width / p_pic->i_height;
1110                     break;
1111             }
1112         }
1113     }
1114
1115     /* Set picture position */
1116     *dx = (win_w - *w) / 2;
1117     *dy = (win_h - *h) / 2;
1118 }
1119
1120
1121 static int XVideoGetPort( Display *dpy )
1122 {
1123     int            i, i_adaptors;
1124     int            xv_port = -1;
1125     XvAdaptorInfo *adaptor_info;
1126
1127     switch( XvQueryAdaptors( dpy, DefaultRootWindow( dpy ),
1128                              &i_adaptors, &adaptor_info ) )
1129     {
1130         case Success:
1131             break;
1132
1133         case XvBadExtension:
1134             intf_ErrMsg( "vout error: XvBadExtension for XvQueryAdaptors" );
1135             return( -1 );
1136
1137         case XvBadAlloc:
1138             intf_ErrMsg( "vout error: XvBadAlloc for XvQueryAdaptors" );
1139             return( -1 );
1140
1141         default:
1142             intf_ErrMsg( "vout error: XvQueryAdaptors failed" );
1143             return( -1 );
1144     }
1145
1146     for( i=0; i < i_adaptors && xv_port == -1; ++i )
1147         if( ( adaptor_info[ i ].type & XvInputMask ) &&
1148             ( adaptor_info[ i ].type & XvImageMask ) )
1149         {
1150             /* check that port supports YUV12 planar format... */
1151             int port = adaptor_info[ i ].base_id;
1152             int i_num_formats, i;
1153             XvImageFormatValues *imageFormats;
1154
1155             imageFormats = XvListImageFormats( dpy, port, &i_num_formats );
1156
1157             for( i=0; i < i_num_formats && xv_port == -1; ++i )
1158                 if( imageFormats[ i ].id == GUID_YUV12_PLANAR )
1159                     xv_port = port;
1160
1161             if( xv_port == -1 )
1162                 intf_WarnMsg( 3, "vout: XVideo image input port %d "
1163                         "does not support the YUV12 planar format which is "
1164                         "currently required by the xvideo output plugin.",
1165                         port );
1166
1167             if( imageFormats )
1168                 XFree( imageFormats );
1169         }
1170
1171     if( i_adaptors > 0 )
1172         XvFreeAdaptorInfo(adaptor_info);
1173
1174     if( xv_port == -1 )
1175         intf_ErrMsg( "vout error: didn't find a suitable Xvideo image input port." );
1176
1177     return( xv_port );
1178 }
1179
1180
1181 /*****************************************************************************
1182  * XVideoDisplay: display image
1183  *****************************************************************************
1184  * This function displays the image stored in p_vout->p_sys->p_xvimage.
1185  * The image is scaled to fit in the output window (and to have the correct
1186  * aspect ratio).
1187  *****************************************************************************/
1188 static void XVideoDisplay( vout_thread_t *p_vout )
1189 {
1190     int     i_dest_width, i_dest_height, i_dest_x, i_dest_y;
1191
1192     if( !p_vout->p_sys->p_xvimage ) return;
1193
1194     XVideoOutputCoords( p_vout->p_rendered_pic, p_vout->b_scale,
1195                         p_vout->p_sys->i_window_width,
1196                         p_vout->p_sys->i_window_height,
1197                         &i_dest_x, &i_dest_y,
1198                         &i_dest_width, &i_dest_height);
1199
1200     XvShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->xv_port,
1201                    p_vout->p_sys->yuv_window, p_vout->p_sys->gc,
1202                    p_vout->p_sys->p_xvimage,
1203                    0 /*src_x*/, 0 /*src_y*/,
1204                    p_vout->p_rendered_pic->i_width,
1205                    p_vout->p_rendered_pic->i_height,
1206                    0 /*dest_x*/, 0 /*dest_y*/, i_dest_width, i_dest_height,
1207                    True );
1208
1209      XResizeWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
1210              i_dest_width, i_dest_height );
1211      XMoveWindow( p_vout->p_sys->p_display, p_vout->p_sys->yuv_window,
1212              i_dest_x, i_dest_y );
1213 }
1214
1215 #if 0
1216 /*****************************************************************************
1217  * XVideoSetAttribute
1218  *****************************************************************************
1219  * This function can be used to set attributes, e.g. XV_BRIGHTNESS and
1220  * XV_CONTRAST. "f_value" should be in the range of 0 to 1.
1221  *****************************************************************************/
1222 static void XVideoSetAttribute( vout_thread_t *p_vout,
1223                                 char *attr_name, float f_value )
1224 {
1225     int             i_attrib;
1226     XvAttribute    *p_attrib;
1227     Display        *p_dpy   = p_vout->p_sys->p_display;
1228     int             xv_port = p_vout->p_sys->xv_port;
1229
1230     p_attrib = XvQueryPortAttributes( p_dpy, xv_port, &i_attrib );
1231
1232     do
1233     {
1234         i_attrib--;
1235
1236         if( i_attrib >= 0 && !strcmp( p_attrib[ i_attrib ].name, attr_name ) )
1237         {
1238             int i_sv = f_value * ( p_attrib[ i_attrib ].max_value
1239                                     - p_attrib[ i_attrib ].min_value + 1 )
1240                         + p_attrib[ i_attrib ].min_value;
1241
1242             XvSetPortAttribute( p_dpy, xv_port,
1243                             XInternAtom( p_dpy, attr_name, False ), i_sv );
1244             break;
1245         }
1246
1247     } while( i_attrib > 0 );
1248
1249     if( p_attrib )
1250         XFree( p_attrib );
1251 }
1252 #endif