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>
40 #include "libavformat/internal.h"
41 #include "libavutil/log.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/parseutils.h"
44 #include "libavutil/time.h"
46 #include <X11/cursorfont.h>
49 #include <X11/Xlibint.h>
50 #include <X11/Xproto.h>
51 #include <X11/Xutil.h>
53 #include <X11/extensions/shape.h>
54 #include <X11/extensions/XShm.h>
55 #include <X11/extensions/Xfixes.h>
59 * X11 Device Demuxer context
62 const AVClass *class; /**< Class for private options. */
63 int frame_size; /**< Size in bytes of a grabbed frame */
64 AVRational time_base; /**< Time base */
65 int64_t time_frame; /**< Current time */
67 int width; /**< Width of the grab frame */
68 int height; /**< Height of the grab frame */
69 int x_off; /**< Horizontal top-left corner coordinate */
70 int y_off; /**< Vertical top-left corner coordinate */
72 Display *dpy; /**< X11 display from which x11grab grabs frames */
73 XImage *image; /**< X11 image holding the grab */
74 int use_shm; /**< !0 when using XShm extension */
75 XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
76 int draw_mouse; /**< Set by a private option. */
77 int follow_mouse; /**< Set by a private option. */
78 int show_region; /**< set by a private option. */
79 AVRational framerate; /**< Set by a private option. */
81 uint32_t palette[256];
84 Window region_win; /**< This is used by show_region option. */
87 #define REGION_WIN_BORDER 3
89 * Draw grabbing region window
91 * @param s x11grab context
94 x11grab_draw_region_win(struct x11grab *s)
96 Display *dpy = s->dpy;
98 Window win = s->region_win;
101 screen = DefaultScreen(dpy);
102 gc = XCreateGC(dpy, win, 0, 0);
103 XSetForeground(dpy, gc, WhitePixel(dpy, screen));
104 XSetBackground(dpy, gc, BlackPixel(dpy, screen));
105 XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
106 XDrawRectangle(dpy, win, gc,
108 (s->width + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
109 (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
114 * Initialize grabbing region window
116 * @param s x11grab context
119 x11grab_region_win_init(struct x11grab *s)
121 Display *dpy = s->dpy;
123 XSetWindowAttributes attribs;
126 screen = DefaultScreen(dpy);
127 attribs.override_redirect = True;
128 s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
129 s->x_off - REGION_WIN_BORDER,
130 s->y_off - REGION_WIN_BORDER,
131 s->width + REGION_WIN_BORDER * 2,
132 s->height + REGION_WIN_BORDER * 2,
134 InputOutput, CopyFromParent,
135 CWOverrideRedirect, &attribs);
138 rect.width = s->width;
139 rect.height = s->height;
140 XShapeCombineRectangles(dpy, s->region_win,
141 ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
142 &rect, 1, ShapeSubtract, 0);
143 XMapWindow(dpy, s->region_win);
144 XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
145 x11grab_draw_region_win(s);
149 * Initialize the x11 grab device demuxer (public device demuxer API).
151 * @param s1 Context from avformat core
153 * <li>AVERROR(ENOMEM) no memory left</li>
154 * <li>AVERROR(EIO) other failure case</li>
159 x11grab_read_header(AVFormatContext *s1)
161 struct x11grab *x11grab = s1->priv_data;
164 enum AVPixelFormat input_pixfmt;
170 char *dpyname, *offset;
176 dpyname = av_strdup(s1->filename);
180 offset = strchr(dpyname, '+');
182 sscanf(offset, "%d,%d", &x_off, &y_off);
183 if (strstr(offset, "nomouse")) {
184 av_log(s1, AV_LOG_WARNING,
185 "'nomouse' specification in argument is deprecated: "
186 "use 'draw_mouse' option with value 0 instead\n");
187 x11grab->draw_mouse = 0;
192 av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
193 s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);
195 dpy = XOpenDisplay(dpyname);
198 av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
203 st = avformat_new_stream(s1, NULL);
205 ret = AVERROR(ENOMEM);
208 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
210 screen = DefaultScreen(dpy);
212 if (x11grab->follow_mouse) {
213 int screen_w, screen_h;
216 screen_w = DisplayWidth(dpy, screen);
217 screen_h = DisplayHeight(dpy, screen);
218 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret);
219 x_off -= x11grab->width / 2;
220 y_off -= x11grab->height / 2;
221 x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
222 y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
223 av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off);
226 if (x11grab->use_shm) {
227 use_shm = XShmQueryExtension(dpy);
228 av_log(s1, AV_LOG_INFO, "shared memory extension%s found\n", use_shm ? "" : " not");
232 int scr = XDefaultScreen(dpy);
233 image = XShmCreateImage(dpy,
234 DefaultVisual(dpy, scr),
235 DefaultDepth(dpy, scr),
239 x11grab->width, x11grab->height);
240 x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
241 image->bytes_per_line * image->height,
243 if (x11grab->shminfo.shmid == -1) {
244 av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
245 ret = AVERROR(ENOMEM);
248 x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
249 x11grab->shminfo.readOnly = False;
251 if (!XShmAttach(dpy, &x11grab->shminfo)) {
252 av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
253 /* needs some better error subroutine :) */
258 image = XGetImage(dpy, RootWindow(dpy, screen),
260 x11grab->width, x11grab->height,
264 switch (image->bits_per_pixel) {
266 av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
267 input_pixfmt = AV_PIX_FMT_PAL8;
268 color_map = DefaultColormap(dpy, screen);
269 for (i = 0; i < 256; ++i)
271 XQueryColors(dpy, color_map, color, 256);
272 for (i = 0; i < 256; ++i)
273 x11grab->palette[i] = (color[i].red & 0xFF00) << 8 |
274 (color[i].green & 0xFF00) |
275 (color[i].blue & 0xFF00) >> 8;
276 x11grab->palette_changed = 1;
279 if ( image->red_mask == 0xf800 &&
280 image->green_mask == 0x07e0 &&
281 image->blue_mask == 0x001f ) {
282 av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
283 input_pixfmt = AV_PIX_FMT_RGB565;
284 } else if (image->red_mask == 0x7c00 &&
285 image->green_mask == 0x03e0 &&
286 image->blue_mask == 0x001f ) {
287 av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
288 input_pixfmt = AV_PIX_FMT_RGB555;
290 av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
291 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);
292 ret = AVERROR_PATCHWELCOME;
297 if ( image->red_mask == 0xff0000 &&
298 image->green_mask == 0x00ff00 &&
299 image->blue_mask == 0x0000ff ) {
300 input_pixfmt = AV_PIX_FMT_BGR24;
301 } else if ( image->red_mask == 0x0000ff &&
302 image->green_mask == 0x00ff00 &&
303 image->blue_mask == 0xff0000 ) {
304 input_pixfmt = AV_PIX_FMT_RGB24;
306 av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
307 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);
308 ret = AVERROR_PATCHWELCOME;
313 if ( image->red_mask == 0xff0000 &&
314 image->green_mask == 0x00ff00 &&
315 image->blue_mask == 0x0000ff ) {
316 input_pixfmt = AV_PIX_FMT_0RGB32;
318 av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
319 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);
320 ret = AVERROR_PATCHWELCOME;
325 av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
326 ret = AVERROR_PATCHWELCOME;
330 x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
332 x11grab->time_base = av_inv_q(x11grab->framerate);
333 x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
334 x11grab->x_off = x_off;
335 x11grab->y_off = y_off;
336 x11grab->image = image;
337 x11grab->use_shm = use_shm;
339 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
340 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
341 st->codec->width = x11grab->width;
342 st->codec->height = x11grab->height;
343 st->codec->pix_fmt = input_pixfmt;
344 st->codec->time_base = x11grab->time_base;
345 st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;
353 * Paint a mouse pointer in an X11 image.
355 * @param image image to paint the mouse pointer to
356 * @param s context used to retrieve original grabbing rectangle
360 paint_mouse_pointer(XImage *image, AVFormatContext *s1)
362 struct x11grab *s = s1->priv_data;
363 int x_off = s->x_off;
364 int y_off = s->y_off;
365 int width = s->width;
366 int height = s->height;
367 Display *dpy = s->dpy;
368 XFixesCursorImage *xcim;
371 int to_line, to_column;
372 int pixstride = image->bits_per_pixel >> 3;
373 /* Warning: in its insanity, xlib provides unsigned image data through a
374 * char* pointer, so we have to make it uint8_t to make things not break.
375 * Anyone who performs further investigation of the xlib API likely risks
376 * permanent brain damage. */
377 uint8_t *pix = image->data;
379 XSetWindowAttributes attr;
381 /* Code doesn't currently support 16-bit or PAL8 */
382 if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
386 s->c = XCreateFontCursor(dpy, XC_left_ptr);
387 w = DefaultRootWindow(dpy);
389 XChangeWindowAttributes(dpy, w, CWCursor, &attr);
391 xcim = XFixesGetCursorImage(dpy);
393 av_log(s1, AV_LOG_WARNING,
394 "XFixes extension not available, impossible to draw cursor\n");
399 x = xcim->x - xcim->xhot;
400 y = xcim->y - xcim->yhot;
402 to_line = FFMIN((y + xcim->height), (height + y_off));
403 to_column = FFMIN((x + xcim->width), (width + x_off));
405 for (line = FFMAX(y, y_off); line < to_line; line++) {
406 for (column = FFMAX(x, x_off); column < to_column; column++) {
407 int xcim_addr = (line - y) * xcim->width + column - x;
408 int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
409 int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
410 int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
411 int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
412 int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
415 pix[image_addr+0] = r;
416 pix[image_addr+1] = g;
417 pix[image_addr+2] = b;
419 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
420 pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
421 pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
422 pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
433 * Read new data in the image structure.
435 * @param dpy X11 display to grab from
437 * @param image Image where the grab will be put
438 * @param x Top-Left grabbing rectangle horizontal coordinate
439 * @param y Top-Left grabbing rectangle vertical coordinate
440 * @return 0 if error, !0 if successful
443 xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
454 GetReq(GetImage, req);
456 /* First set up the standard stuff in the request */
460 req->width = image->width;
461 req->height = image->height;
462 req->planeMask = (unsigned int)AllPlanes;
463 req->format = ZPixmap;
465 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
471 nbytes = (long)rep.length << 2;
472 _XReadPad(dpy, image->data, nbytes);
480 * Grab a frame from x11 (public device demuxer API).
482 * @param s1 Context from avformat core
483 * @param pkt Packet holding the brabbed frame
484 * @return frame size in bytes
487 x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
489 struct x11grab *s = s1->priv_data;
490 Display *dpy = s->dpy;
491 XImage *image = s->image;
492 int x_off = s->x_off;
493 int y_off = s->y_off;
497 int follow_mouse = s->follow_mouse;
499 int64_t curtime, delay;
502 /* Calculate the time of the next frame */
503 s->time_frame += INT64_C(1000000);
505 /* wait based on the frame rate */
507 curtime = av_gettime();
508 delay = s->time_frame * av_q2d(s->time_base) - curtime;
510 if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
511 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) {
574 // clean up the events, and do the initinal draw or redraw.
575 for (evt.type = NoEventMask; XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask, &evt); );
577 x11grab_draw_region_win(s);
579 x11grab_region_win_init(s);
584 if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes)) {
585 av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
588 if (!xget_zpixmap(dpy, root, image, x_off, y_off)) {
589 av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
594 paint_mouse_pointer(image, s1);
597 return s->frame_size;
601 * Close x11 frame grabber (public device demuxer API).
603 * @param s1 Context from avformat core
604 * @return 0 success, !0 failure
607 x11grab_read_close(AVFormatContext *s1)
609 struct x11grab *x11grab = s1->priv_data;
611 /* Detach cleanly from shared mem */
612 if (x11grab->use_shm) {
613 XShmDetach(x11grab->dpy, &x11grab->shminfo);
614 shmdt(x11grab->shminfo.shmaddr);
615 shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
618 /* Destroy X11 image */
619 if (x11grab->image) {
620 XDestroyImage(x11grab->image);
621 x11grab->image = NULL;
624 if (x11grab->region_win) {
625 XDestroyWindow(x11grab->dpy, x11grab->region_win);
628 /* Free X11 display */
629 XCloseDisplay(x11grab->dpy);
633 #define OFFSET(x) offsetof(struct x11grab, x)
634 #define DEC AV_OPT_FLAG_DECODING_PARAM
635 static const AVOption options[] = {
636 { "draw_mouse", "draw the mouse pointer", OFFSET(draw_mouse), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
638 { "follow_mouse", "move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region",
639 OFFSET(follow_mouse), AV_OPT_TYPE_INT, {.i64 = 0}, -1, INT_MAX, DEC, "follow_mouse" },
640 { "centered", "keep the mouse pointer at the center of grabbing region when following",
641 0, AV_OPT_TYPE_CONST, {.i64 = -1}, INT_MIN, INT_MAX, DEC, "follow_mouse" },
643 { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, 0, DEC },
644 { "show_region", "show the grabbing region", OFFSET(show_region), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
645 { "video_size", "set video frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = "vga"}, 0, 0, DEC },
646 { "use_shm", "use MIT-SHM extension", OFFSET(use_shm), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
650 static const AVClass x11_class = {
651 .class_name = "X11grab indev",
652 .item_name = av_default_item_name,
654 .version = LIBAVUTIL_VERSION_INT,
655 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
658 /** x11 grabber device demuxer declaration */
659 AVInputFormat ff_x11grab_demuxer = {
661 .long_name = NULL_IF_CONFIG_SMALL("X11grab"),
662 .priv_data_size = sizeof(struct x11grab),
663 .read_header = x11grab_read_header,
664 .read_packet = x11grab_read_packet,
665 .read_close = x11grab_read_close,
666 .flags = AVFMT_NOFILE,
667 .priv_class = &x11_class,