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