]> git.sesse.net Git - ffmpeg/blob - libavdevice/xcbgrab.c
xcbgrab: XCB-based screen capture
[ffmpeg] / libavdevice / xcbgrab.c
1 /*
2  * XCB input grabber
3  * Copyright (C) 2014 Luca Barbato <lu_zero@gentoo.org>
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include <stdlib.h>
25 #include <xcb/xcb.h>
26
27 #if CONFIG_LIBXCB_XFIXES
28 #include <xcb/xfixes.h>
29 #endif
30
31 #if CONFIG_LIBXCB_SHM
32 #include <sys/shm.h>
33 #include <xcb/shm.h>
34 #endif
35
36 #include "libavformat/avformat.h"
37 #include "libavformat/internal.h"
38
39 #include "libavutil/mathematics.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/time.h"
43
44 typedef struct XCBGrabContext {
45     const AVClass *class;
46
47     xcb_connection_t *conn;
48     xcb_screen_t *screen;
49     xcb_window_t window;
50     xcb_shm_seg_t segment;
51
52     int64_t time_frame;
53     AVRational time_base;
54
55     int x, y;
56     int width, height;
57     int frame_size;
58     int bpp;
59
60     int draw_mouse;
61     int follow_mouse;
62     int show_region;
63     int region_border;
64     int centered;
65
66     const char *video_size;
67     const char *framerate;
68
69     int has_shm;
70 } XCBGrabContext;
71
72 #define FOLLOW_CENTER -1
73
74 #define OFFSET(x) offsetof(XCBGrabContext, x)
75 #define D AV_OPT_FLAG_DECODING_PARAM
76 static const AVOption options[] = {
77     { "x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
78     { "y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
79     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = "vga" }, 0, 0, D },
80     { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc" }, 0, 0, D },
81     { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
82     { "follow_mouse", "Move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region.",
83       OFFSET(follow_mouse), AV_OPT_TYPE_INT, { .i64 = 0 },  FOLLOW_CENTER, INT_MAX, D, "follow_mouse" },
84     { "centered", "Keep the mouse pointer at the center of grabbing region when following.", 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, D, "follow_mouse" },
85     { "show_region", "Show the grabbing region.", OFFSET(show_region), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
86     { "region_border", "Set the region border thickness.", OFFSET(region_border), AV_OPT_TYPE_INT, { .i64 = 3 }, 1, 128, D },
87     { NULL },
88 };
89
90 static const AVClass xcbgrab_class = {
91     .class_name = "xcbgrab indev",
92     .item_name  = av_default_item_name,
93     .option     = options,
94     .version    = LIBAVUTIL_VERSION_INT,
95 };
96
97 static int xcbgrab_reposition(AVFormatContext *s,
98                               xcb_query_pointer_reply_t *p,
99                               xcb_get_geometry_reply_t *geo)
100 {
101     XCBGrabContext *c = s->priv_data;
102     int x = c->x, y = c->y, p_x = p->win_x, p_y = p->win_y;
103     int w = c->width, h = c->height, f = c->follow_mouse;
104
105     if (!p || !geo)
106         return AVERROR(EIO);
107
108     if (f == FOLLOW_CENTER) {
109         x = p_x - w / 2;
110         y = p_y - h / 2;
111     } else {
112         int left   = x + f;
113         int right  = x + w - f;
114         int top    = y + f;
115         int bottom = y + h + f;
116         if (p_x > right) {
117             x += p_x - right;
118         } else if (p_x < left) {
119             x -= left - p_x;
120         }
121         if (p_y > bottom) {
122             y += p_y - bottom;
123         } else if (p_y < top) {
124             y -= top - p_y;
125         }
126     }
127
128     c->x = FFMIN(FFMAX(0, x), geo->width  - w);
129     c->y = FFMIN(FFMAX(0, y), geo->height - h);
130
131     return 0;
132 }
133
134 static int xcbgrab_frame(AVFormatContext *s, AVPacket *pkt)
135 {
136     XCBGrabContext *c = s->priv_data;
137     xcb_get_image_cookie_t iq;
138     xcb_get_image_reply_t *img;
139     xcb_drawable_t drawable = c->screen->root;
140     uint8_t *data;
141     int length, ret;
142
143     iq  = xcb_get_image(c->conn, XCB_IMAGE_FORMAT_Z_PIXMAP, drawable,
144                         c->x, c->y, c->width, c->height, ~0);
145
146     img = xcb_get_image_reply(c->conn, iq, NULL);
147     if (!img)
148         return AVERROR(EAGAIN);
149
150     data   = xcb_get_image_data(img);
151     length = xcb_get_image_data_length(img);
152
153     ret = av_new_packet(pkt, length);
154
155     if (!ret)
156         memcpy(pkt->data, data, length);
157
158     free(img);
159
160     return ret;
161 }
162
163 static void wait_frame(AVFormatContext *s, AVPacket *pkt)
164 {
165     XCBGrabContext *c = s->priv_data;
166     int64_t curtime, delay;
167     int64_t frame_time = av_rescale_q(1, c->time_base, AV_TIME_BASE_Q);
168
169     c->time_frame += frame_time;
170
171     for (;;) {
172         curtime = av_gettime();
173         delay   = c->time_frame - curtime;
174         if (delay <= 0)
175             break;
176         av_usleep(delay);
177     }
178
179     pkt->pts = curtime;
180 }
181
182 #if CONFIG_LIBXCB_SHM
183 static int check_shm(xcb_connection_t *conn)
184 {
185     xcb_shm_query_version_cookie_t cookie = xcb_shm_query_version(conn);
186     xcb_shm_query_version_reply_t *reply;
187
188     reply = xcb_shm_query_version_reply(conn, cookie, NULL);
189     if (reply) {
190         free(reply);
191         return 1;
192     }
193
194     return 0;
195 }
196
197 static void dealloc_shm(void *unused, uint8_t *data)
198 {
199     shmdt(data);
200 }
201
202 static int xcbgrab_frame_shm(AVFormatContext *s, AVPacket *pkt)
203 {
204     XCBGrabContext *c = s->priv_data;
205     xcb_shm_get_image_cookie_t iq;
206     xcb_shm_get_image_reply_t *img;
207     xcb_drawable_t drawable = c->screen->root;
208     uint8_t *data;
209     int size = c->frame_size + FF_INPUT_BUFFER_PADDING_SIZE;
210     int id   = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
211     xcb_generic_error_t *e = NULL;
212
213     if (id == -1) {
214         char errbuf[1024];
215         int err = AVERROR(errno);
216         av_strerror(err, errbuf, sizeof(errbuf));
217         av_log(s, AV_LOG_ERROR, "Cannot get %d bytes of shared memory: %s.\n",
218                size, errbuf);
219         return err;
220     }
221
222     xcb_shm_attach(c->conn, c->segment, id, 0);
223
224     iq = xcb_shm_get_image(c->conn, drawable,
225                            c->x, c->y, c->width, c->height, ~0,
226                            XCB_IMAGE_FORMAT_Z_PIXMAP, c->segment, 0);
227
228     xcb_shm_detach(c->conn, c->segment);
229
230     img = xcb_shm_get_image_reply(c->conn, iq, &e);
231
232     xcb_flush(c->conn);
233
234     if (e) {
235         av_log(s, AV_LOG_ERROR,
236                "Cannot get the image data "
237                "event_error: response_type:%u error_code:%u "
238                "sequence:%u resource_id:%u minor_code:%u major_code:%u.\n",
239                e->response_type, e->error_code,
240                e->sequence, e->resource_id, e->minor_code, e->major_code);
241
242         shmctl(id, IPC_RMID, 0);
243         return AVERROR(EACCES);
244     }
245
246     free(img);
247
248     data = shmat(id, NULL, 0);
249     shmctl(id, IPC_RMID, 0);
250
251     if ((intptr_t)data == -1)
252         return AVERROR(errno);
253
254     pkt->buf = av_buffer_create(data, size, dealloc_shm, NULL, 0);
255     if (!pkt->buf) {
256         shmdt(data);
257         return AVERROR(ENOMEM);
258     }
259
260     pkt->data = pkt->buf->data;
261     pkt->size = c->frame_size;
262
263     return 0;
264 }
265 #endif /* CONFIG_LIBXCB_SHM */
266
267 #if CONFIG_LIBXCB_XFIXES
268 static int check_xfixes(xcb_connection_t *conn)
269 {
270     xcb_xfixes_query_version_cookie_t cookie;
271     xcb_xfixes_query_version_reply_t *reply;
272
273     cookie = xcb_xfixes_query_version(conn, XCB_XFIXES_MAJOR_VERSION,
274                                       XCB_XFIXES_MINOR_VERSION);
275     reply  = xcb_xfixes_query_version_reply(conn, cookie, NULL);
276
277     if (reply) {
278         free(reply);
279         return 1;
280     }
281     return 0;
282 }
283
284 #define BLEND(target, source, alpha) \
285     (target) + ((source) * (255 - (alpha)) + 255 / 2) / 255
286
287 static void xcbgrab_draw_mouse(AVFormatContext *s, AVPacket *pkt,
288                                xcb_query_pointer_reply_t *p,
289                                xcb_get_geometry_reply_t *geo)
290 {
291     XCBGrabContext *gr = s->priv_data;
292     uint32_t *cursor;
293     uint8_t *image = pkt->data;
294     int stride     = gr->bpp / 8;
295     xcb_xfixes_get_cursor_image_cookie_t cc;
296     xcb_xfixes_get_cursor_image_reply_t *ci;
297     int cx, cy, x, y, w, h, c_off, i_off;
298
299     cc = xcb_xfixes_get_cursor_image(gr->conn);
300     ci = xcb_xfixes_get_cursor_image_reply(gr->conn, cc, NULL);
301     if (!ci)
302         return;
303
304     cursor = xcb_xfixes_get_cursor_image_cursor_image(ci);
305     if (!cursor)
306         return;
307
308     cx = ci->x - ci->xhot;
309     cy = ci->y - ci->yhot;
310
311     x = FFMAX(cx, gr->x);
312     y = FFMAX(cy, gr->y);
313
314     w = FFMIN(cx + ci->width,  gr->x + gr->width)  - x;
315     h = FFMIN(cy + ci->height, gr->y + gr->height) - y;
316
317     c_off = x - cx;
318     i_off = x - gr->x;
319
320     cursor += (y - cy) * ci->width;
321     image  += (y - gr->y) * gr->width * stride;
322
323     for (y = 0; y < h; y++) {
324         cursor += c_off;
325         image  += i_off * stride;
326         for (x = 0; x < w; x++, cursor++, image += stride) {
327             int r, g, b, a;
328
329             r =  *cursor        & 0xff;
330             g = (*cursor >>  8) & 0xff;
331             b = (*cursor >> 16) & 0xff;
332             a = (*cursor >> 24) & 0xff;
333
334             if (!a)
335                 continue;
336
337             if (a == 255) {
338                 image[0] = r;
339                 image[1] = g;
340                 image[2] = b;
341             } else {
342                 image[0] = BLEND(r, image[0], a);
343                 image[1] = BLEND(g, image[1], a);
344                 image[2] = BLEND(b, image[2], a);
345             }
346
347         }
348         cursor +=  ci->width - w - c_off;
349         image  += (gr->width - w - i_off) * stride;
350     }
351
352     free(ci);
353 }
354 #endif /* CONFIG_LIBXCB_XFIXES */
355
356 static void xcbgrab_update_region(AVFormatContext *s)
357 {
358     XCBGrabContext *c     = s->priv_data;
359     const uint32_t args[] = { c->x - c->region_border,
360                               c->y - c->region_border };
361
362     xcb_configure_window(c->conn,
363                          c->window,
364                          XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y,
365                          args);
366 }
367
368 static int xcbgrab_read_packet(AVFormatContext *s, AVPacket *pkt)
369 {
370     XCBGrabContext *c = s->priv_data;
371     xcb_query_pointer_cookie_t pc;
372     xcb_get_geometry_cookie_t gc;
373     xcb_query_pointer_reply_t *p  = NULL;
374     xcb_get_geometry_reply_t *geo = NULL;
375     int ret = 0;
376
377     wait_frame(s, pkt);
378
379     if (c->follow_mouse || c->draw_mouse) {
380         pc  = xcb_query_pointer(c->conn, c->screen->root);
381         gc  = xcb_get_geometry(c->conn, c->screen->root);
382         p   = xcb_query_pointer_reply(c->conn, pc, NULL);
383         geo = xcb_get_geometry_reply(c->conn, gc, NULL);
384     }
385
386     if (c->follow_mouse && p->same_screen)
387         xcbgrab_reposition(s, p, geo);
388
389     if (c->show_region)
390         xcbgrab_update_region(s);
391
392 #if CONFIG_LIBXCB_SHM
393     if (c->has_shm && xcbgrab_frame_shm(s, pkt) < 0)
394         c->has_shm = 0;
395 #endif
396     if (!c->has_shm)
397         ret = xcbgrab_frame(s, pkt);
398
399 #if CONFIG_LIBXCB_XFIXES
400     if (c->draw_mouse && p->same_screen)
401         xcbgrab_draw_mouse(s, pkt, p, geo);
402 #endif
403
404     free(p);
405     free(geo);
406
407     return ret;
408 }
409
410 static av_cold int xcbgrab_read_close(AVFormatContext *s)
411 {
412     XCBGrabContext *ctx = s->priv_data;
413
414     xcb_disconnect(ctx->conn);
415
416     return 0;
417 }
418
419 static xcb_screen_t *get_screen(const xcb_setup_t *setup, int screen_num)
420 {
421     xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup);
422     xcb_screen_t *screen     = NULL;
423
424     for (; it.rem > 0; xcb_screen_next (&it)) {
425         if (!screen_num) {
426             screen = it.data;
427             break;
428         }
429
430         screen_num--;
431     }
432
433     return screen;
434 }
435
436 static int pixfmt_from_pixmap_format(AVFormatContext *s, int depth,
437                                      int *pix_fmt)
438 {
439     XCBGrabContext *c        = s->priv_data;
440     const xcb_setup_t *setup = xcb_get_setup(c->conn);
441     const xcb_format_t *fmt  = xcb_setup_pixmap_formats(setup);
442     int length               = xcb_setup_pixmap_formats_length(setup);
443
444     *pix_fmt = 0;
445
446     while (length--) {
447         if (fmt->depth == depth) {
448             switch (depth) {
449             case 32:
450                 if (fmt->bits_per_pixel == 32)
451                     *pix_fmt = AV_PIX_FMT_ARGB;
452                 break;
453             case 24:
454                 if (fmt->bits_per_pixel == 32)
455                     *pix_fmt = AV_PIX_FMT_RGB32;
456                 else if (fmt->bits_per_pixel == 24)
457                     *pix_fmt = AV_PIX_FMT_RGB24;
458                 break;
459             case 16:
460                 if (fmt->bits_per_pixel == 16)
461                     *pix_fmt = AV_PIX_FMT_RGB565;
462                 break;
463             case 15:
464                 if (fmt->bits_per_pixel == 16)
465                     *pix_fmt = AV_PIX_FMT_RGB555;
466                 break;
467             case 8:
468                 if (fmt->bits_per_pixel == 8)
469                     *pix_fmt = AV_PIX_FMT_RGB8;
470                 break;
471             }
472         }
473
474         if (*pix_fmt) {
475             c->bpp        = fmt->bits_per_pixel;
476             c->frame_size = c->width * c->height * fmt->bits_per_pixel / 8;
477             return 0;
478         }
479
480         fmt++;
481     }
482     av_log(s, AV_LOG_ERROR, "Pixmap format not mappable.\n");
483
484     return AVERROR_PATCHWELCOME;
485 }
486
487 static int create_stream(AVFormatContext *s)
488 {
489     XCBGrabContext *c = s->priv_data;
490     AVStream *st      = avformat_new_stream(s, NULL);
491     const char *opts  = strchr(s->filename, '+');
492     xcb_get_geometry_cookie_t gc;
493     xcb_get_geometry_reply_t *geo;
494     int ret;
495
496     if (!st)
497         return AVERROR(ENOMEM);
498
499     ret = av_parse_video_size(&c->width, &c->height, c->video_size);
500     if (ret < 0)
501         return ret;
502
503     ret = av_parse_video_rate(&st->avg_frame_rate, c->framerate);
504     if (ret < 0)
505         return ret;
506
507     if (opts)
508         sscanf(opts, "%d,%d", &c->x, &c->y);
509
510     avpriv_set_pts_info(st, 64, 1, 1000000);
511
512     gc  = xcb_get_geometry(c->conn, c->screen->root);
513     geo = xcb_get_geometry_reply(c->conn, gc, NULL);
514
515     c->width      = FFMIN(geo->width, c->width);
516     c->height     = FFMIN(geo->height, c->height);
517     c->time_base  = (AVRational){ st->avg_frame_rate.den,
518                                   st->avg_frame_rate.num };
519     c->time_frame = av_gettime();
520
521     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
522     st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
523     st->codec->width      = c->width;
524     st->codec->height     = c->height;
525     st->codec->time_base  = c->time_base;
526
527     ret = pixfmt_from_pixmap_format(s, geo->depth, &st->codec->pix_fmt);
528
529     free(geo);
530
531     return ret;
532 }
533
534 static void draw_rectangle(AVFormatContext *s)
535 {
536     XCBGrabContext *c = s->priv_data;
537     xcb_gcontext_t gc = xcb_generate_id(c->conn);
538     uint32_t mask     = XCB_GC_FOREGROUND |
539                         XCB_GC_BACKGROUND |
540                         XCB_GC_LINE_WIDTH |
541                         XCB_GC_LINE_STYLE |
542                         XCB_GC_FILL_STYLE;
543     uint32_t values[] = { c->screen->black_pixel,
544                           c->screen->white_pixel,
545                           c->region_border,
546                           XCB_LINE_STYLE_DOUBLE_DASH,
547                           XCB_FILL_STYLE_SOLID };
548     xcb_rectangle_t r = { 1, 1,
549                           c->width  + c->region_border * 2 - 3,
550                           c->height + c->region_border * 2 - 3 };
551
552     xcb_create_gc(c->conn, gc, c->window, mask, values);
553
554     xcb_poly_rectangle(c->conn, c->window, gc, 1, &r);
555 }
556
557 static void setup_window(AVFormatContext *s)
558 {
559     XCBGrabContext *c = s->priv_data;
560     uint32_t mask     = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
561     uint32_t values[] = { 1,
562                           XCB_EVENT_MASK_EXPOSURE |
563                           XCB_EVENT_MASK_STRUCTURE_NOTIFY };
564     xcb_rectangle_t rect = { c->x, c->y, c->width, c->height };
565
566     c->window = xcb_generate_id(c->conn);
567
568     xcb_create_window(c->conn, XCB_COPY_FROM_PARENT,
569                       c->window,
570                       c->screen->root,
571                       c->x - c->region_border,
572                       c->y - c->region_border,
573                       c->width + c->region_border * 2,
574                       c->height + c->region_border * 2,
575                       0,
576                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
577                       XCB_COPY_FROM_PARENT,
578                       mask, values);
579
580     xcb_shape_rectangles(c->conn, XCB_SHAPE_SO_SUBTRACT,
581                          XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
582                          c->window,
583                          c->region_border, c->region_border,
584                          1, &rect);
585
586     xcb_map_window(c->conn, c->window);
587
588     draw_rectangle(s);
589 }
590
591 static av_cold int xcbgrab_read_header(AVFormatContext *s)
592 {
593     XCBGrabContext *c = s->priv_data;
594     int screen_num, ret;
595     const xcb_setup_t *setup;
596
597     c->conn = xcb_connect(s->filename, &screen_num);
598     if ((ret = xcb_connection_has_error(c->conn))) {
599         av_log(s, AV_LOG_ERROR, "Cannot open display %s, error %d.\n",
600                s->filename ? s->filename : "default", ret);
601         return AVERROR(EIO);
602     }
603     setup = xcb_get_setup(c->conn);
604
605     c->screen = get_screen(setup, screen_num);
606     if (!c->screen) {
607         av_log(s, AV_LOG_ERROR, "The screen %d does not exist.\n",
608                screen_num);
609         xcbgrab_read_close(s);
610         return AVERROR(EIO);
611     }
612
613     c->segment = xcb_generate_id(c->conn);
614
615     ret = create_stream(s);
616
617     if (ret < 0) {
618         xcbgrab_read_close(s);
619         return ret;
620     }
621
622 #if CONFIG_LIBXCB_SHM
623     c->has_shm = check_shm(c->conn);
624 #endif
625
626 #if CONFIG_LIBXCB_XFIXES
627     if (c->draw_mouse) {
628         if (!(c->draw_mouse = check_xfixes(c->conn))) {
629             av_log(s, AV_LOG_WARNING,
630                    "XFixes not available, cannot draw the mouse.\n");
631         }
632         if (c->bpp < 24) {
633             avpriv_report_missing_feature(s, "%d bits per pixel screen",
634                                           c->bpp);
635             c->draw_mouse = 0;
636         }
637     }
638 #endif
639
640     if (c->show_region)
641         setup_window(s);
642
643     return 0;
644 }
645
646 AVInputFormat ff_x11grab_xcb_demuxer = {
647     .name           = "x11grab",
648     .long_name      = NULL_IF_CONFIG_SMALL("X11 screen capture, using XCB"),
649     .priv_data_size = sizeof(XCBGrabContext),
650     .read_header    = xcbgrab_read_header,
651     .read_packet    = xcbgrab_read_packet,
652     .read_close     = xcbgrab_read_close,
653     .flags          = AVFMT_NOFILE,
654     .priv_class     = &xcbgrab_class,
655 };