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