FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
x11grab.c
Go to the documentation of this file.
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
35  * @author Clemens Fruhwirth <clemens@endorphin.org>
36  * @author Edouard Gomez <ed.gomez@free.fr>
37  */
38 
39 #include "config.h"
40 #include "libavformat/internal.h"
41 #include "libavutil/log.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/parseutils.h"
44 #include "libavutil/time.h"
45 #include <time.h>
46 #include <X11/cursorfont.h>
47 #include <X11/X.h>
48 #include <X11/Xlib.h>
49 #include <X11/Xlibint.h>
50 #include <X11/Xproto.h>
51 #include <X11/Xutil.h>
52 #include <sys/shm.h>
53 #include <X11/extensions/shape.h>
54 #include <X11/extensions/XShm.h>
55 #include <X11/extensions/Xfixes.h>
56 #include "avdevice.h"
57 
58 /**
59  * X11 Device Demuxer context
60  */
61 struct x11grab {
62  const AVClass *class; /**< Class for private options. */
63  int frame_size; /**< Size in bytes of a grabbed frame */
64  AVRational time_base; /**< Time base */
65  int64_t time_frame; /**< Current time */
66 
67  int width; /**< Width of the grab frame */
68  int height; /**< Height of the grab frame */
69  int x_off; /**< Horizontal top-left corner coordinate */
70  int y_off; /**< Vertical top-left corner coordinate */
71 
72  Display *dpy; /**< X11 display from which x11grab grabs frames */
73  XImage *image; /**< X11 image holding the grab */
74  int use_shm; /**< !0 when using XShm extension */
75  XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
76  int draw_mouse; /**< Set by a private option. */
77  int follow_mouse; /**< Set by a private option. */
78  int show_region; /**< set by a private option. */
79  char *framerate; /**< Set by a private option. */
80 
81  Cursor c;
82  Window region_win; /**< This is used by show_region option. */
83 };
84 
85 #define REGION_WIN_BORDER 3
86 /**
87  * Draw grabbing region window
88  *
89  * @param s x11grab context
90  */
91 static void
93 {
94  Display *dpy = s->dpy;
95  int screen;
96  Window win = s->region_win;
97  GC gc;
98 
99  screen = DefaultScreen(dpy);
100  gc = XCreateGC(dpy, win, 0, 0);
101  XSetForeground(dpy, gc, WhitePixel(dpy, screen));
102  XSetBackground(dpy, gc, BlackPixel(dpy, screen));
103  XSetLineAttributes(dpy, gc, REGION_WIN_BORDER, LineDoubleDash, 0, 0);
104  XDrawRectangle(dpy, win, gc,
105  1, 1,
106  (s->width + REGION_WIN_BORDER * 2) - 1 * 2 - 1,
107  (s->height + REGION_WIN_BORDER * 2) - 1 * 2 - 1);
108  XFreeGC(dpy, gc);
109 }
110 
111 /**
112  * Initialize grabbing region window
113  *
114  * @param s x11grab context
115  */
116 static void
118 {
119  Display *dpy = s->dpy;
120  int screen;
121  XSetWindowAttributes attribs;
122  XRectangle rect;
123 
124  screen = DefaultScreen(dpy);
125  attribs.override_redirect = True;
126  s->region_win = XCreateWindow(dpy, RootWindow(dpy, screen),
129  s->width + REGION_WIN_BORDER * 2,
130  s->height + REGION_WIN_BORDER * 2,
131  0, CopyFromParent,
132  InputOutput, CopyFromParent,
133  CWOverrideRedirect, &attribs);
134  rect.x = 0;
135  rect.y = 0;
136  rect.width = s->width;
137  rect.height = s->height;
138  XShapeCombineRectangles(dpy, s->region_win,
139  ShapeBounding, REGION_WIN_BORDER, REGION_WIN_BORDER,
140  &rect, 1, ShapeSubtract, 0);
141  XMapWindow(dpy, s->region_win);
142  XSelectInput(dpy, s->region_win, ExposureMask | StructureNotifyMask);
144 }
145 
146 /**
147  * Initialize the x11 grab device demuxer (public device demuxer API).
148  *
149  * @param s1 Context from avformat core
150  * @return <ul>
151  * <li>AVERROR(ENOMEM) no memory left</li>
152  * <li>AVERROR(EIO) other failure case</li>
153  * <li>0 success</li>
154  * </ul>
155  */
156 static int
158 {
159  struct x11grab *x11grab = s1->priv_data;
160  Display *dpy;
161  AVStream *st = NULL;
162  enum AVPixelFormat input_pixfmt;
163  XImage *image;
164  int x_off = 0;
165  int y_off = 0;
166  int screen;
167  int use_shm;
168  char *dpyname, *offset;
169  int ret = 0;
171 
172  dpyname = av_strdup(s1->filename);
173  if (!dpyname)
174  goto out;
175 
176  offset = strchr(dpyname, '+');
177  if (offset) {
178  sscanf(offset, "%d,%d", &x_off, &y_off);
179  if (strstr(offset, "nomouse")) {
181  "'nomouse' specification in argument is deprecated: "
182  "use 'draw_mouse' option with value 0 instead\n");
183  x11grab->draw_mouse = 0;
184  }
185  *offset= 0;
186  }
187 
188  if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) {
189  av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate);
190  goto out;
191  }
192  av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
193  s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);
194 
195  dpy = XOpenDisplay(dpyname);
196  av_freep(&dpyname);
197  if(!dpy) {
198  av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
199  ret = AVERROR(EIO);
200  goto out;
201  }
202 
203  st = avformat_new_stream(s1, NULL);
204  if (!st) {
205  ret = AVERROR(ENOMEM);
206  goto out;
207  }
208  avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
209 
210  screen = DefaultScreen(dpy);
211 
212  if (x11grab->follow_mouse) {
213  int screen_w, screen_h;
214  Window w;
215 
216  screen_w = DisplayWidth(dpy, screen);
217  screen_h = DisplayHeight(dpy, screen);
218  XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret);
219  x_off -= x11grab->width / 2;
220  y_off -= x11grab->height / 2;
221  x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
222  y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
223  av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off);
224  }
225 
226  use_shm = XShmQueryExtension(dpy);
227  av_log(s1, AV_LOG_INFO, "shared memory extension%s found\n", use_shm ? "" : " not");
228 
229  if(use_shm) {
230  int scr = XDefaultScreen(dpy);
231  image = XShmCreateImage(dpy,
232  DefaultVisual(dpy, scr),
233  DefaultDepth(dpy, scr),
234  ZPixmap,
235  NULL,
236  &x11grab->shminfo,
237  x11grab->width, x11grab->height);
238  x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
239  image->bytes_per_line * image->height,
240  IPC_CREAT|0777);
241  if (x11grab->shminfo.shmid == -1) {
242  av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
243  ret = AVERROR(ENOMEM);
244  goto out;
245  }
246  x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
247  x11grab->shminfo.readOnly = False;
248 
249  if (!XShmAttach(dpy, &x11grab->shminfo)) {
250  av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
251  /* needs some better error subroutine :) */
252  ret = AVERROR(EIO);
253  goto out;
254  }
255  } else {
256  image = XGetImage(dpy, RootWindow(dpy, screen),
257  x_off,y_off,
258  x11grab->width, x11grab->height,
259  AllPlanes, ZPixmap);
260  }
261 
262  switch (image->bits_per_pixel) {
263  case 8:
264  av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
265  input_pixfmt = AV_PIX_FMT_PAL8;
266  break;
267  case 16:
268  if ( image->red_mask == 0xf800 &&
269  image->green_mask == 0x07e0 &&
270  image->blue_mask == 0x001f ) {
271  av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
272  input_pixfmt = AV_PIX_FMT_RGB565;
273  } else if (image->red_mask == 0x7c00 &&
274  image->green_mask == 0x03e0 &&
275  image->blue_mask == 0x001f ) {
276  av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
277  input_pixfmt = AV_PIX_FMT_RGB555;
278  } else {
279  av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
280  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);
281  ret = AVERROR(EIO);
282  goto out;
283  }
284  break;
285  case 24:
286  if ( image->red_mask == 0xff0000 &&
287  image->green_mask == 0x00ff00 &&
288  image->blue_mask == 0x0000ff ) {
289  input_pixfmt = AV_PIX_FMT_BGR24;
290  } else if ( image->red_mask == 0x0000ff &&
291  image->green_mask == 0x00ff00 &&
292  image->blue_mask == 0xff0000 ) {
293  input_pixfmt = AV_PIX_FMT_RGB24;
294  } else {
295  av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
296  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);
297  ret = AVERROR(EIO);
298  goto out;
299  }
300  break;
301  case 32:
302  input_pixfmt = AV_PIX_FMT_0RGB32;
303  break;
304  default:
305  av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
306  ret = AVERROR(EINVAL);
307  goto out;
308  }
309 
310  x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
311  x11grab->dpy = dpy;
312  x11grab->time_base = av_inv_q(framerate);
313  x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
314  x11grab->x_off = x_off;
315  x11grab->y_off = y_off;
316  x11grab->image = image;
317  x11grab->use_shm = use_shm;
318 
321  st->codec->width = x11grab->width;
322  st->codec->height = x11grab->height;
323  st->codec->pix_fmt = input_pixfmt;
324  st->codec->time_base = x11grab->time_base;
325  st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;
326 
327 out:
328  av_free(dpyname);
329  return ret;
330 }
331 
332 /**
333  * Paint a mouse pointer in an X11 image.
334  *
335  * @param image image to paint the mouse pointer to
336  * @param s context used to retrieve original grabbing rectangle
337  * coordinates
338  */
339 static void
341 {
342  int x_off = s->x_off;
343  int y_off = s->y_off;
344  int width = s->width;
345  int height = s->height;
346  Display *dpy = s->dpy;
347  XFixesCursorImage *xcim;
348  int x, y;
349  int line, column;
350  int to_line, to_column;
351  int pixstride = image->bits_per_pixel >> 3;
352  /* Warning: in its insanity, xlib provides unsigned image data through a
353  * char* pointer, so we have to make it uint8_t to make things not break.
354  * Anyone who performs further investigation of the xlib API likely risks
355  * permanent brain damage. */
356  uint8_t *pix = image->data;
357  Window w;
358  XSetWindowAttributes attr;
359 
360  /* Code doesn't currently support 16-bit or PAL8 */
361  if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
362  return;
363 
364  if(!s->c)
365  s->c = XCreateFontCursor(dpy, XC_left_ptr);
366  w = DefaultRootWindow(dpy);
367  attr.cursor = s->c;
368  XChangeWindowAttributes(dpy, w, CWCursor, &attr);
369 
370  xcim = XFixesGetCursorImage(dpy);
371 
372  x = xcim->x - xcim->xhot;
373  y = xcim->y - xcim->yhot;
374 
375  to_line = FFMIN((y + xcim->height), (height + y_off));
376  to_column = FFMIN((x + xcim->width), (width + x_off));
377 
378  for (line = FFMAX(y, y_off); line < to_line; line++) {
379  for (column = FFMAX(x, x_off); column < to_column; column++) {
380  int xcim_addr = (line - y) * xcim->width + column - x;
381  int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
382  int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
383  int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
384  int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
385  int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
386 
387  if (a == 255) {
388  pix[image_addr+0] = r;
389  pix[image_addr+1] = g;
390  pix[image_addr+2] = b;
391  } else if (a) {
392  /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
393  pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
394  pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
395  pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
396  }
397  }
398  }
399 
400  XFree(xcim);
401  xcim = NULL;
402 }
403 
404 
405 /**
406  * Read new data in the image structure.
407  *
408  * @param dpy X11 display to grab from
409  * @param d
410  * @param image Image where the grab will be put
411  * @param x Top-Left grabbing rectangle horizontal coordinate
412  * @param y Top-Left grabbing rectangle vertical coordinate
413  * @return 0 if error, !0 if successful
414  */
415 static int
416 xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
417 {
418  xGetImageReply rep;
419  xGetImageReq *req;
420  long nbytes;
421 
422  if (!image) {
423  return 0;
424  }
425 
426  LockDisplay(dpy);
427  GetReq(GetImage, req);
428 
429  /* First set up the standard stuff in the request */
430  req->drawable = d;
431  req->x = x;
432  req->y = y;
433  req->width = image->width;
434  req->height = image->height;
435  req->planeMask = (unsigned int)AllPlanes;
436  req->format = ZPixmap;
437 
438  if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
439  UnlockDisplay(dpy);
440  SyncHandle();
441  return 0;
442  }
443 
444  nbytes = (long)rep.length << 2;
445  _XReadPad(dpy, image->data, nbytes);
446 
447  UnlockDisplay(dpy);
448  SyncHandle();
449  return 1;
450 }
451 
452 /**
453  * Grab a frame from x11 (public device demuxer API).
454  *
455  * @param s1 Context from avformat core
456  * @param pkt Packet holding the brabbed frame
457  * @return frame size in bytes
458  */
459 static int
461 {
462  struct x11grab *s = s1->priv_data;
463  Display *dpy = s->dpy;
464  XImage *image = s->image;
465  int x_off = s->x_off;
466  int y_off = s->y_off;
467 
468  int screen;
469  Window root;
470  int follow_mouse = s->follow_mouse;
471 
472  int64_t curtime, delay;
473  struct timespec ts;
474 
475  /* Calculate the time of the next frame */
476  s->time_frame += INT64_C(1000000);
477 
478  /* wait based on the frame rate */
479  for(;;) {
480  curtime = av_gettime();
481  delay = s->time_frame * av_q2d(s->time_base) - curtime;
482  if (delay <= 0) {
483  if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
484  s->time_frame += INT64_C(1000000);
485  }
486  break;
487  }
488  ts.tv_sec = delay / 1000000;
489  ts.tv_nsec = (delay % 1000000) * 1000;
490  nanosleep(&ts, NULL);
491  }
492 
493  av_init_packet(pkt);
494  pkt->data = image->data;
495  pkt->size = s->frame_size;
496  pkt->pts = curtime;
497 
498  screen = DefaultScreen(dpy);
499  root = RootWindow(dpy, screen);
500  if (follow_mouse) {
501  int screen_w, screen_h;
502  int pointer_x, pointer_y, _;
503  Window w;
504 
505  screen_w = DisplayWidth(dpy, screen);
506  screen_h = DisplayHeight(dpy, screen);
507  XQueryPointer(dpy, root, &w, &w, &pointer_x, &pointer_y, &_, &_, &_);
508  if (follow_mouse == -1) {
509  // follow the mouse, put it at center of grabbing region
510  x_off += pointer_x - s->width / 2 - x_off;
511  y_off += pointer_y - s->height / 2 - y_off;
512  } else {
513  // follow the mouse, but only move the grabbing region when mouse
514  // reaches within certain pixels to the edge.
515  if (pointer_x > x_off + s->width - follow_mouse) {
516  x_off += pointer_x - (x_off + s->width - follow_mouse);
517  } else if (pointer_x < x_off + follow_mouse)
518  x_off -= (x_off + follow_mouse) - pointer_x;
519  if (pointer_y > y_off + s->height - follow_mouse) {
520  y_off += pointer_y - (y_off + s->height - follow_mouse);
521  } else if (pointer_y < y_off + follow_mouse)
522  y_off -= (y_off + follow_mouse) - pointer_y;
523  }
524  // adjust grabbing region position if it goes out of screen.
525  s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);
526  s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);
527 
528  if (s->show_region && s->region_win)
529  XMoveWindow(dpy, s->region_win,
531  s->y_off - REGION_WIN_BORDER);
532  }
533 
534  if (s->show_region) {
535  if (s->region_win) {
536  XEvent evt;
537  // clean up the events, and do the initinal draw or redraw.
538  for (evt.type = NoEventMask; XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask, &evt); );
539  if (evt.type)
541  } else {
543  }
544  }
545 
546  if(s->use_shm) {
547  if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes)) {
548  av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
549  }
550  } else {
551  if (!xget_zpixmap(dpy, root, image, x_off, y_off)) {
552  av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
553  }
554  }
555 
556  if (s->draw_mouse) {
557  paint_mouse_pointer(image, s);
558  }
559 
560  return s->frame_size;
561 }
562 
563 /**
564  * Close x11 frame grabber (public device demuxer API).
565  *
566  * @param s1 Context from avformat core
567  * @return 0 success, !0 failure
568  */
569 static int
571 {
572  struct x11grab *x11grab = s1->priv_data;
573 
574  /* Detach cleanly from shared mem */
575  if (x11grab->use_shm) {
576  XShmDetach(x11grab->dpy, &x11grab->shminfo);
577  shmdt(x11grab->shminfo.shmaddr);
578  shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
579  }
580 
581  /* Destroy X11 image */
582  if (x11grab->image) {
583  XDestroyImage(x11grab->image);
584  x11grab->image = NULL;
585  }
586 
587  if (x11grab->region_win) {
588  XDestroyWindow(x11grab->dpy, x11grab->region_win);
589  }
590 
591  /* Free X11 display */
592  XCloseDisplay(x11grab->dpy);
593  return 0;
594 }
595 
596 #define OFFSET(x) offsetof(struct x11grab, x)
597 #define DEC AV_OPT_FLAG_DECODING_PARAM
598 static const AVOption options[] = {
599  { "draw_mouse", "draw the mouse pointer", OFFSET(draw_mouse), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
600 
601  { "follow_mouse", "move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region",
602  OFFSET(follow_mouse), AV_OPT_TYPE_INT, {.i64 = 0}, -1, INT_MAX, DEC, "follow_mouse" },
603  { "centered", "keep the mouse pointer at the center of grabbing region when following",
604  0, AV_OPT_TYPE_CONST, {.i64 = -1}, INT_MIN, INT_MAX, DEC, "follow_mouse" },
605 
606  { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
607  { "show_region", "show the grabbing region", OFFSET(show_region), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
608  { "video_size", "set video frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = "vga"}, 0, 0, DEC },
609  { NULL },
610 };
611 
612 static const AVClass x11_class = {
613  .class_name = "X11grab indev",
614  .item_name = av_default_item_name,
615  .option = options,
616  .version = LIBAVUTIL_VERSION_INT,
617 };
618 
619 /** x11 grabber device demuxer declaration */
621  .name = "x11grab",
622  .long_name = NULL_IF_CONFIG_SMALL("X11grab"),
623  .priv_data_size = sizeof(struct x11grab),
624  .read_header = x11grab_read_header,
625  .read_packet = x11grab_read_packet,
626  .read_close = x11grab_read_close,
627  .flags = AVFMT_NOFILE,
628  .priv_class = &x11_class,
629 };