3 * Copyright (C) 2014 Luca Barbato <lu_zero@gentoo.org>
5 * This file is part of FFmpeg.
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.
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.
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
27 #if CONFIG_LIBXCB_XFIXES
28 #include <xcb/xfixes.h>
36 #if CONFIG_LIBXCB_SHAPE
37 #include <xcb/shape.h>
40 #include "libavutil/internal.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/parseutils.h"
44 #include "libavutil/time.h"
46 #include "libavformat/avformat.h"
47 #include "libavformat/internal.h"
49 typedef struct XCBGrabContext {
52 xcb_connection_t *conn;
56 AVBufferPool *shm_pool;
60 int64_t frame_duration;
73 const char *video_size;
74 const char *framerate;
79 #define FOLLOW_CENTER -1
81 #define OFFSET(x) offsetof(XCBGrabContext, x)
82 #define D AV_OPT_FLAG_DECODING_PARAM
83 static const AVOption options[] = {
84 { "x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
85 { "y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
86 { "grab_x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
87 { "grab_y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
88 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = "vga" }, 0, 0, D },
89 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc" }, 0, 0, D },
90 { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
91 { "follow_mouse", "Move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region.",
92 OFFSET(follow_mouse), AV_OPT_TYPE_INT, { .i64 = 0 }, FOLLOW_CENTER, INT_MAX, D, "follow_mouse" },
93 { "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" },
94 { "show_region", "Show the grabbing region.", OFFSET(show_region), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
95 { "region_border", "Set the region border thickness.", OFFSET(region_border), AV_OPT_TYPE_INT, { .i64 = 3 }, 1, 128, D },
99 static const AVClass xcbgrab_class = {
100 .class_name = "xcbgrab indev",
101 .item_name = av_default_item_name,
103 .version = LIBAVUTIL_VERSION_INT,
104 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
107 static int xcbgrab_reposition(AVFormatContext *s,
108 xcb_query_pointer_reply_t *p,
109 xcb_get_geometry_reply_t *geo)
111 XCBGrabContext *c = s->priv_data;
112 int x = c->x, y = c->y;
113 int w = c->width, h = c->height, f = c->follow_mouse;
122 if (f == FOLLOW_CENTER) {
127 int right = x + w - f;
129 int bottom = y + h - f;
132 } else if (p_x < left) {
137 } else if (p_y < top) {
142 c->x = FFMIN(FFMAX(0, x), geo->width - w);
143 c->y = FFMIN(FFMAX(0, y), geo->height - h);
148 static void xcbgrab_image_reply_free(void *opaque, uint8_t *data)
153 static int xcbgrab_frame(AVFormatContext *s, AVPacket *pkt)
155 XCBGrabContext *c = s->priv_data;
156 xcb_get_image_cookie_t iq;
157 xcb_get_image_reply_t *img;
158 xcb_drawable_t drawable = c->screen->root;
159 xcb_generic_error_t *e = NULL;
163 iq = xcb_get_image(c->conn, XCB_IMAGE_FORMAT_Z_PIXMAP, drawable,
164 c->x, c->y, c->width, c->height, ~0);
166 img = xcb_get_image_reply(c->conn, iq, &e);
169 av_log(s, AV_LOG_ERROR,
170 "Cannot get the image data "
171 "event_error: response_type:%u error_code:%u "
172 "sequence:%u resource_id:%u minor_code:%u major_code:%u.\n",
173 e->response_type, e->error_code,
174 e->sequence, e->resource_id, e->minor_code, e->major_code);
176 return AVERROR(EACCES);
180 return AVERROR(EAGAIN);
182 data = xcb_get_image_data(img);
183 length = xcb_get_image_data_length(img);
187 pkt->buf = av_buffer_create(data, length, xcbgrab_image_reply_free, img, 0);
190 return AVERROR(ENOMEM);
199 static int64_t wait_frame(AVFormatContext *s, AVPacket *pkt)
201 XCBGrabContext *c = s->priv_data;
202 int64_t curtime, delay;
204 c->time_frame += c->frame_duration;
207 curtime = av_gettime();
208 delay = c->time_frame - curtime;
217 #if CONFIG_LIBXCB_SHM
218 static int check_shm(xcb_connection_t *conn)
220 xcb_shm_query_version_cookie_t cookie = xcb_shm_query_version(conn);
221 xcb_shm_query_version_reply_t *reply;
223 reply = xcb_shm_query_version_reply(conn, cookie, NULL);
232 static void free_shm_buffer(void *opaque, uint8_t *data)
237 static AVBufferRef *allocate_shm_buffer(void *opaque, int size)
239 xcb_connection_t *conn = opaque;
240 xcb_shm_seg_t segment;
245 id = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
249 segment = xcb_generate_id(conn);
250 xcb_shm_attach(conn, segment, id, 0);
251 data = shmat(id, NULL, 0);
252 shmctl(id, IPC_RMID, 0);
253 if ((intptr_t)data == -1 || !data)
256 ref = av_buffer_create(data, size, free_shm_buffer, (void *)(ptrdiff_t)segment, 0);
263 static int xcbgrab_frame_shm(AVFormatContext *s, AVPacket *pkt)
265 XCBGrabContext *c = s->priv_data;
266 xcb_shm_get_image_cookie_t iq;
267 xcb_shm_get_image_reply_t *img;
268 xcb_drawable_t drawable = c->screen->root;
269 xcb_generic_error_t *e = NULL;
271 xcb_shm_seg_t segment;
273 buf = av_buffer_pool_get(c->shm_pool);
275 av_log(s, AV_LOG_ERROR, "Could not get shared memory buffer.\n");
276 return AVERROR(ENOMEM);
278 segment = (xcb_shm_seg_t)av_buffer_pool_buffer_get_opaque(buf);
280 iq = xcb_shm_get_image(c->conn, drawable,
281 c->x, c->y, c->width, c->height, ~0,
282 XCB_IMAGE_FORMAT_Z_PIXMAP, segment, 0);
283 img = xcb_shm_get_image_reply(c->conn, iq, &e);
288 av_log(s, AV_LOG_ERROR,
289 "Cannot get the image data "
290 "event_error: response_type:%u error_code:%u "
291 "sequence:%u resource_id:%u minor_code:%u major_code:%u.\n",
292 e->response_type, e->error_code,
293 e->sequence, e->resource_id, e->minor_code, e->major_code);
296 av_buffer_unref(&buf);
297 return AVERROR(EACCES);
305 pkt->data = buf->data;
306 pkt->size = c->frame_size;
310 #endif /* CONFIG_LIBXCB_SHM */
312 #if CONFIG_LIBXCB_XFIXES
313 static int check_xfixes(xcb_connection_t *conn)
315 xcb_xfixes_query_version_cookie_t cookie;
316 xcb_xfixes_query_version_reply_t *reply;
318 cookie = xcb_xfixes_query_version(conn, XCB_XFIXES_MAJOR_VERSION,
319 XCB_XFIXES_MINOR_VERSION);
320 reply = xcb_xfixes_query_version_reply(conn, cookie, NULL);
329 #define BLEND(target, source, alpha) \
330 (target) + ((source) * (255 - (alpha)) + 255 / 2) / 255
332 static void xcbgrab_draw_mouse(AVFormatContext *s, AVPacket *pkt,
333 xcb_query_pointer_reply_t *p,
334 xcb_get_geometry_reply_t *geo)
336 XCBGrabContext *gr = s->priv_data;
338 uint8_t *image = pkt->data;
339 int stride = gr->bpp / 8;
340 xcb_xfixes_get_cursor_image_cookie_t cc;
341 xcb_xfixes_get_cursor_image_reply_t *ci;
342 int cx, cy, x, y, w, h, c_off, i_off;
344 cc = xcb_xfixes_get_cursor_image(gr->conn);
345 ci = xcb_xfixes_get_cursor_image_reply(gr->conn, cc, NULL);
349 cursor = xcb_xfixes_get_cursor_image_cursor_image(ci);
353 cx = ci->x - ci->xhot;
354 cy = ci->y - ci->yhot;
356 x = FFMAX(cx, gr->x);
357 y = FFMAX(cy, gr->y);
359 w = FFMIN(cx + ci->width, gr->x + gr->width) - x;
360 h = FFMIN(cy + ci->height, gr->y + gr->height) - y;
365 cursor += (y - cy) * ci->width;
366 image += (y - gr->y) * gr->width * stride;
368 for (y = 0; y < h; y++) {
370 image += i_off * stride;
371 for (x = 0; x < w; x++, cursor++, image += stride) {
375 g = (*cursor >> 8) & 0xff;
376 b = (*cursor >> 16) & 0xff;
377 a = (*cursor >> 24) & 0xff;
387 image[0] = BLEND(r, image[0], a);
388 image[1] = BLEND(g, image[1], a);
389 image[2] = BLEND(b, image[2], a);
393 cursor += ci->width - w - c_off;
394 image += (gr->width - w - i_off) * stride;
399 #endif /* CONFIG_LIBXCB_XFIXES */
401 static void xcbgrab_update_region(AVFormatContext *s)
403 XCBGrabContext *c = s->priv_data;
404 const uint32_t args[] = { c->x - c->region_border,
405 c->y - c->region_border };
407 xcb_configure_window(c->conn,
409 XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y,
413 static int xcbgrab_read_packet(AVFormatContext *s, AVPacket *pkt)
415 XCBGrabContext *c = s->priv_data;
416 xcb_query_pointer_cookie_t pc;
417 xcb_get_geometry_cookie_t gc;
418 xcb_query_pointer_reply_t *p = NULL;
419 xcb_get_geometry_reply_t *geo = NULL;
423 pts = wait_frame(s, pkt);
425 if (c->follow_mouse || c->draw_mouse) {
426 pc = xcb_query_pointer(c->conn, c->screen->root);
427 gc = xcb_get_geometry(c->conn, c->screen->root);
428 p = xcb_query_pointer_reply(c->conn, pc, NULL);
429 geo = xcb_get_geometry_reply(c->conn, gc, NULL);
432 if (c->follow_mouse && p->same_screen)
433 xcbgrab_reposition(s, p, geo);
436 xcbgrab_update_region(s);
438 #if CONFIG_LIBXCB_SHM
439 if (c->has_shm && xcbgrab_frame_shm(s, pkt) < 0) {
440 av_log(s, AV_LOG_WARNING, "Continuing without shared memory.\n");
445 ret = xcbgrab_frame(s, pkt);
446 pkt->dts = pkt->pts = pts;
447 pkt->duration = c->frame_duration;
449 #if CONFIG_LIBXCB_XFIXES
450 if (ret >= 0 && c->draw_mouse && p->same_screen)
451 xcbgrab_draw_mouse(s, pkt, p, geo);
460 static av_cold int xcbgrab_read_close(AVFormatContext *s)
462 XCBGrabContext *ctx = s->priv_data;
464 #if CONFIG_LIBXCB_SHM
465 av_buffer_pool_uninit(&ctx->shm_pool);
468 xcb_disconnect(ctx->conn);
473 static xcb_screen_t *get_screen(const xcb_setup_t *setup, int screen_num)
475 xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup);
476 xcb_screen_t *screen = NULL;
478 for (; it.rem > 0; xcb_screen_next (&it)) {
490 static int pixfmt_from_pixmap_format(AVFormatContext *s, int depth,
493 XCBGrabContext *c = s->priv_data;
494 const xcb_setup_t *setup = xcb_get_setup(c->conn);
495 const xcb_format_t *fmt = xcb_setup_pixmap_formats(setup);
496 int length = xcb_setup_pixmap_formats_length(setup);
501 if (fmt->depth == depth) {
504 if (fmt->bits_per_pixel == 32)
505 *pix_fmt = AV_PIX_FMT_0RGB;
508 if (fmt->bits_per_pixel == 32)
509 *pix_fmt = AV_PIX_FMT_0RGB32;
510 else if (fmt->bits_per_pixel == 24)
511 *pix_fmt = AV_PIX_FMT_RGB24;
514 if (fmt->bits_per_pixel == 16)
515 *pix_fmt = AV_PIX_FMT_RGB565;
518 if (fmt->bits_per_pixel == 16)
519 *pix_fmt = AV_PIX_FMT_RGB555;
522 if (fmt->bits_per_pixel == 8)
523 *pix_fmt = AV_PIX_FMT_RGB8;
529 c->bpp = fmt->bits_per_pixel;
530 c->frame_size = c->width * c->height * fmt->bits_per_pixel / 8;
531 #if CONFIG_LIBXCB_SHM
532 c->shm_pool = av_buffer_pool_init2(c->frame_size + AV_INPUT_BUFFER_PADDING_SIZE,
533 c->conn, allocate_shm_buffer, NULL);
535 return AVERROR(ENOMEM);
542 avpriv_report_missing_feature(s, "Mapping this pixmap format");
544 return AVERROR_PATCHWELCOME;
547 static int create_stream(AVFormatContext *s)
549 XCBGrabContext *c = s->priv_data;
550 AVStream *st = avformat_new_stream(s, NULL);
551 xcb_get_geometry_cookie_t gc;
552 xcb_get_geometry_reply_t *geo;
556 return AVERROR(ENOMEM);
558 ret = av_parse_video_size(&c->width, &c->height, c->video_size);
562 ret = av_parse_video_rate(&st->avg_frame_rate, c->framerate);
566 avpriv_set_pts_info(st, 64, 1, 1000000);
568 gc = xcb_get_geometry(c->conn, c->screen->root);
569 geo = xcb_get_geometry_reply(c->conn, gc, NULL);
571 return AVERROR_EXTERNAL;
573 if (c->x + c->width > geo->width ||
574 c->y + c->height > geo->height) {
575 av_log(s, AV_LOG_ERROR,
576 "Capture area %dx%d at position %d.%d "
577 "outside the screen size %dx%d\n",
580 geo->width, geo->height);
582 return AVERROR(EINVAL);
585 c->time_base = (AVRational){ st->avg_frame_rate.den,
586 st->avg_frame_rate.num };
587 c->frame_duration = av_rescale_q(1, c->time_base, AV_TIME_BASE_Q);
588 c->time_frame = av_gettime();
590 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
591 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
592 st->codecpar->width = c->width;
593 st->codecpar->height = c->height;
595 ret = pixfmt_from_pixmap_format(s, geo->depth, &st->codecpar->format);
602 static void draw_rectangle(AVFormatContext *s)
604 XCBGrabContext *c = s->priv_data;
605 xcb_gcontext_t gc = xcb_generate_id(c->conn);
606 uint32_t mask = XCB_GC_FOREGROUND |
611 uint32_t values[] = { c->screen->black_pixel,
612 c->screen->white_pixel,
614 XCB_LINE_STYLE_DOUBLE_DASH,
615 XCB_FILL_STYLE_SOLID };
616 xcb_rectangle_t r = { 1, 1,
617 c->width + c->region_border * 2 - 3,
618 c->height + c->region_border * 2 - 3 };
620 xcb_create_gc(c->conn, gc, c->window, mask, values);
622 xcb_poly_rectangle(c->conn, c->window, gc, 1, &r);
625 static void setup_window(AVFormatContext *s)
627 XCBGrabContext *c = s->priv_data;
628 uint32_t mask = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
629 uint32_t values[] = { 1,
630 XCB_EVENT_MASK_EXPOSURE |
631 XCB_EVENT_MASK_STRUCTURE_NOTIFY };
632 av_unused xcb_rectangle_t rect = { 0, 0, c->width, c->height };
634 c->window = xcb_generate_id(c->conn);
636 xcb_create_window(c->conn, XCB_COPY_FROM_PARENT,
639 c->x - c->region_border,
640 c->y - c->region_border,
641 c->width + c->region_border * 2,
642 c->height + c->region_border * 2,
644 XCB_WINDOW_CLASS_INPUT_OUTPUT,
645 XCB_COPY_FROM_PARENT,
648 #if CONFIG_LIBXCB_SHAPE
649 xcb_shape_rectangles(c->conn, XCB_SHAPE_SO_SUBTRACT,
650 XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
652 c->region_border, c->region_border,
656 xcb_map_window(c->conn, c->window);
661 static av_cold int xcbgrab_read_header(AVFormatContext *s)
663 XCBGrabContext *c = s->priv_data;
665 const xcb_setup_t *setup;
666 char *display_name = av_strdup(s->url);
669 return AVERROR(ENOMEM);
671 if (!sscanf(s->url, "%[^+]+%d,%d", display_name, &c->x, &c->y)) {
673 sscanf(s->url, "+%d,%d", &c->x, &c->y);
676 c->conn = xcb_connect(display_name[0] ? display_name : NULL, &screen_num);
677 av_freep(&display_name);
679 if ((ret = xcb_connection_has_error(c->conn))) {
680 av_log(s, AV_LOG_ERROR, "Cannot open display %s, error %d.\n",
681 s->url[0] ? s->url : "default", ret);
685 setup = xcb_get_setup(c->conn);
687 c->screen = get_screen(setup, screen_num);
689 av_log(s, AV_LOG_ERROR, "The screen %d does not exist.\n",
691 xcbgrab_read_close(s);
695 ret = create_stream(s);
698 xcbgrab_read_close(s);
702 #if CONFIG_LIBXCB_SHM
703 c->has_shm = check_shm(c->conn);
706 #if CONFIG_LIBXCB_XFIXES
708 if (!(c->draw_mouse = check_xfixes(c->conn))) {
709 av_log(s, AV_LOG_WARNING,
710 "XFixes not available, cannot draw the mouse.\n");
713 avpriv_report_missing_feature(s, "%d bits per pixel screen",
726 AVInputFormat ff_xcbgrab_demuxer = {
728 .long_name = NULL_IF_CONFIG_SMALL("X11 screen capture, using XCB"),
729 .priv_data_size = sizeof(XCBGrabContext),
730 .read_header = xcbgrab_read_header,
731 .read_packet = xcbgrab_read_packet,
732 .read_close = xcbgrab_read_close,
733 .flags = AVFMT_NOFILE,
734 .priv_class = &xcbgrab_class,