2 * X11 video grab interface
4 * This file is part of FFmpeg.
7 * Copyright (C) 2006 Clemens Fruhwirth <clemens@endorphin.org>
8 * Edouard Gomez <ed.gomez@free.fr>
10 * This file contains code from grab.c:
11 * Copyright (c) 2000-2001 Fabrice Bellard
13 * This file contains code from the xvidcap project:
14 * Copyright (C) 1997-1998 Rasca, Berlin
15 * 2003-2004 Karl H. Beckers, Frankfurt
17 * FFmpeg is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * FFmpeg is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with FFmpeg; if not, write to the Free Software
29 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 * X11 frame device demuxer
35 * @author Clemens Fruhwirth <clemens@endorphin.org>
36 * @author Edouard Gomez <ed.gomez@free.fr>
44 #include <X11/cursorfont.h>
47 #include <X11/Xlibint.h>
48 #include <X11/Xproto.h>
49 #include <X11/Xutil.h>
51 #include <X11/extensions/shape.h>
52 #include <X11/extensions/Xfixes.h>
53 #include <X11/extensions/XShm.h>
55 #include "libavutil/internal.h"
56 #include "libavutil/log.h"
57 #include "libavutil/opt.h"
58 #include "libavutil/parseutils.h"
59 #include "libavutil/time.h"
61 #include "libavformat/internal.h"
65 /** X11 device demuxer context */
66 typedef struct X11GrabContext {
67 const AVClass *class; /**< Class for private options. */
68 int frame_size; /**< Size in bytes of a grabbed frame */
69 AVRational time_base; /**< Time base */
70 int64_t time_frame; /**< Current time */
72 int width; /**< Width of the grab frame */
73 int height; /**< Height of the grab frame */
74 int x_off; /**< Horizontal top-left corner coordinate */
75 int y_off; /**< Vertical top-left corner coordinate */
77 Display *dpy; /**< X11 display from which x11grab grabs frames */
78 XImage *image; /**< X11 image holding the grab */
79 int use_shm; /**< !0 when using XShm extension */
80 XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
81 int draw_mouse; /**< Set by a private option. */
82 int follow_mouse; /**< Set by a private option. */
83 int show_region; /**< set by a private option. */
84 AVRational framerate; /**< Set by a private option. */
86 uint32_t palette[256];
89 Window region_win; /**< This is used by show_region option. */
92 #define REGION_WIN_BORDER 3
95 * Draw grabbing region window
97 * @param s x11grab context
99 static void x11grab_draw_region_win(X11GrabContext *s)
101 Display *dpy = s->dpy;
102 Window win = s->region_win;
103 int screen = DefaultScreen(dpy);
104 GC gc = XCreateGC(dpy, win, 0, 0);
106 XSetForeground(dpy, gc, WhitePixel(dpy, screen));
107 XSetBackground(dpy, gc, BlackPixel(dpy, screen));
108 XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
109 XDrawRectangle(dpy, win, gc, 1, 1,
110 (s->width + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
111 (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
116 * Initialize grabbing region window
118 * @param s x11grab context
120 static void x11grab_region_win_init(X11GrabContext *s)
122 Display *dpy = s->dpy;
124 XSetWindowAttributes attribs = { .override_redirect = True };
125 int screen = DefaultScreen(dpy);
127 s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
128 s->x_off - REGION_WIN_BORDER,
129 s->y_off - REGION_WIN_BORDER,
130 s->width + REGION_WIN_BORDER * 2,
131 s->height + REGION_WIN_BORDER * 2,
133 InputOutput, CopyFromParent,
134 CWOverrideRedirect, &attribs);
137 rect.width = s->width;
138 rect.height = s->height;
139 XShapeCombineRectangles(dpy, s->region_win,
140 ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
141 &rect, 1, ShapeSubtract, 0);
142 XMapWindow(dpy, s->region_win);
143 XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
144 x11grab_draw_region_win(s);
147 static int setup_shm(AVFormatContext *s, Display *dpy, XImage **image)
149 X11GrabContext *g = s->priv_data;
150 int scr = XDefaultScreen(dpy);
151 XImage *img = XShmCreateImage(dpy, DefaultVisual(dpy, scr),
152 DefaultDepth(dpy, scr), ZPixmap, NULL,
153 &g->shminfo, g->width, g->height);
155 g->shminfo.shmid = shmget(IPC_PRIVATE, img->bytes_per_line * img->height,
158 if (g->shminfo.shmid == -1) {
159 av_log(s, AV_LOG_ERROR, "Cannot get shared memory!\n");
160 return AVERROR(ENOMEM);
163 g->shminfo.shmaddr = img->data = shmat(g->shminfo.shmid, 0, 0);
164 g->shminfo.readOnly = False;
166 if (!XShmAttach(dpy, &g->shminfo)) {
167 av_log(s, AV_LOG_ERROR, "Failed to attach shared memory!\n");
168 /* needs some better error subroutine :) */
176 static int setup_mouse(Display *dpy, int screen)
180 if (XFixesQueryExtension(dpy, &ev_ret, &ev_err)) {
181 Window root = RootWindow(dpy, screen);
182 XFixesSelectCursorInput(dpy, root, XFixesDisplayCursorNotifyMask);
186 return AVERROR(ENOSYS);
189 static int pixfmt_from_image(AVFormatContext *s, XImage *image, int *pix_fmt)
191 av_log(s, AV_LOG_DEBUG,
192 "Image r 0x%.6lx g 0x%.6lx b 0x%.6lx and depth %i\n",
196 image->bits_per_pixel);
198 *pix_fmt = AV_PIX_FMT_NONE;
200 switch (image->bits_per_pixel) {
202 *pix_fmt = AV_PIX_FMT_PAL8;
205 if (image->red_mask == 0xf800 &&
206 image->green_mask == 0x07e0 &&
207 image->blue_mask == 0x001f) {
208 *pix_fmt = AV_PIX_FMT_RGB565;
209 } else if (image->red_mask == 0x7c00 &&
210 image->green_mask == 0x03e0 &&
211 image->blue_mask == 0x001f) {
212 *pix_fmt = AV_PIX_FMT_RGB555;
216 if (image->red_mask == 0xff0000 &&
217 image->green_mask == 0x00ff00 &&
218 image->blue_mask == 0x0000ff) {
219 *pix_fmt = AV_PIX_FMT_BGR24;
220 } else if (image->red_mask == 0x0000ff &&
221 image->green_mask == 0x00ff00 &&
222 image->blue_mask == 0xff0000) {
223 *pix_fmt = AV_PIX_FMT_RGB24;
227 if (image->red_mask == 0xff0000 &&
228 image->green_mask == 0x00ff00 &&
229 image->blue_mask == 0x0000ff ) {
230 *pix_fmt = AV_PIX_FMT_0RGB32;
234 if (*pix_fmt == AV_PIX_FMT_NONE) {
235 av_log(s, AV_LOG_ERROR,
236 "XImages with RGB mask 0x%.6lx 0x%.6lx 0x%.6lx and depth %i "
237 "are currently not supported.\n",
241 image->bits_per_pixel);
243 return AVERROR_PATCHWELCOME;
250 * Initialize the x11 grab device demuxer (public device demuxer API).
252 * @param s1 Context from avformat core
254 * <li>AVERROR(ENOMEM) no memory left</li>
255 * <li>AVERROR(EIO) other failure case</li>
259 static int x11grab_read_header(AVFormatContext *s1)
261 X11GrabContext *x11grab = s1->priv_data;
265 int x_off = 0, y_off = 0, ret = 0, screen, use_shm = 0;
266 char *dpyname, *offset;
271 dpyname = av_strdup(s1->filename);
275 offset = strchr(dpyname, '+');
277 sscanf(offset, "%d,%d", &x_off, &y_off);
278 if (strstr(offset, "nomouse")) {
279 av_log(s1, AV_LOG_WARNING,
280 "'nomouse' specification in argument is deprecated: "
281 "use 'draw_mouse' option with value 0 instead\n");
282 x11grab->draw_mouse = 0;
287 av_log(s1, AV_LOG_INFO,
288 "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
289 s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);
291 dpy = XOpenDisplay(dpyname);
294 av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
299 st = avformat_new_stream(s1, NULL);
301 ret = AVERROR(ENOMEM);
304 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
306 screen = DefaultScreen(dpy);
308 if (x11grab->follow_mouse) {
309 int screen_w, screen_h;
312 screen_w = DisplayWidth(dpy, screen);
313 screen_h = DisplayHeight(dpy, screen);
314 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off,
316 x_off -= x11grab->width / 2;
317 y_off -= x11grab->height / 2;
318 x_off = av_clip(x_off, 0, screen_w - x11grab->width);
319 y_off = av_clip(y_off, 0, screen_h - x11grab->height);
320 av_log(s1, AV_LOG_INFO,
321 "followmouse is enabled, resetting grabbing region to x: %d y: %d\n",
325 if (x11grab->use_shm) {
326 use_shm = XShmQueryExtension(dpy);
327 av_log(s1, AV_LOG_INFO,
328 "shared memory extension %sfound\n", use_shm ? "" : "not ");
331 if (use_shm && setup_shm(s1, dpy, &image) < 0) {
332 av_log(s1, AV_LOG_WARNING, "Falling back to XGetImage\n");
337 image = XGetImage(dpy, RootWindow(dpy, screen),
339 x11grab->width, x11grab->height,
343 if (x11grab->draw_mouse && setup_mouse(dpy, screen) < 0) {
344 av_log(s1, AV_LOG_WARNING,
345 "XFixes not available, cannot draw the mouse cursor\n");
346 x11grab->draw_mouse = 0;
349 x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel / 8;
351 x11grab->time_base = av_inv_q(x11grab->framerate);
352 x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
353 x11grab->x_off = x_off;
354 x11grab->y_off = y_off;
355 x11grab->image = image;
356 x11grab->use_shm = use_shm;
358 ret = pixfmt_from_image(s1, image, &st->codec->pix_fmt);
362 if (st->codec->pix_fmt == AV_PIX_FMT_PAL8) {
363 color_map = DefaultColormap(dpy, screen);
364 for (i = 0; i < 256; ++i)
366 XQueryColors(dpy, color_map, color, 256);
367 for (i = 0; i < 256; ++i)
368 x11grab->palette[i] = (color[i].red & 0xFF00) << 8 |
369 (color[i].green & 0xFF00) |
370 (color[i].blue & 0xFF00) >> 8;
371 x11grab->palette_changed = 1;
375 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
376 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
377 st->codec->width = x11grab->width;
378 st->codec->height = x11grab->height;
379 st->codec->time_base = x11grab->time_base;
380 st->codec->bit_rate = x11grab->frame_size * 1 / av_q2d(x11grab->time_base) * 8;
388 * Paint a mouse pointer in an X11 image.
390 * @param image image to paint the mouse pointer to
391 * @param s context used to retrieve original grabbing rectangle
394 static void paint_mouse_pointer(XImage *image, AVFormatContext *s1)
396 X11GrabContext *s = s1->priv_data;
397 int x_off = s->x_off;
398 int y_off = s->y_off;
399 int width = s->width;
400 int height = s->height;
401 Display *dpy = s->dpy;
402 XFixesCursorImage *xcim;
405 int to_line, to_column;
406 int pixstride = image->bits_per_pixel >> 3;
407 /* Warning: in its insanity, xlib provides unsigned image data through a
408 * char* pointer, so we have to make it uint8_t to make things not break.
409 * Anyone who performs further investigation of the xlib API likely risks
410 * permanent brain damage. */
411 uint8_t *pix = image->data;
413 XSetWindowAttributes attr;
415 /* Code doesn't currently support 16-bit or PAL8 */
416 if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
420 s->c = XCreateFontCursor(dpy, XC_left_ptr);
421 root = DefaultRootWindow(dpy);
423 XChangeWindowAttributes(dpy, root, CWCursor, &attr);
425 xcim = XFixesGetCursorImage(dpy);
427 av_log(s1, AV_LOG_WARNING,
428 "XFixesGetCursorImage failed\n");
432 x = xcim->x - xcim->xhot;
433 y = xcim->y - xcim->yhot;
435 to_line = FFMIN((y + xcim->height), (height + y_off));
436 to_column = FFMIN((x + xcim->width), (width + x_off));
438 for (line = FFMAX(y, y_off); line < to_line; line++) {
439 for (column = FFMAX(x, x_off); column < to_column; column++) {
440 int xcim_addr = (line - y) * xcim->width + column - x;
441 int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
442 int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
443 int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
444 int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
445 int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
448 pix[image_addr + 0] = r;
449 pix[image_addr + 1] = g;
450 pix[image_addr + 2] = b;
452 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
453 pix[image_addr + 0] = r + (pix[image_addr + 0] * (255 - a) + 255 / 2) / 255;
454 pix[image_addr + 1] = g + (pix[image_addr + 1] * (255 - a) + 255 / 2) / 255;
455 pix[image_addr + 2] = b + (pix[image_addr + 2] * (255 - a) + 255 / 2) / 255;
465 * Read new data in the image structure.
467 * @param dpy X11 display to grab from
469 * @param image Image where the grab will be put
470 * @param x Top-Left grabbing rectangle horizontal coordinate
471 * @param y Top-Left grabbing rectangle vertical coordinate
472 * @return 0 if error, !0 if successful
474 static int xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
484 GetReq(GetImage, req);
486 /* First set up the standard stuff in the request */
490 req->width = image->width;
491 req->height = image->height;
492 req->planeMask = (unsigned int)AllPlanes;
493 req->format = ZPixmap;
495 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
501 nbytes = (long)rep.length << 2;
502 _XReadPad(dpy, image->data, nbytes);
510 * Grab a frame from x11 (public device demuxer API).
512 * @param s1 Context from avformat core
513 * @param pkt Packet holding the brabbed frame
514 * @return frame size in bytes
516 static int x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
518 X11GrabContext *s = s1->priv_data;
519 Display *dpy = s->dpy;
520 XImage *image = s->image;
521 int x_off = s->x_off;
522 int y_off = s->y_off;
523 int follow_mouse = s->follow_mouse;
524 int screen, pointer_x, pointer_y, _, same_screen = 1;
526 int64_t curtime, delay;
529 /* Calculate the time of the next frame */
530 s->time_frame += INT64_C(1000000);
532 /* wait based on the frame rate */
534 curtime = av_gettime();
535 delay = s->time_frame * av_q2d(s->time_base) - curtime;
537 if (delay < INT64_C(-1000000) * av_q2d(s->time_base))
538 s->time_frame += INT64_C(1000000);
541 ts.tv_sec = delay / 1000000;
542 ts.tv_nsec = (delay % 1000000) * 1000;
543 nanosleep(&ts, NULL);
547 pkt->data = image->data;
548 pkt->size = s->frame_size;
550 if (s->palette_changed) {
551 uint8_t *pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
554 av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n");
556 memcpy(pal, s->palette, AVPALETTE_SIZE);
557 s->palette_changed = 0;
561 screen = DefaultScreen(dpy);
562 root = RootWindow(dpy, screen);
564 if (follow_mouse || s->draw_mouse)
565 same_screen = XQueryPointer(dpy, root, &w, &w,
566 &pointer_x, &pointer_y, &_, &_, &_);
568 if (follow_mouse && same_screen) {
569 int screen_w, screen_h;
571 screen_w = DisplayWidth(dpy, screen);
572 screen_h = DisplayHeight(dpy, screen);
573 if (follow_mouse == -1) {
574 // follow the mouse, put it at center of grabbing region
575 x_off += pointer_x - s->width / 2 - x_off;
576 y_off += pointer_y - s->height / 2 - y_off;
578 // follow the mouse, but only move the grabbing region when mouse
579 // reaches within certain pixels to the edge.
580 if (pointer_x > x_off + s->width - follow_mouse)
581 x_off += pointer_x - (x_off + s->width - follow_mouse);
582 else if (pointer_x < x_off + follow_mouse)
583 x_off -= (x_off + follow_mouse) - pointer_x;
584 if (pointer_y > y_off + s->height - follow_mouse)
585 y_off += pointer_y - (y_off + s->height - follow_mouse);
586 else if (pointer_y < y_off + follow_mouse)
587 y_off -= (y_off + follow_mouse) - pointer_y;
589 // adjust grabbing region position if it goes out of screen.
590 s->x_off = x_off = av_clip(x_off, 0, screen_w - s->width);
591 s->y_off = y_off = av_clip(y_off, 0, screen_h - s->height);
593 if (s->show_region && s->region_win)
594 XMoveWindow(dpy, s->region_win,
595 s->x_off - REGION_WIN_BORDER,
596 s->y_off - REGION_WIN_BORDER);
599 if (s->show_region && same_screen) {
601 XEvent evt = { .type = NoEventMask };
602 // Clean up the events, and do the initial draw or redraw.
603 while (XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask,
607 x11grab_draw_region_win(s);
609 x11grab_region_win_init(s);
614 if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes))
615 av_log(s1, AV_LOG_INFO, "XShmGetImage() failed\n");
617 if (!xget_zpixmap(dpy, root, image, x_off, y_off))
618 av_log(s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
621 if (s->draw_mouse && same_screen)
622 paint_mouse_pointer(image, s1);
624 return s->frame_size;
628 * Close x11 frame grabber (public device demuxer API).
630 * @param s1 Context from avformat core
631 * @return 0 success, !0 failure
633 static int x11grab_read_close(AVFormatContext *s1)
635 X11GrabContext *x11grab = s1->priv_data;
637 /* Detach cleanly from shared mem */
638 if (x11grab->use_shm) {
639 XShmDetach(x11grab->dpy, &x11grab->shminfo);
640 shmdt(x11grab->shminfo.shmaddr);
641 shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
644 /* Destroy X11 image */
645 if (x11grab->image) {
646 XDestroyImage(x11grab->image);
647 x11grab->image = NULL;
650 if (x11grab->region_win)
651 XDestroyWindow(x11grab->dpy, x11grab->region_win);
653 /* Free X11 display */
654 XCloseDisplay(x11grab->dpy);
658 #define OFFSET(x) offsetof(X11GrabContext, x)
659 #define DEC AV_OPT_FLAG_DECODING_PARAM
660 static const AVOption options[] = {
661 { "grab_x", "Initial x coordinate.", OFFSET(x_off), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, DEC },
662 { "grab_y", "Initial y coordinate.", OFFSET(y_off), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, DEC },
663 { "draw_mouse", "draw the mouse pointer", OFFSET(draw_mouse), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
665 { "follow_mouse", "move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region",
666 OFFSET(follow_mouse), AV_OPT_TYPE_INT, {.i64 = 0}, -1, INT_MAX, DEC, "follow_mouse" },
667 { "centered", "keep the mouse pointer at the center of grabbing region when following",
668 0, AV_OPT_TYPE_CONST, {.i64 = -1}, INT_MIN, INT_MAX, DEC, "follow_mouse" },
670 { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, 0, DEC },
671 { "show_region", "show the grabbing region", OFFSET(show_region), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
672 { "video_size", "set video frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = "vga"}, 0, 0, DEC },
673 { "use_shm", "use MIT-SHM extension", OFFSET(use_shm), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
677 static const AVClass x11_class = {
678 .class_name = "X11grab indev",
679 .item_name = av_default_item_name,
681 .version = LIBAVUTIL_VERSION_INT,
682 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
685 /** x11 grabber device demuxer declaration */
686 AVInputFormat ff_x11grab_demuxer = {
688 .long_name = NULL_IF_CONFIG_SMALL("X11grab"),
689 .priv_data_size = sizeof(X11GrabContext),
690 .read_header = x11grab_read_header,
691 .read_packet = x11grab_read_packet,
692 .read_close = x11grab_read_close,
693 .flags = AVFMT_NOFILE,
694 .priv_class = &x11_class,