]> git.sesse.net Git - ffmpeg/blob - libavdevice/x11grab.c
Merge commit '63f800ca5f4f6b38f3789a7edb03bfabe8bacdd2'
[ffmpeg] / libavdevice / x11grab.c
1 /*
2  * X11 video grab interface
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg integration:
7  * Copyright (C) 2006 Clemens Fruhwirth <clemens@endorphin.org>
8  *                    Edouard Gomez <ed.gomez@free.fr>
9  *
10  * This file contains code from grab.c:
11  * Copyright (c) 2000-2001 Fabrice Bellard
12  *
13  * This file contains code from the xvidcap project:
14  * Copyright (C) 1997-1998 Rasca, Berlin
15  *               2003-2004 Karl H. Beckers, Frankfurt
16  *
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.
21  *
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.
26  *
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
30  */
31
32 /**
33  * @file
34  * X11 frame device demuxer
35  * @author Clemens Fruhwirth <clemens@endorphin.org>
36  * @author Edouard Gomez <ed.gomez@free.fr>
37  */
38
39 #include "config.h"
40
41 #include <time.h>
42 #include <sys/shm.h>
43
44 #include <X11/cursorfont.h>
45 #include <X11/X.h>
46 #include <X11/Xlib.h>
47 #include <X11/Xlibint.h>
48 #include <X11/Xproto.h>
49 #include <X11/Xutil.h>
50
51 #include <X11/extensions/shape.h>
52 #include <X11/extensions/Xfixes.h>
53 #include <X11/extensions/XShm.h>
54
55 #include "avdevice.h"
56
57 #include "libavutil/log.h"
58 #include "libavutil/opt.h"
59 #include "libavutil/parseutils.h"
60 #include "libavutil/time.h"
61
62 #include "libavformat/internal.h"
63
64 /** X11 device demuxer context */
65 typedef struct X11GrabContext {
66     const AVClass *class;    /**< Class for private options. */
67     int frame_size;          /**< Size in bytes of a grabbed frame */
68     AVRational time_base;    /**< Time base */
69     int64_t time_frame;      /**< Current time */
70
71     int width;               /**< Width of the grab frame */
72     int height;              /**< Height 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 */
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. */
83     AVRational framerate;    /**< Set by a private option. */
84     int palette_changed;
85     uint32_t palette[256];
86
87     Cursor c;
88     Window region_win;       /**< This is used by show_region option. */
89 } X11GrabContext;
90
91 #define REGION_WIN_BORDER 3
92
93 /**
94  * Draw grabbing region window
95  *
96  * @param s x11grab context
97  */
98 static void x11grab_draw_region_win(X11GrabContext *s)
99 {
100     Display *dpy = s->dpy;
101     Window win   = s->region_win;
102     int screen = DefaultScreen(dpy);
103     GC gc = XCreateGC(dpy, win, 0, 0);
104
105     XSetForeground(dpy, gc, WhitePixel(dpy, screen));
106     XSetBackground(dpy, gc, BlackPixel(dpy, screen));
107     XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
108     XDrawRectangle(dpy, win, gc, 1, 1,
109                    (s->width  + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
110                    (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
111     XFreeGC(dpy, gc);
112 }
113
114 /**
115  * Initialize grabbing region window
116  *
117  * @param s x11grab context
118  */
119 static void x11grab_region_win_init(X11GrabContext *s)
120 {
121     Display *dpy = s->dpy;
122     XRectangle rect;
123     XSetWindowAttributes attribs = { .override_redirect = True };
124     int screen = DefaultScreen(dpy);
125
126     s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
127                                   s->x_off  - REGION_WIN_BORDER,
128                                   s->y_off  - REGION_WIN_BORDER,
129                                   s->width  + REGION_WIN_BORDER * 2,
130                                   s->height + REGION_WIN_BORDER * 2,
131                                   0, CopyFromParent,
132                                   InputOutput, CopyFromParent,
133                                   CWOverrideRedirect, &attribs);
134     rect.x      = 0;
135     rect.y      = 0;
136     rect.width  = s->width;
137     rect.height = s->height;
138     XShapeCombineRectangles(dpy, s->region_win,
139                             ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
140                             &rect, 1, ShapeSubtract, 0);
141     XMapWindow(dpy, s->region_win);
142     XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
143     x11grab_draw_region_win(s);
144 }
145
146 /**
147  * Initialize the x11 grab device demuxer (public device demuxer API).
148  *
149  * @param s1 Context from avformat core
150  * @return <ul>
151  *          <li>AVERROR(ENOMEM) no memory left</li>
152  *          <li>AVERROR(EIO) other failure case</li>
153  *          <li>0 success</li>
154  *         </ul>
155  */
156 static int x11grab_read_header(AVFormatContext *s1)
157 {
158     X11GrabContext *x11grab = s1->priv_data;
159     Display *dpy;
160     AVStream *st = NULL;
161     enum AVPixelFormat input_pixfmt;
162     XImage *image;
163     int x_off = 0, y_off = 0, ret = 0, screen, use_shm = 0;
164     char *dpyname, *offset;
165     Colormap color_map;
166     XColor color[256];
167     int i;
168
169     dpyname = av_strdup(s1->filename);
170     if (!dpyname)
171         goto out;
172
173     offset = strchr(dpyname, '+');
174     if (offset) {
175         sscanf(offset, "%d,%d", &x_off, &y_off);
176         if (strstr(offset, "nomouse")) {
177             av_log(s1, AV_LOG_WARNING,
178                    "'nomouse' specification in argument is deprecated: "
179                    "use 'draw_mouse' option with value 0 instead\n");
180             x11grab->draw_mouse = 0;
181         }
182         *offset = 0;
183     }
184
185     av_log(s1, AV_LOG_INFO,
186            "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
187            s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);
188
189     dpy = XOpenDisplay(dpyname);
190     av_freep(&dpyname);
191     if (!dpy) {
192         av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
193         ret = AVERROR(EIO);
194         goto out;
195     }
196
197     st = avformat_new_stream(s1, NULL);
198     if (!st) {
199         ret = AVERROR(ENOMEM);
200         goto out;
201     }
202     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
203
204     screen = DefaultScreen(dpy);
205
206     if (x11grab->follow_mouse) {
207         int screen_w, screen_h;
208         Window w;
209
210         screen_w = DisplayWidth(dpy, screen);
211         screen_h = DisplayHeight(dpy, screen);
212         XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off,
213                       &ret, &ret, &ret);
214         x_off -= x11grab->width / 2;
215         y_off -= x11grab->height / 2;
216         x_off  = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
217         y_off  = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
218         av_log(s1, AV_LOG_INFO,
219                "followmouse is enabled, resetting grabbing region to x: %d y: %d\n",
220                x_off, y_off);
221     }
222
223     if (x11grab->use_shm) {
224         use_shm = XShmQueryExtension(dpy);
225         av_log(s1, AV_LOG_INFO,
226                "shared memory extension %sfound\n", use_shm ? "" : "not ");
227     }
228
229     if (use_shm) {
230         int scr = XDefaultScreen(dpy);
231         image = XShmCreateImage(dpy,
232                                 DefaultVisual(dpy, scr),
233                                 DefaultDepth(dpy, scr),
234                                 ZPixmap,
235                                 NULL,
236                                 &x11grab->shminfo,
237                                 x11grab->width, x11grab->height);
238         x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
239                                         image->bytes_per_line * image->height,
240                                         IPC_CREAT | 0777);
241         if (x11grab->shminfo.shmid == -1) {
242             av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
243             ret = AVERROR(ENOMEM);
244             goto out;
245         }
246         x11grab->shminfo.shmaddr  = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
247         x11grab->shminfo.readOnly = False;
248
249         if (!XShmAttach(dpy, &x11grab->shminfo)) {
250             av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
251             /* needs some better error subroutine :) */
252             ret = AVERROR(EIO);
253             goto out;
254         }
255     } else {
256         image = XGetImage(dpy, RootWindow(dpy, screen),
257                           x_off, y_off,
258                           x11grab->width, x11grab->height,
259                           AllPlanes, ZPixmap);
260     }
261
262     switch (image->bits_per_pixel) {
263     case 8:
264         av_log(s1, AV_LOG_DEBUG, "8 bit palette\n");
265         input_pixfmt = AV_PIX_FMT_PAL8;
266         color_map = DefaultColormap(dpy, screen);
267         for (i = 0; i < 256; ++i)
268             color[i].pixel = i;
269         XQueryColors(dpy, color_map, color, 256);
270         for (i = 0; i < 256; ++i)
271             x11grab->palette[i] = (color[i].red   & 0xFF00) << 8 |
272                                   (color[i].green & 0xFF00)      |
273                                   (color[i].blue  & 0xFF00) >> 8;
274         x11grab->palette_changed = 1;
275         break;
276     case 16:
277         if (image->red_mask   == 0xf800 &&
278             image->green_mask == 0x07e0 &&
279             image->blue_mask  == 0x001f) {
280             av_log(s1, AV_LOG_DEBUG, "16 bit RGB565\n");
281             input_pixfmt = AV_PIX_FMT_RGB565;
282         } else if (image->red_mask   == 0x7c00 &&
283                    image->green_mask == 0x03e0 &&
284                    image->blue_mask  == 0x001f) {
285             av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
286             input_pixfmt = AV_PIX_FMT_RGB555;
287         } else {
288             av_log(s1, AV_LOG_ERROR,
289                    "RGB ordering at image depth %i not supported ... aborting\n",
290                    image->bits_per_pixel);
291             av_log(s1, AV_LOG_ERROR,
292                    "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n",
293                    image->red_mask, image->green_mask, image->blue_mask);
294             ret = AVERROR_PATCHWELCOME;
295             goto out;
296         }
297         break;
298     case 24:
299         if (image->red_mask   == 0xff0000 &&
300             image->green_mask == 0x00ff00 &&
301             image->blue_mask  == 0x0000ff) {
302             input_pixfmt = AV_PIX_FMT_BGR24;
303         } else if (image->red_mask   == 0x0000ff &&
304                    image->green_mask == 0x00ff00 &&
305                    image->blue_mask  == 0xff0000) {
306             input_pixfmt = AV_PIX_FMT_RGB24;
307         } else {
308             av_log(s1, AV_LOG_ERROR,
309                    "rgb ordering at image depth %i not supported ... aborting\n",
310                    image->bits_per_pixel);
311             av_log(s1, AV_LOG_ERROR,
312                    "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n",
313                    image->red_mask, image->green_mask, image->blue_mask);
314             ret = AVERROR_PATCHWELCOME;
315             goto out;
316         }
317         break;
318     case 32:
319         if (        image->red_mask   == 0xff0000 &&
320                     image->green_mask == 0x00ff00 &&
321                     image->blue_mask  == 0x0000ff ) {
322             input_pixfmt = AV_PIX_FMT_0RGB32;
323         } else {
324             av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
325             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);
326             ret = AVERROR_PATCHWELCOME;
327             goto out;
328         }
329         break;
330     default:
331         av_log(s1, AV_LOG_ERROR,
332                "image depth %i not supported ... aborting\n",
333                image->bits_per_pixel);
334         ret = AVERROR_PATCHWELCOME;
335         goto out;
336     }
337
338     x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel / 8;
339     x11grab->dpy        = dpy;
340     x11grab->time_base  = av_inv_q(x11grab->framerate);
341     x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
342     x11grab->x_off      = x_off;
343     x11grab->y_off      = y_off;
344     x11grab->image      = image;
345     x11grab->use_shm    = use_shm;
346
347     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
348     st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
349     st->codec->width      = x11grab->width;
350     st->codec->height     = x11grab->height;
351     st->codec->pix_fmt    = input_pixfmt;
352     st->codec->time_base  = x11grab->time_base;
353     st->codec->bit_rate   = x11grab->frame_size * 1 / av_q2d(x11grab->time_base) * 8;
354
355 out:
356     av_free(dpyname);
357     return ret;
358 }
359
360 /**
361  * Paint a mouse pointer in an X11 image.
362  *
363  * @param image image to paint the mouse pointer to
364  * @param s context used to retrieve original grabbing rectangle
365  *          coordinates
366  */
367 static void paint_mouse_pointer(XImage *image, AVFormatContext *s1)
368 {
369     X11GrabContext *s = s1->priv_data;
370     int x_off    = s->x_off;
371     int y_off    = s->y_off;
372     int width    = s->width;
373     int height   = s->height;
374     Display *dpy = s->dpy;
375     XFixesCursorImage *xcim;
376     int x, y;
377     int line, column;
378     int to_line, to_column;
379     int pixstride = image->bits_per_pixel >> 3;
380     /* Warning: in its insanity, xlib provides unsigned image data through a
381      * char* pointer, so we have to make it uint8_t to make things not break.
382      * Anyone who performs further investigation of the xlib API likely risks
383      * permanent brain damage. */
384     uint8_t *pix = image->data;
385     Window w;
386     XSetWindowAttributes attr;
387
388     /* Code doesn't currently support 16-bit or PAL8 */
389     if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
390         return;
391
392     if (!s->c)
393         s->c = XCreateFontCursor(dpy, XC_left_ptr);
394     w = DefaultRootWindow(dpy);
395     attr.cursor = s->c;
396     XChangeWindowAttributes(dpy, w, CWCursor, &attr);
397
398     xcim = XFixesGetCursorImage(dpy);
399     if (!xcim) {
400         av_log(s1, AV_LOG_WARNING,
401                "XFixes extension not available, impossible to draw cursor\n");
402         s->draw_mouse = 0;
403         return;
404     }
405
406     x = xcim->x - xcim->xhot;
407     y = xcim->y - xcim->yhot;
408
409     to_line   = FFMIN((y + xcim->height), (height + y_off));
410     to_column = FFMIN((x + xcim->width),  (width  + x_off));
411
412     for (line = FFMAX(y, y_off); line < to_line; line++) {
413         for (column = FFMAX(x, x_off); column < to_column; column++) {
414             int xcim_addr  = (line  - y)     * xcim->width + column - x;
415             int image_addr = ((line - y_off) * width       + column - x_off) * pixstride;
416             int r          = (uint8_t)(xcim->pixels[xcim_addr] >>  0);
417             int g          = (uint8_t)(xcim->pixels[xcim_addr] >>  8);
418             int b          = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
419             int a          = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
420
421             if (a == 255) {
422                 pix[image_addr + 0] = r;
423                 pix[image_addr + 1] = g;
424                 pix[image_addr + 2] = b;
425             } else if (a) {
426                 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
427                 pix[image_addr + 0] = r + (pix[image_addr + 0] * (255 - a) + 255 / 2) / 255;
428                 pix[image_addr + 1] = g + (pix[image_addr + 1] * (255 - a) + 255 / 2) / 255;
429                 pix[image_addr + 2] = b + (pix[image_addr + 2] * (255 - a) + 255 / 2) / 255;
430             }
431         }
432     }
433
434     XFree(xcim);
435     xcim = NULL;
436 }
437
438 /**
439  * Read new data in the image structure.
440  *
441  * @param dpy X11 display to grab from
442  * @param d
443  * @param image Image where the grab will be put
444  * @param x Top-Left grabbing rectangle horizontal coordinate
445  * @param y Top-Left grabbing rectangle vertical coordinate
446  * @return 0 if error, !0 if successful
447  */
448 static int xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
449 {
450     xGetImageReply rep;
451     xGetImageReq *req;
452     long nbytes;
453
454     if (!image)
455         return 0;
456
457     LockDisplay(dpy);
458     GetReq(GetImage, req);
459
460     /* First set up the standard stuff in the request */
461     req->drawable  = d;
462     req->x         = x;
463     req->y         = y;
464     req->width     = image->width;
465     req->height    = image->height;
466     req->planeMask = (unsigned int)AllPlanes;
467     req->format    = ZPixmap;
468
469     if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
470         UnlockDisplay(dpy);
471         SyncHandle();
472         return 0;
473     }
474
475     nbytes = (long)rep.length << 2;
476     _XReadPad(dpy, image->data, nbytes);
477
478     UnlockDisplay(dpy);
479     SyncHandle();
480     return 1;
481 }
482
483 /**
484  * Grab a frame from x11 (public device demuxer API).
485  *
486  * @param s1 Context from avformat core
487  * @param pkt Packet holding the brabbed frame
488  * @return frame size in bytes
489  */
490 static int x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
491 {
492     X11GrabContext *s = s1->priv_data;
493     Display *dpy      = s->dpy;
494     XImage *image     = s->image;
495     int x_off         = s->x_off;
496     int y_off         = s->y_off;
497     int follow_mouse  = s->follow_mouse;
498     int screen;
499     Window root;
500     int64_t curtime, delay;
501     struct timespec ts;
502
503     /* Calculate the time of the next frame */
504     s->time_frame += INT64_C(1000000);
505
506     /* wait based on the frame rate */
507     for (;;) {
508         curtime = av_gettime();
509         delay   = s->time_frame * av_q2d(s->time_base) - curtime;
510         if (delay <= 0) {
511             if (delay < INT64_C(-1000000) * av_q2d(s->time_base))
512                 s->time_frame += INT64_C(1000000);
513             break;
514         }
515         ts.tv_sec  = delay / 1000000;
516         ts.tv_nsec = (delay % 1000000) * 1000;
517         nanosleep(&ts, NULL);
518     }
519
520     av_init_packet(pkt);
521     pkt->data = image->data;
522     pkt->size = s->frame_size;
523     pkt->pts  = curtime;
524     if (s->palette_changed) {
525         uint8_t *pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
526                                                AVPALETTE_SIZE);
527         if (!pal) {
528             av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n");
529         } else {
530             memcpy(pal, s->palette, AVPALETTE_SIZE);
531             s->palette_changed = 0;
532         }
533     }
534
535     screen = DefaultScreen(dpy);
536     root   = RootWindow(dpy, screen);
537     if (follow_mouse) {
538         int screen_w, screen_h;
539         int pointer_x, pointer_y, _;
540         Window w;
541
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;
549         } else {
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;
560         }
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);
564
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);
569     }
570
571     if (s->show_region) {
572         if (s->region_win) {
573             XEvent evt = { .type = NoEventMask };
574             // Clean up the events, and do the initial draw or redraw.
575             while (XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask,
576                                    &evt))
577                 ;
578             if (evt.type)
579                 x11grab_draw_region_win(s);
580         } else {
581             x11grab_region_win_init(s);
582         }
583     }
584
585     if (s->use_shm) {
586         if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes))
587             av_log(s1, AV_LOG_INFO, "XShmGetImage() failed\n");
588     } else {
589         if (!xget_zpixmap(dpy, root, image, x_off, y_off))
590             av_log(s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
591     }
592
593     if (s->draw_mouse)
594         paint_mouse_pointer(image, s1);
595
596     return s->frame_size;
597 }
598
599 /**
600  * Close x11 frame grabber (public device demuxer API).
601  *
602  * @param s1 Context from avformat core
603  * @return 0 success, !0 failure
604  */
605 static int x11grab_read_close(AVFormatContext *s1)
606 {
607     X11GrabContext *x11grab = s1->priv_data;
608
609     /* Detach cleanly from shared mem */
610     if (x11grab->use_shm) {
611         XShmDetach(x11grab->dpy, &x11grab->shminfo);
612         shmdt(x11grab->shminfo.shmaddr);
613         shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
614     }
615
616     /* Destroy X11 image */
617     if (x11grab->image) {
618         XDestroyImage(x11grab->image);
619         x11grab->image = NULL;
620     }
621
622     if (x11grab->region_win)
623         XDestroyWindow(x11grab->dpy, x11grab->region_win);
624
625     /* Free X11 display */
626     XCloseDisplay(x11grab->dpy);
627     return 0;
628 }
629
630 #define OFFSET(x) offsetof(X11GrabContext, x)
631 #define DEC AV_OPT_FLAG_DECODING_PARAM
632 static const AVOption options[] = {
633     { "draw_mouse", "draw the mouse pointer", OFFSET(draw_mouse), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
634
635     { "follow_mouse", "move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region",
636       OFFSET(follow_mouse), AV_OPT_TYPE_INT, {.i64 = 0}, -1, INT_MAX, DEC, "follow_mouse" },
637     { "centered",     "keep the mouse pointer at the center of grabbing region when following",
638       0, AV_OPT_TYPE_CONST, {.i64 = -1}, INT_MIN, INT_MAX, DEC, "follow_mouse" },
639
640     { "framerate",  "set video frame rate",      OFFSET(framerate),   AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, 0, DEC },
641     { "show_region", "show the grabbing region", OFFSET(show_region), AV_OPT_TYPE_INT,        {.i64 = 0}, 0, 1, DEC },
642     { "video_size",  "set video frame size",     OFFSET(width),       AV_OPT_TYPE_IMAGE_SIZE, {.str = "vga"}, 0, 0, DEC },
643     { "use_shm",     "use MIT-SHM extension",    OFFSET(use_shm),     AV_OPT_TYPE_INT,        {.i64 = 1}, 0, 1, DEC },
644     { NULL },
645 };
646
647 static const AVClass x11_class = {
648     .class_name = "X11grab indev",
649     .item_name  = av_default_item_name,
650     .option     = options,
651     .version    = LIBAVUTIL_VERSION_INT,
652     .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
653 };
654
655 /** x11 grabber device demuxer declaration */
656 AVInputFormat ff_x11grab_demuxer = {
657     .name           = "x11grab",
658     .long_name      = NULL_IF_CONFIG_SMALL("X11grab"),
659     .priv_data_size = sizeof(X11GrabContext),
660     .read_header    = x11grab_read_header,
661     .read_packet    = x11grab_read_packet,
662     .read_close     = x11grab_read_close,
663     .flags          = AVFMT_NOFILE,
664     .priv_class     = &x11_class,
665 };