2 * X11 video grab interface
4 * This file is part of Libav.
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 * Libav 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 * Libav 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 Libav; 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 by Clemens Fruhwirth <clemens@endorphin.org>
35 * and Edouard Gomez <ed.gomez@free.fr>.
39 #include "libavformat/avformat.h"
40 #include "libavutil/log.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/parseutils.h"
46 #include <X11/Xlibint.h>
47 #include <X11/Xproto.h>
48 #include <X11/Xutil.h>
50 #include <X11/extensions/shape.h>
51 #include <X11/extensions/XShm.h>
52 #include <X11/extensions/Xfixes.h>
55 * X11 Device Demuxer context
59 const AVClass *class; /**< Class for private options. */
60 int frame_size; /**< Size in bytes of a grabbed frame */
61 AVRational time_base; /**< Time base */
62 int64_t time_frame; /**< Current time */
64 char *video_size; /**< String describing video size, set by a private option. */
65 int height; /**< Height of the grab frame */
66 int width; /**< Width of the grab frame */
67 int x_off; /**< Horizontal top-left corner coordinate */
68 int y_off; /**< Vertical top-left corner coordinate */
70 Display *dpy; /**< X11 display from which x11grab grabs frames */
71 XImage *image; /**< X11 image holding the grab */
72 int use_shm; /**< !0 when using XShm extension */
73 XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
74 int draw_mouse; /**< Set by a private option. */
75 int follow_mouse; /**< Set by a private option. */
76 int show_region; /**< set by a private option. */
77 char *framerate; /**< Set by a private option. */
79 Window region_win; /**< This is used by show_region option. */
82 #define REGION_WIN_BORDER 3
84 * Draw grabbing region window
86 * @param s x11_grab context
89 x11grab_draw_region_win(struct x11_grab *s)
91 Display *dpy = s->dpy;
93 Window win = s->region_win;
96 screen = DefaultScreen(dpy);
97 gc = XCreateGC(dpy, win, 0, 0);
98 XSetForeground(dpy, gc, WhitePixel(dpy, screen));
99 XSetBackground(dpy, gc, BlackPixel(dpy, screen));
100 XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
101 XDrawRectangle(dpy, win, gc,
103 (s->width + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
104 (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
109 * Initialize grabbing region window
111 * @param s x11_grab context
114 x11grab_region_win_init(struct x11_grab *s)
116 Display *dpy = s->dpy;
118 XSetWindowAttributes attribs;
121 screen = DefaultScreen(dpy);
122 attribs.override_redirect = True;
123 s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
124 s->x_off - REGION_WIN_BORDER,
125 s->y_off - REGION_WIN_BORDER,
126 s->width + REGION_WIN_BORDER * 2,
127 s->height + REGION_WIN_BORDER * 2,
129 InputOutput, CopyFromParent,
130 CWOverrideRedirect, &attribs);
133 rect.width = s->width;
134 rect.height = s->height;
135 XShapeCombineRectangles(dpy, s->region_win,
136 ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
137 &rect, 1, ShapeSubtract, 0);
138 XMapWindow(dpy, s->region_win);
139 XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
140 x11grab_draw_region_win(s);
144 * Initialize the x11 grab device demuxer (public device demuxer API).
146 * @param s1 Context from avformat core
147 * @param ap Parameters from avformat core
149 * <li>AVERROR(ENOMEM) no memory left</li>
150 * <li>AVERROR(EIO) other failure case</li>
155 x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
157 struct x11_grab *x11grab = s1->priv_data;
160 enum PixelFormat input_pixfmt;
166 char *param, *offset;
168 AVRational framerate;
170 param = av_strdup(s1->filename);
171 offset = strchr(param, '+');
173 sscanf(offset, "%d,%d", &x_off, &y_off);
174 x11grab->draw_mouse = !strstr(offset, "nomouse");
178 if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) {
179 av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
182 if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) {
183 av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate);
186 av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
187 s1->filename, param, x_off, y_off, x11grab->width, x11grab->height);
189 dpy = XOpenDisplay(param);
191 av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
196 st = av_new_stream(s1, 0);
198 ret = AVERROR(ENOMEM);
201 av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
203 screen = DefaultScreen(dpy);
205 if (x11grab->follow_mouse) {
206 int screen_w, screen_h;
209 screen_w = DisplayWidth(dpy, screen);
210 screen_h = DisplayHeight(dpy, screen);
211 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret);
212 x_off -= x11grab->width / 2;
213 y_off -= x11grab->height / 2;
214 x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
215 y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
216 av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off);
219 use_shm = XShmQueryExtension(dpy);
220 av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not");
223 int scr = XDefaultScreen(dpy);
224 image = XShmCreateImage(dpy,
225 DefaultVisual(dpy, scr),
226 DefaultDepth(dpy, scr),
230 x11grab->width, x11grab->height);
231 x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
232 image->bytes_per_line * image->height,
234 if (x11grab->shminfo.shmid == -1) {
235 av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
236 ret = AVERROR(ENOMEM);
239 x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
240 x11grab->shminfo.readOnly = False;
242 if (!XShmAttach(dpy, &x11grab->shminfo)) {
243 av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
244 /* needs some better error subroutine :) */
249 image = XGetImage(dpy, RootWindow(dpy, screen),
251 x11grab->width, x11grab->height,
255 switch (image->bits_per_pixel) {
257 av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
258 input_pixfmt = PIX_FMT_PAL8;
261 if ( image->red_mask == 0xf800 &&
262 image->green_mask == 0x07e0 &&
263 image->blue_mask == 0x001f ) {
264 av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
265 input_pixfmt = PIX_FMT_RGB565;
266 } else if (image->red_mask == 0x7c00 &&
267 image->green_mask == 0x03e0 &&
268 image->blue_mask == 0x001f ) {
269 av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
270 input_pixfmt = PIX_FMT_RGB555;
272 av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
273 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);
279 if ( image->red_mask == 0xff0000 &&
280 image->green_mask == 0x00ff00 &&
281 image->blue_mask == 0x0000ff ) {
282 input_pixfmt = PIX_FMT_BGR24;
283 } else if ( image->red_mask == 0x0000ff &&
284 image->green_mask == 0x00ff00 &&
285 image->blue_mask == 0xff0000 ) {
286 input_pixfmt = PIX_FMT_RGB24;
288 av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
289 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);
295 input_pixfmt = PIX_FMT_RGB32;
298 av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
299 ret = AVERROR(EINVAL);
303 x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
305 x11grab->time_base = (AVRational){framerate.den, framerate.num};
306 x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
307 x11grab->x_off = x_off;
308 x11grab->y_off = y_off;
309 x11grab->image = image;
310 x11grab->use_shm = use_shm;
312 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
313 st->codec->codec_id = CODEC_ID_RAWVIDEO;
314 st->codec->width = x11grab->width;
315 st->codec->height = x11grab->height;
316 st->codec->pix_fmt = input_pixfmt;
317 st->codec->time_base = x11grab->time_base;
318 st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;
325 * Paint a mouse pointer in an X11 image.
327 * @param image image to paint the mouse pointer to
328 * @param s context used to retrieve original grabbing rectangle
332 paint_mouse_pointer(XImage *image, struct x11_grab *s)
334 int x_off = s->x_off;
335 int y_off = s->y_off;
336 int width = s->width;
337 int height = s->height;
338 Display *dpy = s->dpy;
339 XFixesCursorImage *xcim;
342 int to_line, to_column;
343 int pixstride = image->bits_per_pixel >> 3;
344 /* Warning: in its insanity, xlib provides unsigned image data through a
345 * char* pointer, so we have to make it uint8_t to make things not break.
346 * Anyone who performs further investigation of the xlib API likely risks
347 * permanent brain damage. */
348 uint8_t *pix = image->data;
350 /* Code doesn't currently support 16-bit or PAL8 */
351 if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
354 xcim = XFixesGetCursorImage(dpy);
356 x = xcim->x - xcim->xhot;
357 y = xcim->y - xcim->yhot;
359 to_line = FFMIN((y + xcim->height), (height + y_off));
360 to_column = FFMIN((x + xcim->width), (width + x_off));
362 for (line = FFMAX(y, y_off); line < to_line; line++) {
363 for (column = FFMAX(x, x_off); column < to_column; column++) {
364 int xcim_addr = (line - y) * xcim->width + column - x;
365 int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
366 int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
367 int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
368 int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
369 int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
372 pix[image_addr+0] = r;
373 pix[image_addr+1] = g;
374 pix[image_addr+2] = b;
376 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
377 pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
378 pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
379 pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
390 * Read new data in the image structure.
392 * @param dpy X11 display to grab from
394 * @param image Image where the grab will be put
395 * @param x Top-Left grabbing rectangle horizontal coordinate
396 * @param y Top-Left grabbing rectangle vertical coordinate
397 * @return 0 if error, !0 if successful
400 xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
411 GetReq(GetImage, req);
413 /* First set up the standard stuff in the request */
417 req->width = image->width;
418 req->height = image->height;
419 req->planeMask = (unsigned int)AllPlanes;
420 req->format = ZPixmap;
422 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
428 nbytes = (long)rep.length << 2;
429 _XReadPad(dpy, image->data, nbytes);
437 * Grab a frame from x11 (public device demuxer API).
439 * @param s1 Context from avformat core
440 * @param pkt Packet holding the brabbed frame
441 * @return frame size in bytes
444 x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
446 struct x11_grab *s = s1->priv_data;
447 Display *dpy = s->dpy;
448 XImage *image = s->image;
449 int x_off = s->x_off;
450 int y_off = s->y_off;
454 int follow_mouse = s->follow_mouse;
456 int64_t curtime, delay;
459 /* Calculate the time of the next frame */
460 s->time_frame += INT64_C(1000000);
462 /* wait based on the frame rate */
464 curtime = av_gettime();
465 delay = s->time_frame * av_q2d(s->time_base) - curtime;
467 if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
468 s->time_frame += INT64_C(1000000);
472 ts.tv_sec = delay / 1000000;
473 ts.tv_nsec = (delay % 1000000) * 1000;
474 nanosleep(&ts, NULL);
478 pkt->data = image->data;
479 pkt->size = s->frame_size;
482 screen = DefaultScreen(dpy);
483 root = RootWindow(dpy, screen);
485 int screen_w, screen_h;
486 int pointer_x, pointer_y, _;
489 screen_w = DisplayWidth(dpy, screen);
490 screen_h = DisplayHeight(dpy, screen);
491 XQueryPointer(dpy, root, &w, &w, &pointer_x, &pointer_y, &_, &_, &_);
492 if (follow_mouse == -1) {
493 // follow the mouse, put it at center of grabbing region
494 x_off += pointer_x - s->width / 2 - x_off;
495 y_off += pointer_y - s->height / 2 - y_off;
497 // follow the mouse, but only move the grabbing region when mouse
498 // reaches within certain pixels to the edge.
499 if (pointer_x > x_off + s->width - follow_mouse) {
500 x_off += pointer_x - (x_off + s->width - follow_mouse);
501 } else if (pointer_x < x_off + follow_mouse)
502 x_off -= (x_off + follow_mouse) - pointer_x;
503 if (pointer_y > y_off + s->height - follow_mouse) {
504 y_off += pointer_y - (y_off + s->height - follow_mouse);
505 } else if (pointer_y < y_off + follow_mouse)
506 y_off -= (y_off + follow_mouse) - pointer_y;
508 // adjust grabbing region position if it goes out of screen.
509 s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);
510 s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);
512 if (s->show_region && s->region_win)
513 XMoveWindow(dpy, s->region_win,
514 s->x_off - REGION_WIN_BORDER,
515 s->y_off - REGION_WIN_BORDER);
518 if (s->show_region) {
521 // clean up the events, and do the initinal draw or redraw.
522 for (evt.type = NoEventMask; XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask, &evt); );
524 x11grab_draw_region_win(s);
526 x11grab_region_win_init(s);
531 if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes)) {
532 av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
535 if (!xget_zpixmap(dpy, root, image, x_off, y_off)) {
536 av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
541 paint_mouse_pointer(image, s);
544 return s->frame_size;
548 * Close x11 frame grabber (public device demuxer API).
550 * @param s1 Context from avformat core
551 * @return 0 success, !0 failure
554 x11grab_read_close(AVFormatContext *s1)
556 struct x11_grab *x11grab = s1->priv_data;
558 /* Detach cleanly from shared mem */
559 if (x11grab->use_shm) {
560 XShmDetach(x11grab->dpy, &x11grab->shminfo);
561 shmdt(x11grab->shminfo.shmaddr);
562 shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
565 /* Destroy X11 image */
566 if (x11grab->image) {
567 XDestroyImage(x11grab->image);
568 x11grab->image = NULL;
571 if (x11grab->region_win) {
572 XDestroyWindow(x11grab->dpy, x11grab->region_win);
575 /* Free X11 display */
576 XCloseDisplay(x11grab->dpy);
580 #define OFFSET(x) offsetof(struct x11_grab, x)
581 #define DEC AV_OPT_FLAG_DECODING_PARAM
582 static const AVOption options[] = {
583 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = "vga"}, 0, 0, DEC },
584 { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
585 { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), FF_OPT_TYPE_INT, { 1 }, 0, 1, DEC },
586 { "follow_mouse", "Move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region.",
587 OFFSET(follow_mouse), FF_OPT_TYPE_INT, { 0 }, -1, INT_MAX, DEC, "follow_mouse" },
588 { "centered", "Keep the mouse pointer at the center of grabbing region when following.", 0, FF_OPT_TYPE_CONST, { -1 }, INT_MIN, INT_MAX, DEC, "follow_mouse" },
589 { "show_region", "Show the grabbing region.", OFFSET(show_region), FF_OPT_TYPE_INT, { 0 }, 0, 1, DEC },
593 static const AVClass x11_class = {
594 .class_name = "X11grab indev",
595 .item_name = av_default_item_name,
597 .version = LIBAVUTIL_VERSION_INT,
600 /** x11 grabber device demuxer declaration */
601 AVInputFormat ff_x11_grab_device_demuxer =
604 NULL_IF_CONFIG_SMALL("X11grab"),
605 sizeof(struct x11_grab),
610 .flags = AVFMT_NOFILE,
611 .priv_class = &x11_class,