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