2 * X11 video grab interface
4 * This file is part of FFmpeg.
7 * Copyright (C) 2006 Clemens Fruhwirth <clemens@endorphin.org>
8 * Edouard Gomez <ed.gomez@free.fr>
10 * This file contains code from grab.c:
11 * Copyright (c) 2000-2001 Fabrice Bellard
13 * This file contains code from the xvidcap project:
14 * Copyright (C) 1997-1998 Rasca, Berlin
15 * 2003-2004 Karl H. Beckers, Frankfurt
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.
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.
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
34 * X11 frame device demuxer by Clemens Fruhwirth <clemens@endorphin.org>
35 * and Edouard Gomez <ed.gomez@free.fr>.
39 #include "libavutil/log.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/parseutils.h"
45 #include <X11/Xlibint.h>
46 #include <X11/Xproto.h>
47 #include <X11/Xutil.h>
49 #include <X11/extensions/XShm.h>
50 #include <X11/extensions/Xfixes.h>
54 * X11 Device Demuxer context
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 */
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 */
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. */
78 * Initialize the x11 grab device demuxer (public device demuxer API).
80 * @param s1 Context from avformat core
81 * @param ap Parameters from avformat core
83 * <li>AVERROR(ENOMEM) no memory left</li>
84 * <li>AVERROR(EIO) other failure case</li>
89 x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
91 struct x11_grab *x11grab = s1->priv_data;
94 enum PixelFormat input_pixfmt;
99 char *dpyname, *offset;
101 AVRational framerate;
103 dpyname = av_strdup(s1->filename);
104 offset = strchr(dpyname, '+');
106 sscanf(offset, "%d,%d", &x_off, &y_off);
107 x11grab->draw_mouse = !strstr(offset, "nomouse");
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");
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);
119 #if FF_API_FORMAT_PARAMETERS
121 x11grab->width = ap->width;
123 x11grab->height = ap->height;
124 if (ap->time_base.num)
125 framerate = (AVRational){ap->time_base.den, ap->time_base.num};
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);
130 dpy = XOpenDisplay(dpyname);
133 av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
138 st = av_new_stream(s1, 0);
140 ret = AVERROR(ENOMEM);
143 av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
145 use_shm = XShmQueryExtension(dpy);
146 av_log(s1, AV_LOG_INFO, "shared memory extension%s found\n", use_shm ? "" : " not");
149 int scr = XDefaultScreen(dpy);
150 image = XShmCreateImage(dpy,
151 DefaultVisual(dpy, scr),
152 DefaultDepth(dpy, scr),
156 x11grab->width, x11grab->height);
157 x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
158 image->bytes_per_line * image->height,
160 if (x11grab->shminfo.shmid == -1) {
161 av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
162 ret = AVERROR(ENOMEM);
165 x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
166 x11grab->shminfo.readOnly = False;
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 :) */
175 image = XGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)),
177 x11grab->width, x11grab->height,
181 switch (image->bits_per_pixel) {
183 av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
184 input_pixfmt = PIX_FMT_PAL8;
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;
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);
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;
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);
221 input_pixfmt = PIX_FMT_RGB32;
224 av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
225 ret = AVERROR(EINVAL);
229 x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
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;
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;
251 * Paint a mouse pointer in an X11 image.
253 * @param image image to paint the mouse pointer to
254 * @param s context used to retrieve original grabbing rectangle
258 paint_mouse_pointer(XImage *image, struct x11_grab *s)
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;
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;
276 /* Code doesn't currently support 16-bit or PAL8 */
277 if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
280 xcim = XFixesGetCursorImage(dpy);
282 x = xcim->x - xcim->xhot;
283 y = xcim->y - xcim->yhot;
285 to_line = FFMIN((y + xcim->height), (height + y_off));
286 to_column = FFMIN((x + xcim->width), (width + x_off));
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);
298 pix[image_addr+0] = r;
299 pix[image_addr+1] = g;
300 pix[image_addr+2] = b;
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;
316 * Read new data in the image structure.
318 * @param dpy X11 display to grab from
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
326 xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
337 GetReq(GetImage, req);
339 /* First set up the standard stuff in the request */
343 req->width = image->width;
344 req->height = image->height;
345 req->planeMask = (unsigned int)AllPlanes;
346 req->format = ZPixmap;
348 if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
354 nbytes = (long)rep.length << 2;
355 _XReadPad(dpy, image->data, nbytes);
363 * Grab a frame from x11 (public device demuxer API).
365 * @param s1 Context from avformat core
366 * @param pkt Packet holding the brabbed frame
367 * @return frame size in bytes
370 x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
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;
378 int64_t curtime, delay;
381 /* Calculate the time of the next frame */
382 s->time_frame += INT64_C(1000000);
384 /* wait based on the frame rate */
386 curtime = av_gettime();
387 delay = s->time_frame * av_q2d(s->time_base) - curtime;
389 if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
390 s->time_frame += INT64_C(1000000);
394 ts.tv_sec = delay / 1000000;
395 ts.tv_nsec = (delay % 1000000) * 1000;
396 nanosleep(&ts, NULL);
400 pkt->data = image->data;
401 pkt->size = s->frame_size;
405 if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
406 av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
409 if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
410 av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
415 paint_mouse_pointer(image, s);
418 return s->frame_size;
422 * Close x11 frame grabber (public device demuxer API).
424 * @param s1 Context from avformat core
425 * @return 0 success, !0 failure
428 x11grab_read_close(AVFormatContext *s1)
430 struct x11_grab *x11grab = s1->priv_data;
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);
439 /* Destroy X11 image */
440 if (x11grab->image) {
441 XDestroyImage(x11grab->image);
442 x11grab->image = NULL;
445 /* Free X11 display */
446 XCloseDisplay(x11grab->dpy);
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 },
459 static const AVClass x11_class = {
460 .class_name = "X11grab indev",
461 .item_name = av_default_item_name,
463 .version = LIBAVUTIL_VERSION_INT,
466 /** x11 grabber device demuxer declaration */
467 AVInputFormat ff_x11_grab_device_demuxer =
470 NULL_IF_CONFIG_SMALL("X11grab"),
471 sizeof(struct x11_grab),
476 .flags = AVFMT_NOFILE,
477 .priv_class = &x11_class,