]> git.sesse.net Git - vlc/blob - modules/video_output/xcb/x11.c
XCB: select X11 visual from pixmap, not from root depth
[vlc] / modules / video_output / xcb / x11.c
1 /**
2  * @file x11.c
3  * @brief X C Bindings video output module for VLC media player
4  */
5 /*****************************************************************************
6  * Copyright © 2009 Rémi Denis-Courmont
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2.0
11  * of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  ****************************************************************************/
22
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26
27 #include <stdlib.h>
28 #include <assert.h>
29
30 #include <sys/types.h>
31 #include <sys/shm.h>
32
33 #include <xcb/xcb.h>
34 #include <xcb/shm.h>
35
36 #include <xcb/xcb_aux.h>
37 #include <xcb/xcb_image.h>
38
39 #include <vlc_common.h>
40 #include <vlc_plugin.h>
41 #include <vlc_vout.h>
42 #include <vlc_window.h>
43
44 #include "xcb_vlc.h"
45
46 #define DISPLAY_TEXT N_("X11 display")
47 #define DISPLAY_LONGTEXT N_( \
48     "X11 hardware display to use. By default VLC will " \
49     "use the value of the DISPLAY environment variable.")
50
51 #define SHM_TEXT N_("Use shared memory")
52 #define SHM_LONGTEXT N_( \
53     "Use shared memory to communicate between VLC and the X server.")
54
55 static int  Open (vlc_object_t *);
56 static void Close (vlc_object_t *);
57
58 /*
59  * Module descriptor
60  */
61 vlc_module_begin ()
62     set_shortname (N_("XCB"))
63     set_description (N_("(Experimental) XCB video output"))
64     set_category (CAT_VIDEO)
65     set_subcategory (SUBCAT_VIDEO_VOUT)
66     set_capability ("video output", 0)
67     set_callbacks (Open, Close)
68
69     add_string ("x11-display", NULL, NULL,
70                 DISPLAY_TEXT, DISPLAY_LONGTEXT, true)
71     add_bool ("x11-shm", true, NULL, SHM_TEXT, SHM_LONGTEXT, true)
72 vlc_module_end ()
73
74 struct vout_sys_t
75 {
76     xcb_connection_t *conn;
77     xcb_screen_t *screen;
78     vout_window_t *embed; /* VLC window (when windowed) */
79
80     xcb_visualid_t vid; /* selected visual */
81     xcb_window_t parent; /* parent X window */
82     xcb_colormap_t cmap; /* colormap for selected visual */
83     xcb_window_t window; /* drawable X window */
84     xcb_gcontext_t gc; /* context to put images */
85     bool shm; /* whether to use MIT-SHM */
86     uint8_t bpp; /* bits per pixel */
87     uint8_t pad; /* scanline pad */
88 };
89
90 static int Init (vout_thread_t *);
91 static void Deinit (vout_thread_t *);
92 static void Render (vout_thread_t *, picture_t *);
93 static void Display (vout_thread_t *, picture_t *);
94 static int Manage (vout_thread_t *);
95
96 int CheckError (vout_thread_t *vout, const char *str, xcb_void_cookie_t ck)
97 {
98     xcb_generic_error_t *err;
99
100     err = xcb_request_check (vout->p_sys->conn, ck);
101     if (err)
102     {
103         msg_Err (vout, "%s: X11 error %d", str, err->error_code);
104         return VLC_EGENERIC;
105     }
106     return VLC_SUCCESS;
107 }
108
109 #define p_vout vout
110
111 /**
112  * Probe the X server.
113  */
114 static int Open (vlc_object_t *obj)
115 {
116     vout_thread_t *vout = (vout_thread_t *)obj;
117     vout_sys_t *p_sys = malloc (sizeof (*p_sys));
118     if (p_sys == NULL)
119         return VLC_ENOMEM;
120
121     vout->p_sys = p_sys;
122     p_sys->conn = NULL;
123     p_sys->embed = NULL;
124
125     /* Connect to X */
126     char *display = var_CreateGetNonEmptyString (vout, "x11-display");
127     int snum;
128     p_sys->conn = xcb_connect (display, &snum);
129     if (xcb_connection_has_error (p_sys->conn) /*== NULL*/)
130     {
131         msg_Err (vout, "cannot connect to X server %s",
132                  display ? display : "");
133         free (display);
134         goto error;
135     }
136     free (display);
137
138     const xcb_setup_t *setup = xcb_get_setup (p_sys->conn);
139
140     /* Get the preferred screen */
141     xcb_screen_t *scr = xcb_aux_get_screen (p_sys->conn, snum);
142     p_sys->screen = scr;
143     assert (p_sys->screen);
144     msg_Dbg (vout, "using screen %d", snum);
145
146     /* Determine our video format. Normally, this is done in pf_init(), but
147      * this plugin always uses the same format for a given X11 screen. */
148     uint8_t depth = 0;
149     bool gray = true;
150     for (const xcb_format_t *fmt = xcb_setup_pixmap_formats (setup),
151              *end = fmt + xcb_setup_pixmap_formats_length (setup);
152          fmt < end; fmt++)
153     {
154         vlc_fourcc_t chroma = 0;
155
156         if (fmt->depth < depth)
157             continue; /* We already found a better format! */
158
159         /* Check that the pixmap format is supported by VLC. */
160         switch (fmt->depth)
161         {
162           case 24:
163             if (fmt->bits_per_pixel == 32)
164                 chroma = VLC_FOURCC ('R', 'V', '3', '2');
165             else if (fmt->bits_per_pixel == 24)
166                 chroma = VLC_FOURCC ('R', 'V', '2', '4');
167             else
168                 continue;
169             break;
170           case 16:
171             if (fmt->bits_per_pixel != 16)
172                 continue;
173             chroma = VLC_FOURCC ('R', 'V', '1', '6');
174             break;
175           case 15:
176             if (fmt->bits_per_pixel != 16)
177                 continue;
178             chroma = VLC_FOURCC ('R', 'V', '1', '5');
179             break;
180           case 8:
181             if (fmt->bits_per_pixel != 8)
182                 continue;
183             chroma = VLC_FOURCC ('R', 'G', 'B', '2');
184             break;
185           default:
186             continue;
187         }
188         if ((fmt->bits_per_pixel << 4) % fmt->scanline_pad)
189             continue; /* VLC pads lines to 16 pixels internally */
190
191         /* Byte sex is a non-issue for 8-bits. It can be worked around with
192          * RGB masks for 24-bits. Too bad for 15-bits and 16-bits. */
193 #ifdef WORDS_BIGENDIAN
194 # define ORDER XCB_IMAGE_ORDER_MSB_FIRST
195 #else
196 # define ORDER XCB_IMAGE_ORDER_LSB_FIRST
197 #endif
198         if (fmt->bits_per_pixel == 16 && setup->image_byte_order != ORDER)
199             continue;
200
201         /* Check that the selected screen supports this depth */
202         xcb_depth_iterator_t it = xcb_screen_allowed_depths_iterator (scr);
203         while (it.rem > 0 && it.data->depth != fmt->depth)
204              xcb_depth_next (&it);
205         if (!it.rem)
206             continue; /* Depth not supported on this screen */
207
208         /* Find a visual type for the selected depth */
209         const xcb_visualtype_t *vt = xcb_depth_visuals (it.data);
210         xcb_visualid_t vid = 0;
211         for (int i = xcb_depth_visuals_length (it.data); (i > 0) && !vid; i--)
212         {
213             if (vt->_class == XCB_VISUAL_CLASS_TRUE_COLOR)
214             {
215                 msg_Dbg (vout,
216                          "using TrueColor %"PRIu8"-bits visual ID 0x%0"PRIx32,
217                          fmt->depth, vt->visual_id);
218                 vid = vt->visual_id;
219                 gray = false;
220                 break;
221             }
222             if (fmt->depth == 8 && vt->_class == XCB_VISUAL_CLASS_STATIC_GRAY)
223             {
224                 if (!gray)
225                     continue; /* Prefer color over gray scale */
226                 vid = vt->visual_id;
227                 chroma = VLC_FOURCC ('G', 'R', 'E', 'Y');
228                 msg_Dbg (vout,
229                          "using static gray 8-bits visual ID 0x%x"PRIx32,
230                          vt->visual_id);
231                 break;
232             }
233         }
234
235         if (!vid)
236             continue; /* The screen does not *really* support this depth */
237
238         vout->fmt_out.i_chroma = vout->output.i_chroma = chroma;
239         if (!gray)
240         {
241             vout->output.i_rmask = vt->red_mask;
242             vout->output.i_gmask = vt->green_mask;
243             vout->output.i_bmask = vt->blue_mask;
244         }
245         p_sys->vid = vid;
246         p_sys->bpp = fmt->bits_per_pixel;
247         p_sys->pad = fmt->scanline_pad;
248
249         depth = fmt->depth;
250     }
251
252     if (depth == 0)
253     {
254         msg_Err (vout, "no supported pixmap formats");
255         goto error;
256     }
257
258     msg_Dbg (vout, "using %"PRIu8" bits per pixels (line pad: %"PRIu8")",
259              p_sys->bpp, p_sys->pad);
260
261     /* Create colormap (needed to select non-default visual) */
262     p_sys->cmap = xcb_generate_id (p_sys->conn);
263     xcb_create_colormap (p_sys->conn, XCB_COLORMAP_ALLOC_NONE,
264                          p_sys->cmap, scr->root, p_sys->vid);
265
266     /* Check shared memory support */
267     p_sys->shm = var_CreateGetBool (vout, "x11-shm") > 0;
268     if (p_sys->shm)
269     {
270         xcb_shm_query_version_cookie_t ck;
271         xcb_shm_query_version_reply_t *r;
272         xcb_generic_error_t *err;
273
274         ck = xcb_shm_query_version (p_sys->conn);
275         r = xcb_shm_query_version_reply (p_sys->conn, ck, &err);
276         if (!r)
277         {
278             msg_Err (vout, "shared memory (MIT-SHM) not available");
279             msg_Warn (vout, "display will be slow");
280             p_sys->shm = false;
281         }
282     }
283
284     /* Get window */
285     /* FIXME: WTH to put as initial width/height values??? */
286     p_sys->embed = vout_RequestXWindow (vout, &(int){ 0 }, &(int){ 0 },
287                                         &(unsigned){ 0 }, &(unsigned){ 0 });
288     if (p_sys->embed == NULL)
289     {
290         msg_Err (vout, "parent window not available");
291         goto error;
292     }
293
294     vout->pf_init = Init;
295     vout->pf_end = Deinit;
296     vout->pf_render = Render;
297     vout->pf_display = Display;
298     vout->pf_manage = Manage;
299     return VLC_SUCCESS;
300
301 error:
302     Close (obj);
303     return VLC_EGENERIC;
304 }
305
306
307 /**
308  * Disconnect from the X server.
309  */
310 static void Close (vlc_object_t *obj)
311 {
312     vout_thread_t *vout = (vout_thread_t *)obj;
313     vout_sys_t *p_sys = vout->p_sys;
314
315     if (p_sys->embed)
316         vout_ReleaseWindow (p_sys->embed);
317     /* colormap is garbage-ollected by X (?) */
318     if (p_sys->conn)
319         xcb_disconnect (p_sys->conn);
320     free (p_sys);
321 }
322
323 struct picture_sys_t
324 {
325     xcb_connection_t *conn; /* Shared connection to X server */
326     xcb_image_t *image;  /* Picture buffer */
327     xcb_image_t *native; /* Rendered picture buffer (in X server format) */
328     xcb_shm_seg_t segment; /* Shared memory segment X ID */
329 };
330
331 #define SHM_ERR ((void *)(intptr_t)(-1))
332
333 static int PictureInit (vout_thread_t *vout, picture_t *pic)
334 {
335     vout_sys_t *p_sys = vout->p_sys;
336     picture_sys_t *priv = malloc (sizeof (*p_sys));
337
338     if (priv == NULL)
339         return VLC_ENOMEM;
340
341     assert (pic->i_status == FREE_PICTURE);
342     vout_InitPicture (vout, pic, vout->output.i_chroma,
343                       vout->output.i_width, vout->output.i_height,
344                       vout->output.i_aspect);
345
346     void *shm = SHM_ERR;
347     const size_t size = pic->p->i_pitch * pic->p->i_lines;
348
349     if (p_sys->shm)
350     {   /* Allocate shared memory segment */
351         int id = shmget (IPC_PRIVATE, size, IPC_CREAT | 0700);
352
353         if (id == -1)
354         {
355             msg_Err (vout, "shared memory allocation error: %m");
356             goto error;
357         }
358
359         /* Attach the segment to VLC */
360         shm = shmat (id, NULL, 0 /* read/write */);
361         if (shm == SHM_ERR)
362         {
363             msg_Err (vout, "shared memory attachment error: %m");
364             shmctl (id, IPC_RMID, 0);
365             goto error;
366         }
367
368         /* Attach the segment to X */
369         xcb_void_cookie_t ck;
370
371         priv->segment = xcb_generate_id (p_sys->conn);
372         ck = xcb_shm_attach_checked (p_sys->conn, priv->segment, id, 1);
373         shmctl (id, IPC_RMID, 0);
374
375         if (CheckError (vout, "shared memory server-side error", ck))
376         {
377             msg_Info (vout, "using buggy X (remote) server? SSH?");
378             shmdt (shm);
379             shm = SHM_ERR;
380         }
381     }
382     else
383         priv->segment = 0;
384
385     const unsigned real_width = pic->p->i_pitch / (p_sys->bpp >> 3);
386     /* FIXME: anyway to getthing more intuitive than that?? */
387
388     xcb_image_t *img;
389     img = xcb_image_create (real_width, pic->p->i_lines,
390                             XCB_IMAGE_FORMAT_Z_PIXMAP, p_sys->pad,
391                             p_sys->screen->root_depth, p_sys->bpp, p_sys->bpp,
392 #ifdef WORDS_BIGENDIAN
393                             XCB_IMAGE_ORDER_MSB_FIRST,
394 #else
395                             XCB_IMAGE_ORDER_LSB_FIRST,
396 #endif
397                             XCB_IMAGE_ORDER_MSB_FIRST,
398                             NULL,
399                             (shm != SHM_ERR) ? size : 0,
400                             (shm != SHM_ERR) ? shm : NULL);
401
402     if (img == NULL)
403     {
404         if (shm != SHM_ERR)
405             xcb_shm_detach (p_sys->conn, priv->segment);
406         goto error;
407     }
408     if (shm != SHM_ERR && xcb_image_native (p_sys->conn, img, 0) == NULL)
409         msg_Warn (vout, "incompatible X server image format");
410
411     priv->conn = p_sys->conn;
412     priv->image = img;
413     priv->native = NULL;
414     pic->p_sys = priv;
415     pic->p->p_pixels = img->data;
416     pic->i_status = DESTROYED_PICTURE;
417     pic->i_type = DIRECT_PICTURE;
418     return VLC_SUCCESS;
419
420 error:
421     if (shm != SHM_ERR)
422         shmdt (shm);
423     free (priv);
424     return VLC_EGENERIC;
425 }
426
427
428 /**
429  * Release picture private data
430  */
431 static void PictureDeinit (picture_t *pic)
432 {
433     struct picture_sys_t *p_sys = pic->p_sys;
434
435     if (p_sys->segment != 0)
436     {
437         xcb_shm_detach (p_sys->conn, p_sys->segment);
438         shmdt (p_sys->image->data);
439     }
440     if ((p_sys->native != NULL) && (p_sys->native != p_sys->image))
441         xcb_image_destroy (p_sys->native);
442     xcb_image_destroy (p_sys->image);
443     free (p_sys);
444 }
445
446 /**
447  * Allocate drawable window and picture buffers.
448  */
449 static int Init (vout_thread_t *vout)
450 {
451     vout_sys_t *p_sys = vout->p_sys;
452     const xcb_screen_t *screen = p_sys->screen;
453     unsigned x, y, width, height;
454
455     I_OUTPUTPICTURES = 0;
456
457     /* Determine parent window and size */
458     if (vout->b_fullscreen)
459     {
460         p_sys->parent = screen->root;
461         width = screen->width_in_pixels;
462         height = screen->height_in_pixels;
463     }
464     else
465     {
466         p_sys->parent = p_sys->embed->handle.xid;
467
468         /* Subscribe to parent window resize events */
469         const uint32_t value = XCB_EVENT_MASK_STRUCTURE_NOTIFY;
470         xcb_change_window_attributes (p_sys->conn, p_sys->parent,
471                                       XCB_CW_EVENT_MASK, &value);
472
473         xcb_get_geometry_cookie_t ck;
474         ck = xcb_get_geometry (p_sys->conn, p_sys->parent);
475
476         xcb_get_geometry_reply_t *geo;
477         xcb_generic_error_t *err;
478         geo = xcb_get_geometry_reply (p_sys->conn, ck, &err);
479         width = geo->width;
480         height = geo->height;
481         free (geo);
482     }
483
484     vout_PlacePicture (vout, width, height, &x, &y, &width, &height);
485
486     /* FIXME: I don't get the subtlety between output and fmt_out here */
487     vout->fmt_out.i_visible_width = width;
488     vout->fmt_out.i_visible_height = height;
489     vout->fmt_out.i_sar_num = vout->fmt_out.i_sar_den = 1;
490
491     vout->output.i_width = vout->fmt_out.i_width =
492         width * vout->fmt_in.i_width / vout->fmt_in.i_visible_width;
493     vout->output.i_height = vout->fmt_out.i_height =
494         height * vout->fmt_in.i_height / vout->fmt_in.i_visible_height;
495     vout->fmt_out.i_x_offset =
496         width * vout->fmt_in.i_x_offset / vout->fmt_in.i_visible_width;
497     p_vout->fmt_out.i_y_offset =
498         height * vout->fmt_in.i_y_offset / vout->fmt_in.i_visible_height;
499
500     assert (height > 0);
501     vout->output.i_aspect = vout->fmt_out.i_aspect =
502         width * VOUT_ASPECT_FACTOR / height;
503
504     /* Create window */
505     const uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK
506                         | XCB_CW_COLORMAP;
507     const uint32_t values[] = {
508         /* XCB_CW_BACK_PIXEL */
509         screen->black_pixel,
510         /* XCB_CW_EVENT_MASK */
511         XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE |
512         XCB_EVENT_MASK_POINTER_MOTION,
513         /* XCB_CW_COLORMAP */
514         p_sys->cmap,
515     };
516     xcb_void_cookie_t c;
517     xcb_window_t window = xcb_generate_id (p_sys->conn);
518
519     c = xcb_create_window_checked (p_sys->conn, screen->root_depth, window,
520                                    p_sys->parent, x, y, width, height, 0,
521                                    XCB_WINDOW_CLASS_INPUT_OUTPUT,
522                                    p_sys->vid, mask, values);
523     if (CheckError (vout, "cannot create X11 window", c))
524         goto error;
525     p_sys->window = window;
526     msg_Dbg (vout, "using X11 window %08"PRIx32, p_sys->window);
527     xcb_map_window (p_sys->conn, window);
528
529     /* Create graphic context (I wonder why the heck do we need this) */
530     p_sys->gc = xcb_generate_id (p_sys->conn);
531     xcb_create_gc (p_sys->conn, p_sys->gc, p_sys->window, 0, NULL);
532     msg_Dbg (vout, "using X11 graphic context %08"PRIx32, p_sys->gc);
533     xcb_flush (p_sys->conn);
534
535     /* Allocate picture buffers */
536     I_OUTPUTPICTURES = 0;
537     for (size_t index = 0; I_OUTPUTPICTURES < 2; index++)
538     {
539         picture_t *pic = vout->p_picture + index;
540
541         if (index > sizeof (vout->p_picture) / sizeof (pic))
542             break;
543         if (pic->i_status != FREE_PICTURE)
544             continue;
545         if (PictureInit (vout, pic))
546             break;
547         PP_OUTPUTPICTURE[I_OUTPUTPICTURES++] = pic;
548     }
549
550     return VLC_SUCCESS;
551
552 error:
553     Deinit (vout);
554     return VLC_EGENERIC;
555 }
556
557 /**
558  * Free picture buffers.
559  */
560 static void Deinit (vout_thread_t *vout)
561 {
562     vout_sys_t *p_sys = vout->p_sys;
563
564     for (int i = 0; i < I_OUTPUTPICTURES; i++)
565         PictureDeinit (PP_OUTPUTPICTURE[i]);
566
567     xcb_unmap_window (p_sys->conn, p_sys->window);
568     xcb_destroy_window (p_sys->conn, p_sys->window);
569 }
570
571 /**
572  * Prepares an image ahead of display.
573  */
574 static void Render (vout_thread_t *vout, picture_t *pic)
575 {
576     vout_sys_t *p_sys = vout->p_sys;
577     picture_sys_t *priv = pic->p_sys;
578
579     if ((priv->native != NULL) && (priv->native != priv->image))
580         xcb_image_destroy (priv->native);
581     priv->native = xcb_image_native (p_sys->conn, priv->image, 1);
582 }
583
584
585 /**
586  * Sends an image to the X server.
587  */
588 static void Display (vout_thread_t *vout, picture_t *pic)
589 {
590     vout_sys_t *p_sys = vout->p_sys;
591     picture_sys_t *priv = pic->p_sys;
592     xcb_image_t *img = priv->image, *native = priv->native;
593
594     if ((native == img) && (img->base == NULL))
595     {
596         xcb_shm_segment_info_t info = {
597             .shmseg = priv->segment,
598             .shmid = -1, /* lost track of it, unimportant */
599             .shmaddr = img->data,
600         };
601
602         xcb_image_shm_put (p_sys->conn, p_sys->window, p_sys->gc, img, info,
603                         0, 0, 0, 0, img->width, img->height, 0);
604     }
605     else
606     if (native != NULL)
607         xcb_image_put (p_sys->conn, p_sys->window, p_sys->gc, native, 0, 0, 0);
608     xcb_flush (p_sys->conn);
609 }
610
611 /**
612  * Process incoming X events.
613  */
614 static int Manage (vout_thread_t *vout)
615 {
616     vout_sys_t *p_sys = vout->p_sys;
617     xcb_generic_event_t *ev;
618
619     while ((ev = xcb_poll_for_event (p_sys->conn)) != NULL)
620         ProcessEvent (vout, p_sys->conn, p_sys->window, ev);
621
622     if (xcb_connection_has_error (p_sys->conn))
623     {
624         msg_Err (vout, "X server failure");
625         return VLC_EGENERIC;
626     }
627     return VLC_SUCCESS;
628 }