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