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