]> git.sesse.net Git - ffmpeg/blob - libavdevice/x11grab.c
Merge commit '142e76f1055de5dde44696e71a5f63f2cb11dedf'
[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 by Clemens Fruhwirth <clemens@endorphin.org>
35  * and Edouard Gomez <ed.gomez@free.fr>.
36  */
37
38 #include "config.h"
39 #include "libavutil/log.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/parseutils.h"
42 #include <time.h>
43 #include <X11/X.h>
44 #include <X11/Xlib.h>
45 #include <X11/Xlibint.h>
46 #include <X11/Xproto.h>
47 #include <X11/Xutil.h>
48 #include <sys/shm.h>
49 #include <X11/extensions/XShm.h>
50 #include <X11/extensions/Xfixes.h>
51 #include "avdevice.h"
52
53 /**
54  * X11 Device Demuxer context
55  */
56 struct x11_grab
57 {
58     const AVClass *class;    /**< Class for private options. */
59     int frame_size;          /**< Size in bytes of a grabbed frame */
60     AVRational time_base;    /**< Time base */
61     int64_t time_frame;      /**< Current time */
62
63     char *video_size;        /**< String describing video size, set by a private option. */
64     int height;              /**< Height of the grab frame */
65     int width;               /**< Width of the grab frame */
66     int x_off;               /**< Horizontal top-left corner coordinate */
67     int y_off;               /**< Vertical top-left corner coordinate */
68
69     Display *dpy;            /**< X11 display from which x11grab grabs frames */
70     XImage *image;           /**< X11 image holding the grab */
71     int use_shm;             /**< !0 when using XShm extension */
72     XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
73     int  draw_mouse;         /**< Set by a private option. */
74     char *framerate;         /**< Set by a private option. */
75 };
76
77 /**
78  * Initialize the x11 grab device demuxer (public device demuxer API).
79  *
80  * @param s1 Context from avformat core
81  * @param ap Parameters from avformat core
82  * @return <ul>
83  *          <li>AVERROR(ENOMEM) no memory left</li>
84  *          <li>AVERROR(EIO) other failure case</li>
85  *          <li>0 success</li>
86  *         </ul>
87  */
88 static int
89 x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
90 {
91     struct x11_grab *x11grab = s1->priv_data;
92     Display *dpy;
93     AVStream *st = NULL;
94     enum PixelFormat input_pixfmt;
95     XImage *image;
96     int x_off = 0;
97     int y_off = 0;
98     int use_shm;
99     char *dpyname, *offset;
100     int ret = 0;
101     AVRational framerate;
102
103     dpyname = av_strdup(s1->filename);
104     offset = strchr(dpyname, '+');
105     if (offset) {
106         sscanf(offset, "%d,%d", &x_off, &y_off);
107         x11grab->draw_mouse = !strstr(offset, "nomouse");
108         *offset= 0;
109     }
110
111     if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) {
112         av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
113         goto out;
114     }
115     if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) {
116         av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate);
117         goto out;
118     }
119 #if FF_API_FORMAT_PARAMETERS
120     if (ap->width > 0)
121         x11grab->width = ap->width;
122     if (ap->height > 0)
123         x11grab->height = ap->height;
124     if (ap->time_base.num)
125         framerate = (AVRational){ap->time_base.den, ap->time_base.num};
126 #endif
127     av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
128            s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);
129
130     dpy = XOpenDisplay(dpyname);
131     av_freep(&dpyname);
132     if(!dpy) {
133         av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
134         ret = AVERROR(EIO);
135         goto out;
136     }
137
138     st = av_new_stream(s1, 0);
139     if (!st) {
140         ret = AVERROR(ENOMEM);
141         goto out;
142     }
143     av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
144
145     use_shm = XShmQueryExtension(dpy);
146     av_log(s1, AV_LOG_INFO, "shared memory extension%s found\n", use_shm ? "" : " not");
147
148     if(use_shm) {
149         int scr = XDefaultScreen(dpy);
150         image = XShmCreateImage(dpy,
151                                 DefaultVisual(dpy, scr),
152                                 DefaultDepth(dpy, scr),
153                                 ZPixmap,
154                                 NULL,
155                                 &x11grab->shminfo,
156                                 x11grab->width, x11grab->height);
157         x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
158                                         image->bytes_per_line * image->height,
159                                         IPC_CREAT|0777);
160         if (x11grab->shminfo.shmid == -1) {
161             av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
162             ret = AVERROR(ENOMEM);
163             goto out;
164         }
165         x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
166         x11grab->shminfo.readOnly = False;
167
168         if (!XShmAttach(dpy, &x11grab->shminfo)) {
169             av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
170             /* needs some better error subroutine :) */
171             ret = AVERROR(EIO);
172             goto out;
173         }
174     } else {
175         image = XGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)),
176                           x_off,y_off,
177                           x11grab->width, x11grab->height,
178                           AllPlanes, ZPixmap);
179     }
180
181     switch (image->bits_per_pixel) {
182     case 8:
183         av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
184         input_pixfmt = PIX_FMT_PAL8;
185         break;
186     case 16:
187         if (       image->red_mask   == 0xf800 &&
188                    image->green_mask == 0x07e0 &&
189                    image->blue_mask  == 0x001f ) {
190             av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
191             input_pixfmt = PIX_FMT_RGB565;
192         } else if (image->red_mask   == 0x7c00 &&
193                    image->green_mask == 0x03e0 &&
194                    image->blue_mask  == 0x001f ) {
195             av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
196             input_pixfmt = PIX_FMT_RGB555;
197         } else {
198             av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
199             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);
200             ret = AVERROR(EIO);
201             goto out;
202         }
203         break;
204     case 24:
205         if (        image->red_mask   == 0xff0000 &&
206                     image->green_mask == 0x00ff00 &&
207                     image->blue_mask  == 0x0000ff ) {
208             input_pixfmt = PIX_FMT_BGR24;
209         } else if ( image->red_mask   == 0x0000ff &&
210                     image->green_mask == 0x00ff00 &&
211                     image->blue_mask  == 0xff0000 ) {
212             input_pixfmt = PIX_FMT_RGB24;
213         } else {
214             av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
215             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);
216             ret = AVERROR(EIO);
217             goto out;
218         }
219         break;
220     case 32:
221         input_pixfmt = PIX_FMT_RGB32;
222         break;
223     default:
224         av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
225         ret = AVERROR(EINVAL);
226         goto out;
227     }
228
229     x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
230     x11grab->dpy = dpy;
231     x11grab->time_base  = (AVRational){framerate.den, framerate.num};
232     x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
233     x11grab->x_off = x_off;
234     x11grab->y_off = y_off;
235     x11grab->image = image;
236     x11grab->use_shm = use_shm;
237
238     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
239     st->codec->codec_id = CODEC_ID_RAWVIDEO;
240     st->codec->width  = x11grab->width;
241     st->codec->height = x11grab->height;
242     st->codec->pix_fmt = input_pixfmt;
243     st->codec->time_base = x11grab->time_base;
244     st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;
245
246 out:
247     return ret;
248 }
249
250 /**
251  * Paint a mouse pointer in an X11 image.
252  *
253  * @param image image to paint the mouse pointer to
254  * @param s context used to retrieve original grabbing rectangle
255  *          coordinates
256  */
257 static void
258 paint_mouse_pointer(XImage *image, struct x11_grab *s)
259 {
260     int x_off = s->x_off;
261     int y_off = s->y_off;
262     int width = s->width;
263     int height = s->height;
264     Display *dpy = s->dpy;
265     XFixesCursorImage *xcim;
266     int x, y;
267     int line, column;
268     int to_line, to_column;
269     int pixstride = image->bits_per_pixel >> 3;
270     /* Warning: in its insanity, xlib provides unsigned image data through a
271      * char* pointer, so we have to make it uint8_t to make things not break.
272      * Anyone who performs further investigation of the xlib API likely risks
273      * permanent brain damage. */
274     uint8_t *pix = image->data;
275
276     /* Code doesn't currently support 16-bit or PAL8 */
277     if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
278         return;
279
280     xcim = XFixesGetCursorImage(dpy);
281
282     x = xcim->x - xcim->xhot;
283     y = xcim->y - xcim->yhot;
284
285     to_line = FFMIN((y + xcim->height), (height + y_off));
286     to_column = FFMIN((x + xcim->width), (width + x_off));
287
288     for (line = FFMAX(y, y_off); line < to_line; line++) {
289         for (column = FFMAX(x, x_off); column < to_column; column++) {
290             int  xcim_addr = (line - y) * xcim->width + column - x;
291             int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
292             int r = (uint8_t)(xcim->pixels[xcim_addr] >>  0);
293             int g = (uint8_t)(xcim->pixels[xcim_addr] >>  8);
294             int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
295             int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
296
297             if (a == 255) {
298                 pix[image_addr+0] = r;
299                 pix[image_addr+1] = g;
300                 pix[image_addr+2] = b;
301             } else if (a) {
302                 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
303                 pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
304                 pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
305                 pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
306             }
307         }
308     }
309
310     XFree(xcim);
311     xcim = NULL;
312 }
313
314
315 /**
316  * Read new data in the image structure.
317  *
318  * @param dpy X11 display to grab from
319  * @param d
320  * @param image Image where the grab will be put
321  * @param x Top-Left grabbing rectangle horizontal coordinate
322  * @param y Top-Left grabbing rectangle vertical coordinate
323  * @return 0 if error, !0 if successful
324  */
325 static int
326 xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
327 {
328     xGetImageReply rep;
329     xGetImageReq *req;
330     long nbytes;
331
332     if (!image) {
333         return 0;
334     }
335
336     LockDisplay(dpy);
337     GetReq(GetImage, req);
338
339     /* First set up the standard stuff in the request */
340     req->drawable = d;
341     req->x = x;
342     req->y = y;
343     req->width = image->width;
344     req->height = image->height;
345     req->planeMask = (unsigned int)AllPlanes;
346     req->format = ZPixmap;
347
348     if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
349         UnlockDisplay(dpy);
350         SyncHandle();
351         return 0;
352     }
353
354     nbytes = (long)rep.length << 2;
355     _XReadPad(dpy, image->data, nbytes);
356
357     UnlockDisplay(dpy);
358     SyncHandle();
359     return 1;
360 }
361
362 /**
363  * Grab a frame from x11 (public device demuxer API).
364  *
365  * @param s1 Context from avformat core
366  * @param pkt Packet holding the brabbed frame
367  * @return frame size in bytes
368  */
369 static int
370 x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
371 {
372     struct x11_grab *s = s1->priv_data;
373     Display *dpy = s->dpy;
374     XImage *image = s->image;
375     int x_off = s->x_off;
376     int y_off = s->y_off;
377
378     int64_t curtime, delay;
379     struct timespec ts;
380
381     /* Calculate the time of the next frame */
382     s->time_frame += INT64_C(1000000);
383
384     /* wait based on the frame rate */
385     for(;;) {
386         curtime = av_gettime();
387         delay = s->time_frame * av_q2d(s->time_base) - curtime;
388         if (delay <= 0) {
389             if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
390                 s->time_frame += INT64_C(1000000);
391             }
392             break;
393         }
394         ts.tv_sec = delay / 1000000;
395         ts.tv_nsec = (delay % 1000000) * 1000;
396         nanosleep(&ts, NULL);
397     }
398
399     av_init_packet(pkt);
400     pkt->data = image->data;
401     pkt->size = s->frame_size;
402     pkt->pts = curtime;
403
404     if(s->use_shm) {
405         if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
406             av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
407         }
408     } else {
409         if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
410             av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
411         }
412     }
413
414     if (s->draw_mouse) {
415         paint_mouse_pointer(image, s);
416     }
417
418     return s->frame_size;
419 }
420
421 /**
422  * Close x11 frame grabber (public device demuxer API).
423  *
424  * @param s1 Context from avformat core
425  * @return 0 success, !0 failure
426  */
427 static int
428 x11grab_read_close(AVFormatContext *s1)
429 {
430     struct x11_grab *x11grab = s1->priv_data;
431
432     /* Detach cleanly from shared mem */
433     if (x11grab->use_shm) {
434         XShmDetach(x11grab->dpy, &x11grab->shminfo);
435         shmdt(x11grab->shminfo.shmaddr);
436         shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
437     }
438
439     /* Destroy X11 image */
440     if (x11grab->image) {
441         XDestroyImage(x11grab->image);
442         x11grab->image = NULL;
443     }
444
445     /* Free X11 display */
446     XCloseDisplay(x11grab->dpy);
447     return 0;
448 }
449
450 #define OFFSET(x) offsetof(struct x11_grab, x)
451 #define DEC AV_OPT_FLAG_DECODING_PARAM
452 static const AVOption options[] = {
453     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = "vga"}, 0, 0, DEC },
454     { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
455     { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), FF_OPT_TYPE_INT, { 1 }, 0, 1, DEC },
456     { NULL },
457 };
458
459 static const AVClass x11_class = {
460     .class_name = "X11grab indev",
461     .item_name  = av_default_item_name,
462     .option     = options,
463     .version    = LIBAVUTIL_VERSION_INT,
464 };
465
466 /** x11 grabber device demuxer declaration */
467 AVInputFormat ff_x11_grab_device_demuxer =
468 {
469     "x11grab",
470     NULL_IF_CONFIG_SMALL("X11grab"),
471     sizeof(struct x11_grab),
472     NULL,
473     x11grab_read_header,
474     x11grab_read_packet,
475     x11grab_read_close,
476     .flags = AVFMT_NOFILE,
477     .priv_class = &x11_class,
478 };