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