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