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>
57 #include "libavutil/log.h"
58 #include "libavutil/opt.h"
59 #include "libavutil/parseutils.h"
60 #include "libavutil/time.h"
62 #include "libavformat/internal.h"
64 /** X11 device demuxer context */
65 typedef struct X11GrabContext {
66 const AVClass *class; /**< Class for private options. */
67 int frame_size; /**< Size in bytes of a grabbed frame */
68 AVRational time_base; /**< Time base */
69 int64_t time_frame; /**< Current time */
71 int width; /**< Width of the grab frame */
72 int height; /**< Height of the grab frame */
73 int x_off; /**< Horizontal top-left corner coordinate */
74 int y_off; /**< Vertical top-left corner coordinate */
76 Display *dpy; /**< X11 display from which x11grab grabs frames */
77 XImage *image; /**< X11 image holding the grab */
78 int use_shm; /**< !0 when using XShm extension */
79 XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
80 int draw_mouse; /**< Set by a private option. */
81 int follow_mouse; /**< Set by a private option. */
82 int show_region; /**< set by a private option. */
83 AVRational framerate; /**< Set by a private option. */
85 uint32_t palette[256];
88 Window region_win; /**< This is used by show_region option. */
91 #define REGION_WIN_BORDER 3
94 * Draw grabbing region window
96 * @param s x11grab context
98 static void x11grab_draw_region_win(X11GrabContext *s)
100 Display *dpy = s->dpy;
101 Window win = s->region_win;
102 int screen = DefaultScreen(dpy);
103 GC gc = XCreateGC(dpy, win, 0, 0);
105 XSetForeground(dpy, gc, WhitePixel(dpy, screen));
106 XSetBackground(dpy, gc, BlackPixel(dpy, screen));
107 XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
108 XDrawRectangle(dpy, win, gc, 1, 1,
109 (s->width + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
110 (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
115 * Initialize grabbing region window
117 * @param s x11grab context
119 static void x11grab_region_win_init(X11GrabContext *s)
121 Display *dpy = s->dpy;
123 XSetWindowAttributes attribs = { .override_redirect = True };
124 int screen = DefaultScreen(dpy);
126 s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
127 s->x_off - REGION_WIN_BORDER,
128 s->y_off - REGION_WIN_BORDER,
129 s->width + REGION_WIN_BORDER * 2,
130 s->height + REGION_WIN_BORDER * 2,
132 InputOutput, CopyFromParent,
133 CWOverrideRedirect, &attribs);
136 rect.width = s->width;
137 rect.height = s->height;
138 XShapeCombineRectangles(dpy, s->region_win,
139 ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
140 &rect, 1, ShapeSubtract, 0);
141 XMapWindow(dpy, s->region_win);
142 XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
143 x11grab_draw_region_win(s);
147 * Initialize the x11 grab device demuxer (public device demuxer API).
149 * @param s1 Context from avformat core
151 * <li>AVERROR(ENOMEM) no memory left</li>
152 * <li>AVERROR(EIO) other failure case</li>
156 static int x11grab_read_header(AVFormatContext *s1)
158 X11GrabContext *x11grab = s1->priv_data;
161 enum AVPixelFormat input_pixfmt;
163 int x_off = 0, y_off = 0, ret = 0, screen, use_shm = 0;
164 char *dpyname, *offset;
169 dpyname = av_strdup(s1->filename);
173 offset = strchr(dpyname, '+');
175 sscanf(offset, "%d,%d", &x_off, &y_off);
176 if (strstr(offset, "nomouse")) {
177 av_log(s1, AV_LOG_WARNING,
178 "'nomouse' specification in argument is deprecated: "
179 "use 'draw_mouse' option with value 0 instead\n");
180 x11grab->draw_mouse = 0;
185 av_log(s1, AV_LOG_INFO,
186 "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
187 s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);
189 dpy = XOpenDisplay(dpyname);
192 av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
197 st = avformat_new_stream(s1, NULL);
199 ret = AVERROR(ENOMEM);
202 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
204 screen = DefaultScreen(dpy);
206 if (x11grab->follow_mouse) {
207 int screen_w, screen_h;
210 screen_w = DisplayWidth(dpy, screen);
211 screen_h = DisplayHeight(dpy, screen);
212 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off,
214 x_off -= x11grab->width / 2;
215 y_off -= x11grab->height / 2;
216 x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
217 y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
218 av_log(s1, AV_LOG_INFO,
219 "followmouse is enabled, resetting grabbing region to x: %d y: %d\n",
223 if (x11grab->use_shm) {
224 use_shm = XShmQueryExtension(dpy);
225 av_log(s1, AV_LOG_INFO,
226 "shared memory extension %sfound\n", use_shm ? "" : "not ");
230 int scr = XDefaultScreen(dpy);
231 image = XShmCreateImage(dpy,
232 DefaultVisual(dpy, scr),
233 DefaultDepth(dpy, scr),
237 x11grab->width, x11grab->height);
238 x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
239 image->bytes_per_line * image->height,
241 if (x11grab->shminfo.shmid == -1) {
242 av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
243 ret = AVERROR(ENOMEM);
246 x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
247 x11grab->shminfo.readOnly = False;
249 if (!XShmAttach(dpy, &x11grab->shminfo)) {
250 av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
251 /* needs some better error subroutine :) */
256 image = XGetImage(dpy, RootWindow(dpy, screen),
258 x11grab->width, x11grab->height,
262 switch (image->bits_per_pixel) {
264 av_log(s1, AV_LOG_DEBUG, "8 bit palette\n");
265 input_pixfmt = AV_PIX_FMT_PAL8;
266 color_map = DefaultColormap(dpy, screen);
267 for (i = 0; i < 256; ++i)
269 XQueryColors(dpy, color_map, color, 256);
270 for (i = 0; i < 256; ++i)
271 x11grab->palette[i] = (color[i].red & 0xFF00) << 8 |
272 (color[i].green & 0xFF00) |
273 (color[i].blue & 0xFF00) >> 8;
274 x11grab->palette_changed = 1;
277 if (image->red_mask == 0xf800 &&
278 image->green_mask == 0x07e0 &&
279 image->blue_mask == 0x001f) {
280 av_log(s1, AV_LOG_DEBUG, "16 bit RGB565\n");
281 input_pixfmt = AV_PIX_FMT_RGB565;
282 } else if (image->red_mask == 0x7c00 &&
283 image->green_mask == 0x03e0 &&
284 image->blue_mask == 0x001f) {
285 av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
286 input_pixfmt = AV_PIX_FMT_RGB555;
288 av_log(s1, AV_LOG_ERROR,
289 "RGB ordering at image depth %i not supported ... aborting\n",
290 image->bits_per_pixel);
291 av_log(s1, AV_LOG_ERROR,
292 "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n",
293 image->red_mask, image->green_mask, image->blue_mask);
294 ret = AVERROR_PATCHWELCOME;
299 if (image->red_mask == 0xff0000 &&
300 image->green_mask == 0x00ff00 &&
301 image->blue_mask == 0x0000ff) {
302 input_pixfmt = AV_PIX_FMT_BGR24;
303 } else if (image->red_mask == 0x0000ff &&
304 image->green_mask == 0x00ff00 &&
305 image->blue_mask == 0xff0000) {
306 input_pixfmt = AV_PIX_FMT_RGB24;
308 av_log(s1, AV_LOG_ERROR,
309 "rgb ordering at image depth %i not supported ... aborting\n",
310 image->bits_per_pixel);
311 av_log(s1, AV_LOG_ERROR,
312 "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n",
313 image->red_mask, image->green_mask, image->blue_mask);
314 ret = AVERROR_PATCHWELCOME;
319 if ( image->red_mask == 0xff0000 &&
320 image->green_mask == 0x00ff00 &&
321 image->blue_mask == 0x0000ff ) {
322 input_pixfmt = AV_PIX_FMT_0RGB32;
324 av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
325 av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);
326 ret = AVERROR_PATCHWELCOME;
331 av_log(s1, AV_LOG_ERROR,
332 "image depth %i not supported ... aborting\n",
333 image->bits_per_pixel);
334 ret = AVERROR_PATCHWELCOME;
338 x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel / 8;
340 x11grab->time_base = av_inv_q(x11grab->framerate);
341 x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
342 x11grab->x_off = x_off;
343 x11grab->y_off = y_off;
344 x11grab->image = image;
345 x11grab->use_shm = use_shm;
347 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
348 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
349 st->codec->width = x11grab->width;
350 st->codec->height = x11grab->height;
351 st->codec->pix_fmt = input_pixfmt;
352 st->codec->time_base = x11grab->time_base;
353 st->codec->bit_rate = x11grab->frame_size * 1 / av_q2d(x11grab->time_base) * 8;
361 * Paint a mouse pointer in an X11 image.
363 * @param image image to paint the mouse pointer to
364 * @param s context used to retrieve original grabbing rectangle
367 static void paint_mouse_pointer(XImage *image, AVFormatContext *s1)
369 X11GrabContext *s = s1->priv_data;
370 int x_off = s->x_off;
371 int y_off = s->y_off;
372 int width = s->width;
373 int height = s->height;
374 Display *dpy = s->dpy;
375 XFixesCursorImage *xcim;
378 int to_line, to_column;
379 int pixstride = image->bits_per_pixel >> 3;
380 /* Warning: in its insanity, xlib provides unsigned image data through a
381 * char* pointer, so we have to make it uint8_t to make things not break.
382 * Anyone who performs further investigation of the xlib API likely risks
383 * permanent brain damage. */
384 uint8_t *pix = image->data;
386 XSetWindowAttributes attr;
388 /* Code doesn't currently support 16-bit or PAL8 */
389 if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
393 s->c = XCreateFontCursor(dpy, XC_left_ptr);
394 w = DefaultRootWindow(dpy);
396 XChangeWindowAttributes(dpy, w, CWCursor, &attr);
398 xcim = XFixesGetCursorImage(dpy);
400 av_log(s1, AV_LOG_WARNING,
401 "XFixes extension not available, impossible to draw cursor\n");
406 x = xcim->x - xcim->xhot;
407 y = xcim->y - xcim->yhot;
409 to_line = FFMIN((y + xcim->height), (height + y_off));
410 to_column = FFMIN((x + xcim->width), (width + x_off));
412 for (line = FFMAX(y, y_off); line < to_line; line++) {
413 for (column = FFMAX(x, x_off); column < to_column; column++) {
414 int xcim_addr = (line - y) * xcim->width + column - x;
415 int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
416 int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
417 int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
418 int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
419 int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
422 pix[image_addr + 0] = r;
423 pix[image_addr + 1] = g;
424 pix[image_addr + 2] = b;
426 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
427 pix[image_addr + 0] = r + (pix[image_addr + 0] * (255 - a) + 255 / 2) / 255;
428 pix[image_addr + 1] = g + (pix[image_addr + 1] * (255 - a) + 255 / 2) / 255;
429 pix[image_addr + 2] = b + (pix[image_addr + 2] * (255 - a) + 255 / 2) / 255;
439 * Read new data in the image structure.
441 * @param dpy X11 display to grab from
443 * @param image Image where the grab will be put
444 * @param x Top-Left grabbing rectangle horizontal coordinate
445 * @param y Top-Left grabbing rectangle vertical coordinate
446 * @return 0 if error, !0 if successful
448 static int xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
458 GetReq(GetImage, req);
460 /* First set up the standard stuff in the request */
464 req->width = image->width;
465 req->height = image->height;
466 req->planeMask = (unsigned int)AllPlanes;
467 req->format = ZPixmap;
469 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
475 nbytes = (long)rep.length << 2;
476 _XReadPad(dpy, image->data, nbytes);
484 * Grab a frame from x11 (public device demuxer API).
486 * @param s1 Context from avformat core
487 * @param pkt Packet holding the brabbed frame
488 * @return frame size in bytes
490 static int x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
492 X11GrabContext *s = s1->priv_data;
493 Display *dpy = s->dpy;
494 XImage *image = s->image;
495 int x_off = s->x_off;
496 int y_off = s->y_off;
497 int follow_mouse = s->follow_mouse;
500 int64_t curtime, delay;
503 /* Calculate the time of the next frame */
504 s->time_frame += INT64_C(1000000);
506 /* wait based on the frame rate */
508 curtime = av_gettime();
509 delay = s->time_frame * av_q2d(s->time_base) - curtime;
511 if (delay < INT64_C(-1000000) * av_q2d(s->time_base))
512 s->time_frame += INT64_C(1000000);
515 ts.tv_sec = delay / 1000000;
516 ts.tv_nsec = (delay % 1000000) * 1000;
517 nanosleep(&ts, NULL);
521 pkt->data = image->data;
522 pkt->size = s->frame_size;
524 if (s->palette_changed) {
525 uint8_t *pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
528 av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n");
530 memcpy(pal, s->palette, AVPALETTE_SIZE);
531 s->palette_changed = 0;
535 screen = DefaultScreen(dpy);
536 root = RootWindow(dpy, screen);
538 int screen_w, screen_h;
539 int pointer_x, pointer_y, _;
542 screen_w = DisplayWidth(dpy, screen);
543 screen_h = DisplayHeight(dpy, screen);
544 XQueryPointer(dpy, root, &w, &w, &pointer_x, &pointer_y, &_, &_, &_);
545 if (follow_mouse == -1) {
546 // follow the mouse, put it at center of grabbing region
547 x_off += pointer_x - s->width / 2 - x_off;
548 y_off += pointer_y - s->height / 2 - y_off;
550 // follow the mouse, but only move the grabbing region when mouse
551 // reaches within certain pixels to the edge.
552 if (pointer_x > x_off + s->width - follow_mouse)
553 x_off += pointer_x - (x_off + s->width - follow_mouse);
554 else if (pointer_x < x_off + follow_mouse)
555 x_off -= (x_off + follow_mouse) - pointer_x;
556 if (pointer_y > y_off + s->height - follow_mouse)
557 y_off += pointer_y - (y_off + s->height - follow_mouse);
558 else if (pointer_y < y_off + follow_mouse)
559 y_off -= (y_off + follow_mouse) - pointer_y;
561 // adjust grabbing region position if it goes out of screen.
562 s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);
563 s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);
565 if (s->show_region && s->region_win)
566 XMoveWindow(dpy, s->region_win,
567 s->x_off - REGION_WIN_BORDER,
568 s->y_off - REGION_WIN_BORDER);
571 if (s->show_region) {
573 XEvent evt = { .type = NoEventMask };
574 // Clean up the events, and do the initial draw or redraw.
575 while (XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask,
579 x11grab_draw_region_win(s);
581 x11grab_region_win_init(s);
586 if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes))
587 av_log(s1, AV_LOG_INFO, "XShmGetImage() failed\n");
589 if (!xget_zpixmap(dpy, root, image, x_off, y_off))
590 av_log(s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
594 paint_mouse_pointer(image, s1);
596 return s->frame_size;
600 * Close x11 frame grabber (public device demuxer API).
602 * @param s1 Context from avformat core
603 * @return 0 success, !0 failure
605 static int x11grab_read_close(AVFormatContext *s1)
607 X11GrabContext *x11grab = s1->priv_data;
609 /* Detach cleanly from shared mem */
610 if (x11grab->use_shm) {
611 XShmDetach(x11grab->dpy, &x11grab->shminfo);
612 shmdt(x11grab->shminfo.shmaddr);
613 shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
616 /* Destroy X11 image */
617 if (x11grab->image) {
618 XDestroyImage(x11grab->image);
619 x11grab->image = NULL;
622 if (x11grab->region_win)
623 XDestroyWindow(x11grab->dpy, x11grab->region_win);
625 /* Free X11 display */
626 XCloseDisplay(x11grab->dpy);
630 #define OFFSET(x) offsetof(X11GrabContext, x)
631 #define DEC AV_OPT_FLAG_DECODING_PARAM
632 static const AVOption options[] = {
633 { "draw_mouse", "draw the mouse pointer", OFFSET(draw_mouse), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
635 { "follow_mouse", "move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region",
636 OFFSET(follow_mouse), AV_OPT_TYPE_INT, {.i64 = 0}, -1, INT_MAX, DEC, "follow_mouse" },
637 { "centered", "keep the mouse pointer at the center of grabbing region when following",
638 0, AV_OPT_TYPE_CONST, {.i64 = -1}, INT_MIN, INT_MAX, DEC, "follow_mouse" },
640 { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, 0, DEC },
641 { "show_region", "show the grabbing region", OFFSET(show_region), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
642 { "video_size", "set video frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = "vga"}, 0, 0, DEC },
643 { "use_shm", "use MIT-SHM extension", OFFSET(use_shm), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
647 static const AVClass x11_class = {
648 .class_name = "X11grab indev",
649 .item_name = av_default_item_name,
651 .version = LIBAVUTIL_VERSION_INT,
652 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
655 /** x11 grabber device demuxer declaration */
656 AVInputFormat ff_x11grab_demuxer = {
658 .long_name = NULL_IF_CONFIG_SMALL("X11grab"),
659 .priv_data_size = sizeof(X11GrabContext),
660 .read_header = x11grab_read_header,
661 .read_packet = x11grab_read_packet,
662 .read_close = x11grab_read_close,
663 .flags = AVFMT_NOFILE,
664 .priv_class = &x11_class,