x11grab.c 23 KB

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