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"
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/XShm.h>
53 #include <X11/extensions/Xfixes.h>
57 * X11 Device Demuxer context
61 const AVClass *class; /**< Class for private options. */
62 int frame_size; /**< Size in bytes of a grabbed frame */
63 AVRational time_base; /**< Time base */
64 int64_t time_frame; /**< Current time */
66 char *video_size; /**< String describing video size, set by a private option. */
67 int height; /**< Height of the grab frame */
68 int width; /**< Width 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 char *framerate; /**< Set by a private option. */
81 Window region_win; /**< This is used by show_region option. */
84 #define REGION_WIN_BORDER 3
86 * Draw grabbing region window
88 * @param s x11_grab context
91 x11grab_draw_region_win(struct x11_grab *s)
93 Display *dpy = s->dpy;
95 Window win = s->region_win;
98 screen = DefaultScreen(dpy);
99 gc = XCreateGC(dpy, win, 0, 0);
100 XSetForeground(dpy, gc, WhitePixel(dpy, screen));
101 XSetBackground(dpy, gc, BlackPixel(dpy, screen));
102 XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
103 XDrawRectangle(dpy, win, gc,
105 (s->width + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
106 (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
111 * Initialize grabbing region window
113 * @param s x11_grab context
116 x11grab_region_win_init(struct x11_grab *s)
118 Display *dpy = s->dpy;
120 XSetWindowAttributes attribs;
123 screen = DefaultScreen(dpy);
124 attribs.override_redirect = True;
125 s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
126 s->x_off - REGION_WIN_BORDER,
127 s->y_off - REGION_WIN_BORDER,
128 s->width + REGION_WIN_BORDER * 2,
129 s->height + REGION_WIN_BORDER * 2,
131 InputOutput, CopyFromParent,
132 CWOverrideRedirect, &attribs);
135 rect.width = s->width;
136 rect.height = s->height;
137 XShapeCombineRectangles(dpy, s->region_win,
138 ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
139 &rect, 1, ShapeSubtract, 0);
140 XMapWindow(dpy, s->region_win);
141 XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
142 x11grab_draw_region_win(s);
146 * Initialize the x11 grab device demuxer (public device demuxer API).
148 * @param s1 Context from avformat core
150 * <li>AVERROR(ENOMEM) no memory left</li>
151 * <li>AVERROR(EIO) other failure case</li>
156 x11grab_read_header(AVFormatContext *s1)
158 struct x11_grab *x11grab = s1->priv_data;
161 enum PixelFormat input_pixfmt;
167 char *dpyname, *offset;
169 AVRational framerate;
171 dpyname = av_strdup(s1->filename);
175 offset = strchr(dpyname, '+');
177 sscanf(offset, "%d,%d", &x_off, &y_off);
178 x11grab->draw_mouse = !strstr(offset, "nomouse");
182 if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) {
183 av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
186 if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) {
187 av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate);
190 av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
191 s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);
193 dpy = XOpenDisplay(dpyname);
196 av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
201 st = avformat_new_stream(s1, NULL);
203 ret = AVERROR(ENOMEM);
206 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
208 screen = DefaultScreen(dpy);
210 if (x11grab->follow_mouse) {
211 int screen_w, screen_h;
214 screen_w = DisplayWidth(dpy, screen);
215 screen_h = DisplayHeight(dpy, screen);
216 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret);
217 x_off -= x11grab->width / 2;
218 y_off -= x11grab->height / 2;
219 x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
220 y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
221 av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off);
224 use_shm = XShmQueryExtension(dpy);
225 av_log(s1, AV_LOG_INFO, "shared memory extension%s found\n", use_shm ? "" : " not");
228 int scr = XDefaultScreen(dpy);
229 image = XShmCreateImage(dpy,
230 DefaultVisual(dpy, scr),
231 DefaultDepth(dpy, scr),
235 x11grab->width, x11grab->height);
236 x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
237 image->bytes_per_line * image->height,
239 if (x11grab->shminfo.shmid == -1) {
240 av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
241 ret = AVERROR(ENOMEM);
244 x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
245 x11grab->shminfo.readOnly = False;
247 if (!XShmAttach(dpy, &x11grab->shminfo)) {
248 av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
249 /* needs some better error subroutine :) */
254 image = XGetImage(dpy, RootWindow(dpy, screen),
256 x11grab->width, x11grab->height,
260 switch (image->bits_per_pixel) {
262 av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
263 input_pixfmt = PIX_FMT_PAL8;
266 if ( image->red_mask == 0xf800 &&
267 image->green_mask == 0x07e0 &&
268 image->blue_mask == 0x001f ) {
269 av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
270 input_pixfmt = PIX_FMT_RGB565;
271 } else if (image->red_mask == 0x7c00 &&
272 image->green_mask == 0x03e0 &&
273 image->blue_mask == 0x001f ) {
274 av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
275 input_pixfmt = PIX_FMT_RGB555;
277 av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
278 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);
284 if ( image->red_mask == 0xff0000 &&
285 image->green_mask == 0x00ff00 &&
286 image->blue_mask == 0x0000ff ) {
287 input_pixfmt = PIX_FMT_BGR24;
288 } else if ( image->red_mask == 0x0000ff &&
289 image->green_mask == 0x00ff00 &&
290 image->blue_mask == 0xff0000 ) {
291 input_pixfmt = PIX_FMT_RGB24;
293 av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
294 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);
300 input_pixfmt = PIX_FMT_0RGB32;
303 av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
304 ret = AVERROR(EINVAL);
308 x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
310 x11grab->time_base = (AVRational){framerate.den, framerate.num};
311 x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
312 x11grab->x_off = x_off;
313 x11grab->y_off = y_off;
314 x11grab->image = image;
315 x11grab->use_shm = use_shm;
317 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
318 st->codec->codec_id = CODEC_ID_RAWVIDEO;
319 st->codec->width = x11grab->width;
320 st->codec->height = x11grab->height;
321 st->codec->pix_fmt = input_pixfmt;
322 st->codec->time_base = x11grab->time_base;
323 st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;
331 * Paint a mouse pointer in an X11 image.
333 * @param image image to paint the mouse pointer to
334 * @param s context used to retrieve original grabbing rectangle
338 paint_mouse_pointer(XImage *image, struct x11_grab *s)
340 int x_off = s->x_off;
341 int y_off = s->y_off;
342 int width = s->width;
343 int height = s->height;
344 Display *dpy = s->dpy;
345 XFixesCursorImage *xcim;
348 int to_line, to_column;
349 int pixstride = image->bits_per_pixel >> 3;
350 /* Warning: in its insanity, xlib provides unsigned image data through a
351 * char* pointer, so we have to make it uint8_t to make things not break.
352 * Anyone who performs further investigation of the xlib API likely risks
353 * permanent brain damage. */
354 uint8_t *pix = image->data;
356 /* Code doesn't currently support 16-bit or PAL8 */
357 if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
360 xcim = XFixesGetCursorImage(dpy);
362 x = xcim->x - xcim->xhot;
363 y = xcim->y - xcim->yhot;
365 to_line = FFMIN((y + xcim->height), (height + y_off));
366 to_column = FFMIN((x + xcim->width), (width + x_off));
368 for (line = FFMAX(y, y_off); line < to_line; line++) {
369 for (column = FFMAX(x, x_off); column < to_column; column++) {
370 int xcim_addr = (line - y) * xcim->width + column - x;
371 int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
372 int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
373 int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
374 int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
375 int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
378 pix[image_addr+0] = r;
379 pix[image_addr+1] = g;
380 pix[image_addr+2] = b;
382 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
383 pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
384 pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
385 pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
396 * Read new data in the image structure.
398 * @param dpy X11 display to grab from
400 * @param image Image where the grab will be put
401 * @param x Top-Left grabbing rectangle horizontal coordinate
402 * @param y Top-Left grabbing rectangle vertical coordinate
403 * @return 0 if error, !0 if successful
406 xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
417 GetReq(GetImage, req);
419 /* First set up the standard stuff in the request */
423 req->width = image->width;
424 req->height = image->height;
425 req->planeMask = (unsigned int)AllPlanes;
426 req->format = ZPixmap;
428 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
434 nbytes = (long)rep.length << 2;
435 _XReadPad(dpy, image->data, nbytes);
443 * Grab a frame from x11 (public device demuxer API).
445 * @param s1 Context from avformat core
446 * @param pkt Packet holding the brabbed frame
447 * @return frame size in bytes
450 x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
452 struct x11_grab *s = s1->priv_data;
453 Display *dpy = s->dpy;
454 XImage *image = s->image;
455 int x_off = s->x_off;
456 int y_off = s->y_off;
460 int follow_mouse = s->follow_mouse;
462 int64_t curtime, delay;
465 /* Calculate the time of the next frame */
466 s->time_frame += INT64_C(1000000);
468 /* wait based on the frame rate */
470 curtime = av_gettime();
471 delay = s->time_frame * av_q2d(s->time_base) - curtime;
473 if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
474 s->time_frame += INT64_C(1000000);
478 ts.tv_sec = delay / 1000000;
479 ts.tv_nsec = (delay % 1000000) * 1000;
480 nanosleep(&ts, NULL);
484 pkt->data = image->data;
485 pkt->size = s->frame_size;
488 screen = DefaultScreen(dpy);
489 root = RootWindow(dpy, screen);
491 int screen_w, screen_h;
492 int pointer_x, pointer_y, _;
495 screen_w = DisplayWidth(dpy, screen);
496 screen_h = DisplayHeight(dpy, screen);
497 XQueryPointer(dpy, root, &w, &w, &pointer_x, &pointer_y, &_, &_, &_);
498 if (follow_mouse == -1) {
499 // follow the mouse, put it at center of grabbing region
500 x_off += pointer_x - s->width / 2 - x_off;
501 y_off += pointer_y - s->height / 2 - y_off;
503 // follow the mouse, but only move the grabbing region when mouse
504 // reaches within certain pixels to the edge.
505 if (pointer_x > x_off + s->width - follow_mouse) {
506 x_off += pointer_x - (x_off + s->width - follow_mouse);
507 } else if (pointer_x < x_off + follow_mouse)
508 x_off -= (x_off + follow_mouse) - pointer_x;
509 if (pointer_y > y_off + s->height - follow_mouse) {
510 y_off += pointer_y - (y_off + s->height - follow_mouse);
511 } else if (pointer_y < y_off + follow_mouse)
512 y_off -= (y_off + follow_mouse) - pointer_y;
514 // adjust grabbing region position if it goes out of screen.
515 s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);
516 s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);
518 if (s->show_region && s->region_win)
519 XMoveWindow(dpy, s->region_win,
520 s->x_off - REGION_WIN_BORDER,
521 s->y_off - REGION_WIN_BORDER);
524 if (s->show_region) {
527 // clean up the events, and do the initinal draw or redraw.
528 for (evt.type = NoEventMask; XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask, &evt); );
530 x11grab_draw_region_win(s);
532 x11grab_region_win_init(s);
537 if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes)) {
538 av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
541 if (!xget_zpixmap(dpy, root, image, x_off, y_off)) {
542 av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
547 paint_mouse_pointer(image, s);
550 return s->frame_size;
554 * Close x11 frame grabber (public device demuxer API).
556 * @param s1 Context from avformat core
557 * @return 0 success, !0 failure
560 x11grab_read_close(AVFormatContext *s1)
562 struct x11_grab *x11grab = s1->priv_data;
564 /* Detach cleanly from shared mem */
565 if (x11grab->use_shm) {
566 XShmDetach(x11grab->dpy, &x11grab->shminfo);
567 shmdt(x11grab->shminfo.shmaddr);
568 shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
571 /* Destroy X11 image */
572 if (x11grab->image) {
573 XDestroyImage(x11grab->image);
574 x11grab->image = NULL;
577 if (x11grab->region_win) {
578 XDestroyWindow(x11grab->dpy, x11grab->region_win);
581 /* Free X11 display */
582 XCloseDisplay(x11grab->dpy);
586 #define OFFSET(x) offsetof(struct x11_grab, x)
587 #define DEC AV_OPT_FLAG_DECODING_PARAM
588 static const AVOption options[] = {
589 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = "vga"}, 0, 0, DEC },
590 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
591 { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), AV_OPT_TYPE_INT, { 1 }, 0, 1, DEC },
592 { "follow_mouse", "Move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region.",
593 OFFSET(follow_mouse), AV_OPT_TYPE_INT, { 0 }, -1, INT_MAX, DEC, "follow_mouse" },
594 { "centered", "Keep the mouse pointer at the center of grabbing region when following.", 0, AV_OPT_TYPE_CONST, { -1 }, INT_MIN, INT_MAX, DEC, "follow_mouse" },
595 { "show_region", "Show the grabbing region.", OFFSET(show_region), AV_OPT_TYPE_INT, { 0 }, 0, 1, DEC },
599 static const AVClass x11_class = {
600 .class_name = "X11grab indev",
601 .item_name = av_default_item_name,
603 .version = LIBAVUTIL_VERSION_INT,
606 /** x11 grabber device demuxer declaration */
607 AVInputFormat ff_x11_grab_device_demuxer = {
609 .long_name = NULL_IF_CONFIG_SMALL("X11grab"),
610 .priv_data_size = sizeof(struct x11_grab),
611 .read_header = x11grab_read_header,
612 .read_packet = x11grab_read_packet,
613 .read_close = x11grab_read_close,
614 .flags = AVFMT_NOFILE,
615 .priv_class = &x11_class,