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