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