x11grab.c 23 KB

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