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