]> 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 "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 nomouse;
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->nomouse= 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 #if 0
222         GetColorInfo (image, &c_info);
223         if ( c_info.alpha_mask == 0xff000000 && image->green_mask == 0x0000ff00) {
224             /* byte order is relevant here, not endianness
225              * endianness is handled by avcodec, but atm no such thing
226              * as having ABGR, instead of ARGB in a word. Since we
227              * need this for Solaris/SPARC, but need to do the conversion
228              * for every frame we do it outside of this loop, cf. below
229              * this matches both ARGB32 and ABGR32 */
230             input_pixfmt = PIX_FMT_ARGB32;
231         }  else {
232             av_log(s1, AV_LOG_ERROR,"image depth %i not supported ... aborting\n", image->bits_per_pixel);
233             return AVERROR(EIO);
234         }
235 #endif
236         input_pixfmt = PIX_FMT_RGB32;
237         break;
238     default:
239         av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
240         ret = AVERROR(EINVAL);
241         goto out;
242     }
243
244     x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
245     x11grab->dpy = dpy;
246     x11grab->time_base  = (AVRational){framerate.den, framerate.num};
247     x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
248     x11grab->x_off = x_off;
249     x11grab->y_off = y_off;
250     x11grab->image = image;
251     x11grab->use_shm = use_shm;
252
253     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
254     st->codec->codec_id = CODEC_ID_RAWVIDEO;
255     st->codec->width  = x11grab->width;
256     st->codec->height = x11grab->height;
257     st->codec->pix_fmt = input_pixfmt;
258     st->codec->time_base = x11grab->time_base;
259     st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;
260
261 out:
262     return ret;
263 }
264
265 /**
266  * Paint a mouse pointer in an X11 image.
267  *
268  * @param image image to paint the mouse pointer to
269  * @param s context used to retrieve original grabbing rectangle
270  *          coordinates
271  */
272 static void
273 paint_mouse_pointer(XImage *image, struct x11_grab *s)
274 {
275     int x_off = s->x_off;
276     int y_off = s->y_off;
277     int width = s->width;
278     int height = s->height;
279     Display *dpy = s->dpy;
280     XFixesCursorImage *xcim;
281     int x, y;
282     int line, column;
283     int to_line, to_column;
284     int pixstride = image->bits_per_pixel >> 3;
285     /* Warning: in its insanity, xlib provides unsigned image data through a
286      * char* pointer, so we have to make it uint8_t to make things not break.
287      * Anyone who performs further investigation of the xlib API likely risks
288      * permanent brain damage. */
289     uint8_t *pix = image->data;
290
291     /* Code doesn't currently support 16-bit or PAL8 */
292     if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
293         return;
294
295     xcim = XFixesGetCursorImage(dpy);
296
297     x = xcim->x - xcim->xhot;
298     y = xcim->y - xcim->yhot;
299
300     to_line = FFMIN((y + xcim->height), (height + y_off));
301     to_column = FFMIN((x + xcim->width), (width + x_off));
302
303     for (line = FFMAX(y, y_off); line < to_line; line++) {
304         for (column = FFMAX(x, x_off); column < to_column; column++) {
305             int  xcim_addr = (line - y) * xcim->width + column - x;
306             int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
307             int r = (uint8_t)(xcim->pixels[xcim_addr] >>  0);
308             int g = (uint8_t)(xcim->pixels[xcim_addr] >>  8);
309             int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
310             int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
311
312             if (a == 255) {
313                 pix[image_addr+0] = r;
314                 pix[image_addr+1] = g;
315                 pix[image_addr+2] = b;
316             } else if (a) {
317                 /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
318                 pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
319                 pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
320                 pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
321             }
322         }
323     }
324
325     XFree(xcim);
326     xcim = NULL;
327 }
328
329
330 /**
331  * Read new data in the image structure.
332  *
333  * @param dpy X11 display to grab from
334  * @param d
335  * @param image Image where the grab will be put
336  * @param x Top-Left grabbing rectangle horizontal coordinate
337  * @param y Top-Left grabbing rectangle vertical coordinate
338  * @return 0 if error, !0 if successful
339  */
340 static int
341 xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
342 {
343     xGetImageReply rep;
344     xGetImageReq *req;
345     long nbytes;
346
347     if (!image) {
348         return 0;
349     }
350
351     LockDisplay(dpy);
352     GetReq(GetImage, req);
353
354     /* First set up the standard stuff in the request */
355     req->drawable = d;
356     req->x = x;
357     req->y = y;
358     req->width = image->width;
359     req->height = image->height;
360     req->planeMask = (unsigned int)AllPlanes;
361     req->format = ZPixmap;
362
363     if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
364         UnlockDisplay(dpy);
365         SyncHandle();
366         return 0;
367     }
368
369     nbytes = (long)rep.length << 2;
370     _XReadPad(dpy, image->data, nbytes);
371
372     UnlockDisplay(dpy);
373     SyncHandle();
374     return 1;
375 }
376
377 /**
378  * Grab a frame from x11 (public device demuxer API).
379  *
380  * @param s1 Context from avformat core
381  * @param pkt Packet holding the brabbed frame
382  * @return frame size in bytes
383  */
384 static int
385 x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
386 {
387     struct x11_grab *s = s1->priv_data;
388     Display *dpy = s->dpy;
389     XImage *image = s->image;
390     int x_off = s->x_off;
391     int y_off = s->y_off;
392
393     int64_t curtime, delay;
394     struct timespec ts;
395
396     /* Calculate the time of the next frame */
397     s->time_frame += INT64_C(1000000);
398
399     /* wait based on the frame rate */
400     for(;;) {
401         curtime = av_gettime();
402         delay = s->time_frame * av_q2d(s->time_base) - curtime;
403         if (delay <= 0) {
404             if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
405                 s->time_frame += INT64_C(1000000);
406             }
407             break;
408         }
409         ts.tv_sec = delay / 1000000;
410         ts.tv_nsec = (delay % 1000000) * 1000;
411         nanosleep(&ts, NULL);
412     }
413
414     av_init_packet(pkt);
415     pkt->data = image->data;
416     pkt->size = s->frame_size;
417     pkt->pts = curtime;
418
419     if(s->use_shm) {
420         if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
421             av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
422         }
423     } else {
424         if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
425             av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
426         }
427     }
428
429     if(!s->nomouse){
430         paint_mouse_pointer(image, s);
431     }
432
433     return s->frame_size;
434 }
435
436 /**
437  * Close x11 frame grabber (public device demuxer API).
438  *
439  * @param s1 Context from avformat core
440  * @return 0 success, !0 failure
441  */
442 static int
443 x11grab_read_close(AVFormatContext *s1)
444 {
445     struct x11_grab *x11grab = s1->priv_data;
446
447     /* Detach cleanly from shared mem */
448     if (x11grab->use_shm) {
449         XShmDetach(x11grab->dpy, &x11grab->shminfo);
450         shmdt(x11grab->shminfo.shmaddr);
451         shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
452     }
453
454     /* Destroy X11 image */
455     if (x11grab->image) {
456         XDestroyImage(x11grab->image);
457         x11grab->image = NULL;
458     }
459
460     /* Free X11 display */
461     XCloseDisplay(x11grab->dpy);
462     return 0;
463 }
464
465 #define OFFSET(x) offsetof(struct x11_grab, x)
466 #define DEC AV_OPT_FLAG_DECODING_PARAM
467 static const AVOption options[] = {
468     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = "vga"}, 0, 0, DEC },
469     { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
470     { NULL },
471 };
472
473 static const AVClass x11_class = {
474     .class_name = "X11grab indev",
475     .item_name  = av_default_item_name,
476     .option     = options,
477     .version    = LIBAVUTIL_VERSION_INT,
478 };
479
480 /** x11 grabber device demuxer declaration */
481 AVInputFormat ff_x11_grab_device_demuxer =
482 {
483     "x11grab",
484     NULL_IF_CONFIG_SMALL("X11grab"),
485     sizeof(struct x11_grab),
486     NULL,
487     x11grab_read_header,
488     x11grab_read_packet,
489     x11grab_read_close,
490     .flags = AVFMT_NOFILE,
491     .priv_class = &x11_class,
492 };