x11grab: Fallback to normal XImage if SHM is not supported
[libav.git] / libavdevice / x11grab.c
CommitLineData
f58f4ce1
GP
1/*
2 * X11 video grab interface
2909f177 3 *
2912e87a 4 * This file is part of Libav.
f58f4ce1 5 *
2912e87a 6 * Libav integration:
ef84bf04
EG
7 * Copyright (C) 2006 Clemens Fruhwirth <clemens@endorphin.org>
8 * Edouard Gomez <ed.gomez@free.fr>
f58f4ce1 9 *
ef84bf04 10 * This file contains code from grab.c:
aac105fc 11 * Copyright (c) 2000-2001 Fabrice Bellard
f58f4ce1
GP
12 *
13 * This file contains code from the xvidcap project:
ef84bf04
EG
14 * Copyright (C) 1997-1998 Rasca, Berlin
15 * 2003-2004 Karl H. Beckers, Frankfurt
f58f4ce1 16 *
2912e87a 17 * Libav is free software; you can redistribute it and/or modify
f58f4ce1
GP
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.
21 *
2912e87a 22 * Libav is distributed in the hope that it will be useful,
f58f4ce1
GP
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.
26 *
e5a389a1 27 * You should have received a copy of the GNU General Public License
2912e87a 28 * along with Libav; if not, write to the Free Software
e5a389a1 29 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
f58f4ce1 30 */
2909f177 31
6e71a18e 32/**
ba87f080 33 * @file
e873c03a
DB
34 * X11 frame device demuxer
35 * @author Clemens Fruhwirth <clemens@endorphin.org>
36 * @author Edouard Gomez <ed.gomez@free.fr>
6e71a18e
EG
37 */
38
b0067549 39#include "config.h"
f07a4290 40
f58f4ce1 41#include <time.h>
f07a4290
LB
42#include <sys/shm.h>
43
f58f4ce1
GP
44#include <X11/X.h>
45#include <X11/Xlib.h>
46#include <X11/Xlibint.h>
47#include <X11/Xproto.h>
ef84bf04 48#include <X11/Xutil.h>
f07a4290 49
1442d295 50#include <X11/extensions/shape.h>
781c1aa6 51#include <X11/extensions/Xfixes.h>
f07a4290 52#include <X11/extensions/XShm.h>
f58f4ce1 53
f07a4290
LB
54#include "libavutil/log.h"
55#include "libavutil/opt.h"
56#include "libavutil/parseutils.h"
57#include "libavutil/time.h"
58
59#include "libavformat/avformat.h"
60#include "libavformat/internal.h"
61
62/** X11 device demuxer context */
58396e80 63typedef struct X11GrabContext {
724a900c 64 const AVClass *class; /**< Class for private options. */
6e71a18e
EG
65 int frame_size; /**< Size in bytes of a grabbed frame */
66 AVRational time_base; /**< Time base */
67 int64_t time_frame; /**< Current time */
68
724a900c 69 char *video_size; /**< String describing video size, set by a private option. */
6e71a18e
EG
70 int height; /**< Height of the grab frame */
71 int width; /**< Width of the grab frame */
72 int x_off; /**< Horizontal top-left corner coordinate */
73 int y_off; /**< Vertical top-left corner coordinate */
74
75 Display *dpy; /**< X11 display from which x11grab grabs frames */
76 XImage *image; /**< X11 image holding the grab */
77 int use_shm; /**< !0 when using XShm extension */
78 XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
f07a4290
LB
79 int draw_mouse; /**< Set by a private option. */
80 int follow_mouse; /**< Set by a private option. */
81 int show_region; /**< set by a private option. */
ff494cbd 82 char *framerate; /**< Set by a private option. */
1442d295
YJL
83
84 Window region_win; /**< This is used by show_region option. */
58396e80 85} X11GrabContext;
6e71a18e 86
1442d295 87#define REGION_WIN_BORDER 3
f07a4290 88
1442d295
YJL
89/**
90 * Draw grabbing region window
91 *
24f8961f 92 * @param s x11grab context
1442d295 93 */
58396e80 94static void x11grab_draw_region_win(X11GrabContext *s)
1442d295
YJL
95{
96 Display *dpy = s->dpy;
f07a4290 97 Window win = s->region_win;
20e82b41
LB
98 int screen = DefaultScreen(dpy);
99 GC gc = XCreateGC(dpy, win, 0, 0);
1442d295 100
1442d295
YJL
101 XSetForeground(dpy, gc, WhitePixel(dpy, screen));
102 XSetBackground(dpy, gc, BlackPixel(dpy, screen));
103 XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
f07a4290 104 XDrawRectangle(dpy, win, gc, 1, 1,
1442d295
YJL
105 (s->width + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
106 (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
107 XFreeGC(dpy, gc);
108}
109
110/**
111 * Initialize grabbing region window
112 *
24f8961f 113 * @param s x11grab context
1442d295 114 */
58396e80 115static void x11grab_region_win_init(X11GrabContext *s)
1442d295
YJL
116{
117 Display *dpy = s->dpy;
1442d295 118 XRectangle rect;
20e82b41
LB
119 XSetWindowAttributes attribs = { .override_redirect = True };
120 int screen = DefaultScreen(dpy);
1442d295 121
1442d295
YJL
122 s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
123 s->x_off - REGION_WIN_BORDER,
124 s->y_off - REGION_WIN_BORDER,
125 s->width + REGION_WIN_BORDER * 2,
126 s->height + REGION_WIN_BORDER * 2,
127 0, CopyFromParent,
128 InputOutput, CopyFromParent,
129 CWOverrideRedirect, &attribs);
f07a4290
LB
130 rect.x = 0;
131 rect.y = 0;
1442d295
YJL
132 rect.width = s->width;
133 rect.height = s->height;
134 XShapeCombineRectangles(dpy, s->region_win,
135 ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
136 &rect, 1, ShapeSubtract, 0);
137 XMapWindow(dpy, s->region_win);
138 XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
139 x11grab_draw_region_win(s);
140}
141
bb3ead7e
LB
142static int setup_shm(AVFormatContext *s, Display *dpy, XImage **image)
143{
144 X11GrabContext *g = s->priv_data;
145 int scr = XDefaultScreen(dpy);
146 XImage *img = XShmCreateImage(dpy, DefaultVisual(dpy, scr),
147 DefaultDepth(dpy, scr), ZPixmap, NULL,
148 &g->shminfo, g->width, g->height);
149
150 g->shminfo.shmid = shmget(IPC_PRIVATE, img->bytes_per_line * img->height,
151 IPC_CREAT | 0777);
152
153 if (g->shminfo.shmid == -1) {
154 av_log(s, AV_LOG_ERROR, "Cannot get shared memory!\n");
155 return AVERROR(ENOMEM);
156 }
157
158 g->shminfo.shmaddr = img->data = shmat(g->shminfo.shmid, 0, 0);
159 g->shminfo.readOnly = False;
160
161 if (!XShmAttach(dpy, &g->shminfo)) {
162 av_log(s, AV_LOG_ERROR, "Failed to attach shared memory!\n");
163 /* needs some better error subroutine :) */
164 return AVERROR(EIO);
165 }
166
167 *image = img;
168 return 0;
169}
170
6e71a18e 171/**
49bd8e4b 172 * Initialize the x11 grab device demuxer (public device demuxer API).
6e71a18e
EG
173 *
174 * @param s1 Context from avformat core
6e71a18e 175 * @return <ul>
5632e568 176 * <li>AVERROR(ENOMEM) no memory left</li>
6f3e0b21 177 * <li>AVERROR(EIO) other failure case</li>
6e71a18e
EG
178 * <li>0 success</li>
179 * </ul>
180 */
f07a4290 181static int x11grab_read_header(AVFormatContext *s1)
f58f4ce1 182{
58396e80 183 X11GrabContext *x11grab = s1->priv_data;
aac105fc
EG
184 Display *dpy;
185 AVStream *st = NULL;
716d413c 186 enum AVPixelFormat input_pixfmt;
aac105fc 187 XImage *image;
20e82b41 188 int x_off = 0, y_off = 0, ret = 0, screen, use_shm;
0cd4faf9 189 char *param, *offset;
ff494cbd 190 AVRational framerate;
aac105fc 191
cc58300e 192 param = av_strdup(s1->filename);
d3958ab4
AO
193 if (!param)
194 goto out;
195
0cd4faf9
PI
196 offset = strchr(param, '+');
197 if (offset) {
198 sscanf(offset, "%d,%d", &x_off, &y_off);
ce558c8f 199 x11grab->draw_mouse = !strstr(offset, "nomouse");
f07a4290 200 *offset = 0;
0cd4faf9
PI
201 }
202
20e82b41
LB
203 ret = av_parse_video_size(&x11grab->width, &x11grab->height,
204 x11grab->video_size);
205 if (ret < 0) {
724a900c
AK
206 av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
207 goto out;
208 }
20e82b41
LB
209
210 ret = av_parse_video_rate(&framerate, x11grab->framerate);
211 if (ret < 0) {
f07a4290
LB
212 av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n",
213 x11grab->framerate);
ff494cbd
AK
214 goto out;
215 }
f07a4290
LB
216 av_log(s1, AV_LOG_INFO,
217 "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
724a900c 218 s1->filename, param, x_off, y_off, x11grab->width, x11grab->height);
0cd4faf9
PI
219
220 dpy = XOpenDisplay(param);
f07a4290 221 if (!dpy) {
0cd4faf9 222 av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
3102fb03
AK
223 ret = AVERROR(EIO);
224 goto out;
0cd4faf9 225 }
aac105fc 226
3b3bbdd3 227 st = avformat_new_stream(s1, NULL);
aac105fc 228 if (!st) {
3102fb03
AK
229 ret = AVERROR(ENOMEM);
230 goto out;
aac105fc 231 }
c3f9ebf7 232 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
aac105fc 233
085791a9
YJL
234 screen = DefaultScreen(dpy);
235
236 if (x11grab->follow_mouse) {
237 int screen_w, screen_h;
238 Window w;
239
240 screen_w = DisplayWidth(dpy, screen);
241 screen_h = DisplayHeight(dpy, screen);
f07a4290
LB
242 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off,
243 &ret, &ret, &ret);
085791a9
YJL
244 x_off -= x11grab->width / 2;
245 y_off -= x11grab->height / 2;
f07a4290
LB
246 x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
247 y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
248 av_log(s1, AV_LOG_INFO,
249 "followmouse is enabled, resetting grabbing region to x: %d y: %d\n",
250 x_off, y_off);
085791a9
YJL
251 }
252
aac105fc 253 use_shm = XShmQueryExtension(dpy);
f07a4290 254 av_log(s1, AV_LOG_INFO,
7bb505a3 255 "shared memory extension %sfound\n", use_shm ? "" : "not ");
aac105fc 256
bb3ead7e
LB
257 if (use_shm && setup_shm(s1, dpy, &image) < 0) {
258 av_log(s1, AV_LOG_WARNING, "Falling back to XGetImage\n");
259 use_shm = 0;
260 }
261
262 if (!use_shm) {
085791a9 263 image = XGetImage(dpy, RootWindow(dpy, screen),
f07a4290 264 x_off, y_off,
724a900c 265 x11grab->width, x11grab->height,
aac105fc
EG
266 AllPlanes, ZPixmap);
267 }
268
269 switch (image->bits_per_pixel) {
270 case 8:
f07a4290 271 av_log(s1, AV_LOG_DEBUG, "8 bit palette\n");
716d413c 272 input_pixfmt = AV_PIX_FMT_PAL8;
aac105fc
EG
273 break;
274 case 16:
f07a4290
LB
275 if (image->red_mask == 0xf800 &&
276 image->green_mask == 0x07e0 &&
277 image->blue_mask == 0x001f) {
278 av_log(s1, AV_LOG_DEBUG, "16 bit RGB565\n");
716d413c 279 input_pixfmt = AV_PIX_FMT_RGB565;
6e71a18e
EG
280 } else if (image->red_mask == 0x7c00 &&
281 image->green_mask == 0x03e0 &&
f07a4290 282 image->blue_mask == 0x001f) {
aac105fc 283 av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
716d413c 284 input_pixfmt = AV_PIX_FMT_RGB555;
aac105fc 285 } else {
f07a4290
LB
286 av_log(s1, AV_LOG_ERROR,
287 "RGB ordering at image depth %i not supported ... aborting\n",
288 image->bits_per_pixel);
289 av_log(s1, AV_LOG_ERROR,
290 "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n",
291 image->red_mask, image->green_mask, image->blue_mask);
3102fb03
AK
292 ret = AVERROR(EIO);
293 goto out;
aac105fc
EG
294 }
295 break;
296 case 24:
f07a4290
LB
297 if (image->red_mask == 0xff0000 &&
298 image->green_mask == 0x00ff00 &&
299 image->blue_mask == 0x0000ff) {
716d413c 300 input_pixfmt = AV_PIX_FMT_BGR24;
f07a4290
LB
301 } else if (image->red_mask == 0x0000ff &&
302 image->green_mask == 0x00ff00 &&
303 image->blue_mask == 0xff0000) {
716d413c 304 input_pixfmt = AV_PIX_FMT_RGB24;
aac105fc 305 } else {
f07a4290
LB
306 av_log(s1, AV_LOG_ERROR,
307 "rgb ordering at image depth %i not supported ... aborting\n",
308 image->bits_per_pixel);
309 av_log(s1, AV_LOG_ERROR,
310 "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n",
311 image->red_mask, image->green_mask, image->blue_mask);
3102fb03
AK
312 ret = AVERROR(EIO);
313 goto out;
aac105fc
EG
314 }
315 break;
316 case 32:
716d413c 317 input_pixfmt = AV_PIX_FMT_RGB32;
aac105fc
EG
318 break;
319 default:
f07a4290
LB
320 av_log(s1, AV_LOG_ERROR,
321 "image depth %i not supported ... aborting\n",
322 image->bits_per_pixel);
3102fb03
AK
323 ret = AVERROR(EINVAL);
324 goto out;
aac105fc
EG
325 }
326
f07a4290
LB
327 x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel / 8;
328 x11grab->dpy = dpy;
329 x11grab->time_base = (AVRational) { framerate.den, framerate.num };
ff494cbd 330 x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
f07a4290
LB
331 x11grab->x_off = x_off;
332 x11grab->y_off = y_off;
333 x11grab->image = image;
334 x11grab->use_shm = use_shm;
aac105fc 335
72415b2a 336 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
f07a4290
LB
337 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
338 st->codec->width = x11grab->width;
339 st->codec->height = x11grab->height;
340 st->codec->pix_fmt = input_pixfmt;
341 st->codec->time_base = x11grab->time_base;
342 st->codec->bit_rate = x11grab->frame_size * 1 / av_q2d(x11grab->time_base) * 8;
aac105fc 343
3102fb03 344out:
d3958ab4 345 av_free(param);
3102fb03 346 return ret;
f58f4ce1
GP
347}
348
6e71a18e 349/**
49bd8e4b 350 * Paint a mouse pointer in an X11 image.
6e71a18e 351 *
bd107136 352 * @param image image to paint the mouse pointer to
6e71a18e
EG
353 * @param s context used to retrieve original grabbing rectangle
354 * coordinates
6e71a18e 355 */
58396e80 356static void paint_mouse_pointer(XImage *image, X11GrabContext *s)
2909f177 357{
f07a4290
LB
358 int x_off = s->x_off;
359 int y_off = s->y_off;
360 int width = s->width;
361 int height = s->height;
781c1aa6
R
362 Display *dpy = s->dpy;
363 XFixesCursorImage *xcim;
364 int x, y;
365 int line, column;
366 int to_line, to_column;
8ce803db
JGG
367 int pixstride = image->bits_per_pixel >> 3;
368 /* Warning: in its insanity, xlib provides unsigned image data through a
369 * char* pointer, so we have to make it uint8_t to make things not break.
370 * Anyone who performs further investigation of the xlib API likely risks
371 * permanent brain damage. */
372 uint8_t *pix = image->data;
373
374 /* Code doesn't currently support 16-bit or PAL8 */
375 if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
376 return;
aac105fc 377
33e7febd 378 xcim = XFixesGetCursorImage(dpy);
aac105fc 379
781c1aa6
R
380 x = xcim->x - xcim->xhot;
381 y = xcim->y - xcim->yhot;
382
f07a4290
LB
383 to_line = FFMIN((y + xcim->height), (height + y_off));
384 to_column = FFMIN((x + xcim->width), (width + x_off));
781c1aa6
R
385
386 for (line = FFMAX(y, y_off); line < to_line; line++) {
387 for (column = FFMAX(x, x_off); column < to_column; column++) {
f07a4290
LB
388 int xcim_addr = (line - y) * xcim->width + column - x;
389 int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
390 int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
391 int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
392 int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
393 int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
8ce803db
JGG
394
395 if (a == 255) {
f07a4290
LB
396 pix[image_addr + 0] = r;
397 pix[image_addr + 1] = g;
398 pix[image_addr + 2] = b;
8ce803db
JGG
399 } else if (a) {
400 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
f07a4290
LB
401 pix[image_addr + 0] = r + (pix[image_addr + 0] * (255 - a) + 255 / 2) / 255;
402 pix[image_addr + 1] = g + (pix[image_addr + 1] * (255 - a) + 255 / 2) / 255;
403 pix[image_addr + 2] = b + (pix[image_addr + 2] * (255 - a) + 255 / 2) / 255;
0235a311 404 }
aac105fc
EG
405 }
406 }
781c1aa6
R
407
408 XFree(xcim);
409 xcim = NULL;
f58f4ce1
GP
410}
411
6e71a18e 412/**
49bd8e4b 413 * Read new data in the image structure.
6e71a18e
EG
414 *
415 * @param dpy X11 display to grab from
05f3b6ab 416 * @param d
6e71a18e
EG
417 * @param image Image where the grab will be put
418 * @param x Top-Left grabbing rectangle horizontal coordinate
419 * @param y Top-Left grabbing rectangle vertical coordinate
420 * @return 0 if error, !0 if successful
f58f4ce1 421 */
f07a4290 422static int xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
f58f4ce1 423{
aac105fc
EG
424 xGetImageReply rep;
425 xGetImageReq *req;
426 long nbytes;
427
f07a4290 428 if (!image)
6e71a18e 429 return 0;
aac105fc
EG
430
431 LockDisplay(dpy);
432 GetReq(GetImage, req);
433
434 /* First set up the standard stuff in the request */
f07a4290
LB
435 req->drawable = d;
436 req->x = x;
437 req->y = y;
438 req->width = image->width;
439 req->height = image->height;
aac105fc 440 req->planeMask = (unsigned int)AllPlanes;
f07a4290 441 req->format = ZPixmap;
aac105fc 442
6e71a18e 443 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
aac105fc
EG
444 UnlockDisplay(dpy);
445 SyncHandle();
6e71a18e 446 return 0;
aac105fc
EG
447 }
448
449 nbytes = (long)rep.length << 2;
450 _XReadPad(dpy, image->data, nbytes);
451
452 UnlockDisplay(dpy);
453 SyncHandle();
6e71a18e 454 return 1;
f58f4ce1
GP
455}
456
6e71a18e 457/**
49bd8e4b 458 * Grab a frame from x11 (public device demuxer API).
6e71a18e
EG
459 *
460 * @param s1 Context from avformat core
461 * @param pkt Packet holding the brabbed frame
462 * @return frame size in bytes
463 */
f07a4290 464static int x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
f58f4ce1 465{
58396e80 466 X11GrabContext *s = s1->priv_data;
f07a4290
LB
467 Display *dpy = s->dpy;
468 XImage *image = s->image;
469 int x_off = s->x_off;
470 int y_off = s->y_off;
471 int follow_mouse = s->follow_mouse;
085791a9
YJL
472 int screen;
473 Window root;
aac105fc
EG
474 int64_t curtime, delay;
475 struct timespec ts;
476
477 /* Calculate the time of the next frame */
ba78f9d4 478 s->time_frame += INT64_C(1000000);
aac105fc
EG
479
480 /* wait based on the frame rate */
f07a4290 481 for (;;) {
aac105fc 482 curtime = av_gettime();
f07a4290 483 delay = s->time_frame * av_q2d(s->time_base) - curtime;
aac105fc 484 if (delay <= 0) {
f07a4290 485 if (delay < INT64_C(-1000000) * av_q2d(s->time_base))
ba78f9d4 486 s->time_frame += INT64_C(1000000);
aac105fc
EG
487 break;
488 }
f07a4290 489 ts.tv_sec = delay / 1000000;
aac105fc
EG
490 ts.tv_nsec = (delay % 1000000) * 1000;
491 nanosleep(&ts, NULL);
492 }
493
2f2c6040
SD
494 av_init_packet(pkt);
495 pkt->data = image->data;
496 pkt->size = s->frame_size;
f07a4290 497 pkt->pts = curtime;
aac105fc 498
085791a9 499 screen = DefaultScreen(dpy);
f07a4290 500 root = RootWindow(dpy, screen);
085791a9
YJL
501 if (follow_mouse) {
502 int screen_w, screen_h;
503 int pointer_x, pointer_y, _;
504 Window w;
505
506 screen_w = DisplayWidth(dpy, screen);
507 screen_h = DisplayHeight(dpy, screen);
508 XQueryPointer(dpy, root, &w, &w, &pointer_x, &pointer_y, &_, &_, &_);
509 if (follow_mouse == -1) {
510 // follow the mouse, put it at center of grabbing region
f07a4290 511 x_off += pointer_x - s->width / 2 - x_off;
085791a9
YJL
512 y_off += pointer_y - s->height / 2 - y_off;
513 } else {
514 // follow the mouse, but only move the grabbing region when mouse
515 // reaches within certain pixels to the edge.
f07a4290 516 if (pointer_x > x_off + s->width - follow_mouse)
085791a9 517 x_off += pointer_x - (x_off + s->width - follow_mouse);
f07a4290 518 else if (pointer_x < x_off + follow_mouse)
085791a9 519 x_off -= (x_off + follow_mouse) - pointer_x;
f07a4290 520 if (pointer_y > y_off + s->height - follow_mouse)
085791a9 521 y_off += pointer_y - (y_off + s->height - follow_mouse);
f07a4290 522 else if (pointer_y < y_off + follow_mouse)
085791a9
YJL
523 y_off -= (y_off + follow_mouse) - pointer_y;
524 }
525 // adjust grabbing region position if it goes out of screen.
526 s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);
527 s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);
1442d295
YJL
528
529 if (s->show_region && s->region_win)
530 XMoveWindow(dpy, s->region_win,
531 s->x_off - REGION_WIN_BORDER,
532 s->y_off - REGION_WIN_BORDER);
533 }
534
535 if (s->show_region) {
536 if (s->region_win) {
20e82b41
LB
537 XEvent evt = { .type = NoEventMask };
538 // Clean up the events, and do the initial draw or redraw.
539 while (XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask,
540 &evt))
f07a4290 541 ;
1442d295
YJL
542 if (evt.type)
543 x11grab_draw_region_win(s);
544 } else {
545 x11grab_region_win_init(s);
546 }
085791a9
YJL
547 }
548
f07a4290
LB
549 if (s->use_shm) {
550 if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes))
551 av_log(s1, AV_LOG_INFO, "XShmGetImage() failed\n");
aac105fc 552 } else {
f07a4290
LB
553 if (!xget_zpixmap(dpy, root, image, x_off, y_off))
554 av_log(s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
aac105fc
EG
555 }
556
f07a4290 557 if (s->draw_mouse)
781c1aa6 558 paint_mouse_pointer(image, s);
aac105fc 559
aac105fc 560 return s->frame_size;
f58f4ce1
GP
561}
562
6e71a18e 563/**
49bd8e4b 564 * Close x11 frame grabber (public device demuxer API).
6e71a18e
EG
565 *
566 * @param s1 Context from avformat core
567 * @return 0 success, !0 failure
568 */
f07a4290 569static int x11grab_read_close(AVFormatContext *s1)
f58f4ce1 570{
58396e80 571 X11GrabContext *x11grab = s1->priv_data;
aac105fc
EG
572
573 /* Detach cleanly from shared mem */
574 if (x11grab->use_shm) {
575 XShmDetach(x11grab->dpy, &x11grab->shminfo);
576 shmdt(x11grab->shminfo.shmaddr);
577 shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
578 }
579
580 /* Destroy X11 image */
581 if (x11grab->image) {
582 XDestroyImage(x11grab->image);
583 x11grab->image = NULL;
584 }
585
f07a4290 586 if (x11grab->region_win)
1442d295 587 XDestroyWindow(x11grab->dpy, x11grab->region_win);
1442d295 588
aac105fc
EG
589 /* Free X11 display */
590 XCloseDisplay(x11grab->dpy);
591 return 0;
f58f4ce1
GP
592}
593
58396e80 594#define OFFSET(x) offsetof(X11GrabContext, x)
724a900c
AK
595#define DEC AV_OPT_FLAG_DECODING_PARAM
596static const AVOption options[] = {
145f741e
AK
597 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = "vga"}, 0, 0, DEC },
598 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
e6153f17 599 { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, DEC },
085791a9 600 { "follow_mouse", "Move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region.",
e6153f17 601 OFFSET(follow_mouse), AV_OPT_TYPE_INT, { .i64 = 0 }, -1, INT_MAX, DEC, "follow_mouse" },
124134e4 602 { "centered", "Keep the mouse pointer at the center of grabbing region when following.", 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, DEC, "follow_mouse" },
e6153f17 603 { "show_region", "Show the grabbing region.", OFFSET(show_region), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
724a900c
AK
604 { NULL },
605};
606
607static const AVClass x11_class = {
608 .class_name = "X11grab indev",
609 .item_name = av_default_item_name,
610 .option = options,
611 .version = LIBAVUTIL_VERSION_INT,
612};
613
6e71a18e 614/** x11 grabber device demuxer declaration */
24f8961f 615AVInputFormat ff_x11grab_demuxer = {
30b4ee79
DB
616 .name = "x11grab",
617 .long_name = NULL_IF_CONFIG_SMALL("X11grab"),
58396e80 618 .priv_data_size = sizeof(X11GrabContext),
30b4ee79
DB
619 .read_header = x11grab_read_header,
620 .read_packet = x11grab_read_packet,
621 .read_close = x11grab_read_close,
622 .flags = AVFMT_NOFILE,
623 .priv_class = &x11_class,
f58f4ce1 624};