x11grab.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 libavdevice/x11grab.c
  33. * X11 frame device demuxer by Clemens Fruhwirth <clemens@endorphin.org>
  34. * and Edouard Gomez <ed.gomez@free.fr>.
  35. */
  36. #include "config.h"
  37. #include "libavformat/avformat.h"
  38. #include <unistd.h>
  39. #include <fcntl.h>
  40. #include <sys/ioctl.h>
  41. #include <sys/time.h>
  42. #define _LINUX_TIME_H 1
  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/ipc.h>
  50. #include <sys/shm.h>
  51. #include <X11/extensions/XShm.h>
  52. /**
  53. * X11 Device Demuxer context
  54. */
  55. struct x11_grab
  56. {
  57. int frame_size; /**< Size in bytes of a grabbed frame */
  58. AVRational time_base; /**< Time base */
  59. int64_t time_frame; /**< Current time */
  60. int height; /**< Height of the grab frame */
  61. int width; /**< Width of the grab frame */
  62. int x_off; /**< Horizontal top-left corner coordinate */
  63. int y_off; /**< Vertical top-left corner coordinate */
  64. Display *dpy; /**< X11 display from which x11grab grabs frames */
  65. XImage *image; /**< X11 image holding the grab */
  66. int use_shm; /**< !0 when using XShm extension */
  67. XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
  68. int mouse_warning_shown;
  69. };
  70. /**
  71. * Initializes the x11 grab device demuxer (public device demuxer API).
  72. *
  73. * @param s1 Context from avformat core
  74. * @param ap Parameters from avformat core
  75. * @return <ul>
  76. * <li>AVERROR(ENOMEM) no memory left</li>
  77. * <li>AVERROR(EIO) other failure case</li>
  78. * <li>0 success</li>
  79. * </ul>
  80. */
  81. static int
  82. x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
  83. {
  84. struct x11_grab *x11grab = s1->priv_data;
  85. Display *dpy;
  86. AVStream *st = NULL;
  87. int input_pixfmt;
  88. XImage *image;
  89. int x_off = 0;
  90. int y_off = 0;
  91. int use_shm;
  92. char *param, *offset;
  93. param = av_strdup(s1->filename);
  94. offset = strchr(param, '+');
  95. if (offset) {
  96. sscanf(offset, "%d,%d", &x_off, &y_off);
  97. *offset= 0;
  98. }
  99. av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n", s1->filename, param, x_off, y_off, ap->width, ap->height);
  100. dpy = XOpenDisplay(param);
  101. if(!dpy) {
  102. av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
  103. return AVERROR(EIO);
  104. }
  105. if (!ap || ap->width <= 0 || ap->height <= 0 || ap->time_base.den <= 0) {
  106. av_log(s1, AV_LOG_ERROR, "AVParameters don't have video size and/or rate. Use -s and -r.\n");
  107. return AVERROR(EIO);
  108. }
  109. st = av_new_stream(s1, 0);
  110. if (!st) {
  111. return AVERROR(ENOMEM);
  112. }
  113. av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  114. use_shm = XShmQueryExtension(dpy);
  115. av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not");
  116. if(use_shm) {
  117. int scr = XDefaultScreen(dpy);
  118. image = XShmCreateImage(dpy,
  119. DefaultVisual(dpy, scr),
  120. DefaultDepth(dpy, scr),
  121. ZPixmap,
  122. NULL,
  123. &x11grab->shminfo,
  124. ap->width, ap->height);
  125. x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
  126. image->bytes_per_line * image->height,
  127. IPC_CREAT|0777);
  128. if (x11grab->shminfo.shmid == -1) {
  129. av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
  130. return AVERROR(ENOMEM);
  131. }
  132. x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
  133. x11grab->shminfo.readOnly = False;
  134. if (!XShmAttach(dpy, &x11grab->shminfo)) {
  135. av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
  136. /* needs some better error subroutine :) */
  137. return AVERROR(EIO);
  138. }
  139. } else {
  140. image = XGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)),
  141. x_off,y_off,
  142. ap->width,ap->height,
  143. AllPlanes, ZPixmap);
  144. }
  145. switch (image->bits_per_pixel) {
  146. case 8:
  147. av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
  148. input_pixfmt = PIX_FMT_PAL8;
  149. break;
  150. case 16:
  151. if ( image->red_mask == 0xf800 &&
  152. image->green_mask == 0x07e0 &&
  153. image->blue_mask == 0x001f ) {
  154. av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
  155. input_pixfmt = PIX_FMT_RGB565;
  156. } else if (image->red_mask == 0x7c00 &&
  157. image->green_mask == 0x03e0 &&
  158. image->blue_mask == 0x001f ) {
  159. av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
  160. input_pixfmt = PIX_FMT_RGB555;
  161. } else {
  162. av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
  163. 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);
  164. return AVERROR(EIO);
  165. }
  166. break;
  167. case 24:
  168. if ( image->red_mask == 0xff0000 &&
  169. image->green_mask == 0x00ff00 &&
  170. image->blue_mask == 0x0000ff ) {
  171. input_pixfmt = PIX_FMT_BGR24;
  172. } else if ( image->red_mask == 0x0000ff &&
  173. image->green_mask == 0x00ff00 &&
  174. image->blue_mask == 0xff0000 ) {
  175. input_pixfmt = PIX_FMT_RGB24;
  176. } else {
  177. av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
  178. 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);
  179. return AVERROR(EIO);
  180. }
  181. break;
  182. case 32:
  183. #if 0
  184. GetColorInfo (image, &c_info);
  185. if ( c_info.alpha_mask == 0xff000000 && image->green_mask == 0x0000ff00) {
  186. /* byte order is relevant here, not endianness
  187. * endianness is handled by avcodec, but atm no such thing
  188. * as having ABGR, instead of ARGB in a word. Since we
  189. * need this for Solaris/SPARC, but need to do the conversion
  190. * for every frame we do it outside of this loop, cf. below
  191. * this matches both ARGB32 and ABGR32 */
  192. input_pixfmt = PIX_FMT_ARGB32;
  193. } else {
  194. av_log(s1, AV_LOG_ERROR,"image depth %i not supported ... aborting\n", image->bits_per_pixel);
  195. return AVERROR(EIO);
  196. }
  197. #endif
  198. input_pixfmt = PIX_FMT_RGB32;
  199. break;
  200. default:
  201. av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
  202. return -1;
  203. }
  204. x11grab->frame_size = ap->width * ap->height * image->bits_per_pixel/8;
  205. x11grab->dpy = dpy;
  206. x11grab->width = ap->width;
  207. x11grab->height = ap->height;
  208. x11grab->time_base = ap->time_base;
  209. x11grab->time_frame = av_gettime() / av_q2d(ap->time_base);
  210. x11grab->x_off = x_off;
  211. x11grab->y_off = y_off;
  212. x11grab->image = image;
  213. x11grab->use_shm = use_shm;
  214. x11grab->mouse_warning_shown = 0;
  215. st->codec->codec_type = CODEC_TYPE_VIDEO;
  216. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  217. st->codec->width = ap->width;
  218. st->codec->height = ap->height;
  219. st->codec->pix_fmt = input_pixfmt;
  220. st->codec->time_base = ap->time_base;
  221. st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(ap->time_base) * 8;
  222. return 0;
  223. }
  224. /**
  225. * Get pointer coordinates from X11.
  226. *
  227. * @param x Integer where horizontal coordinate will be returned
  228. * @param y Integer where vertical coordinate will be returned
  229. * @param dpy X11 display from where pointer coordinates are retrieved
  230. * @param s1 Context used for logging errors if necessary
  231. */
  232. static void
  233. get_pointer_coordinates(int *x, int *y, Display *dpy, AVFormatContext *s1)
  234. {
  235. Window mrootwindow, childwindow;
  236. int dummy;
  237. mrootwindow = DefaultRootWindow(dpy);
  238. if (XQueryPointer(dpy, mrootwindow, &mrootwindow, &childwindow,
  239. x, y, &dummy, &dummy, (unsigned int*)&dummy)) {
  240. } else {
  241. struct x11_grab *s = s1->priv_data;
  242. if (!s->mouse_warning_shown) {
  243. av_log(s1, AV_LOG_INFO, "couldn't find mouse pointer\n");
  244. s->mouse_warning_shown = 1;
  245. }
  246. *x = -1;
  247. *y = -1;
  248. }
  249. }
  250. /**
  251. * Mouse painting helper function that applies an 'and' and 'or' mask pair to
  252. * '*dst' pixel. It actually draws a mouse pointer pixel to grabbed frame.
  253. *
  254. * @param dst Destination pixel
  255. * @param and Part of the mask that must be applied using a bitwise 'and'
  256. * operator
  257. * @param or Part of the mask that must be applied using a bitwise 'or'
  258. * operator
  259. * @param bits_per_pixel Bits per pixel used in the grabbed image
  260. */
  261. static void inline
  262. apply_masks(uint8_t *dst, int and, int or, int bits_per_pixel)
  263. {
  264. switch (bits_per_pixel) {
  265. case 32:
  266. *(uint32_t*)dst = (*(uint32_t*)dst & and) | or;
  267. break;
  268. case 16:
  269. *(uint16_t*)dst = (*(uint16_t*)dst & and) | or;
  270. break;
  271. case 8:
  272. *dst = !!or;
  273. break;
  274. }
  275. }
  276. /**
  277. * Paints a mouse pointer in an X11 image.
  278. *
  279. * @param image image to paint the mouse pointer to
  280. * @param s context used to retrieve original grabbing rectangle
  281. * coordinates
  282. * @param x Mouse pointer coordinate
  283. * @param y Mouse pointer coordinate
  284. */
  285. static void
  286. paint_mouse_pointer(XImage *image, struct x11_grab *s, int x, int y)
  287. {
  288. /* 16x20x1bpp bitmap for the black channel of the mouse pointer */
  289. static const uint16_t const mousePointerBlack[] =
  290. {
  291. 0x0000, 0x0003, 0x0005, 0x0009, 0x0011,
  292. 0x0021, 0x0041, 0x0081, 0x0101, 0x0201,
  293. 0x03c1, 0x0049, 0x0095, 0x0093, 0x0120,
  294. 0x0120, 0x0240, 0x0240, 0x0380, 0x0000
  295. };
  296. /* 16x20x1bpp bitmap for the white channel of the mouse pointer */
  297. static const uint16_t const mousePointerWhite[] =
  298. {
  299. 0x0000, 0x0000, 0x0002, 0x0006, 0x000e,
  300. 0x001e, 0x003e, 0x007e, 0x00fe, 0x01fe,
  301. 0x003e, 0x0036, 0x0062, 0x0060, 0x00c0,
  302. 0x00c0, 0x0180, 0x0180, 0x0000, 0x0000
  303. };
  304. int x_off = s->x_off;
  305. int y_off = s->y_off;
  306. int width = s->width;
  307. int height = s->height;
  308. if ( x - x_off >= 0 && x < width + x_off
  309. && y - y_off >= 0 && y < height + y_off) {
  310. uint8_t *im_data = (uint8_t*)image->data;
  311. int bytes_per_pixel;
  312. int line;
  313. int masks;
  314. /* Select correct masks and pixel size */
  315. if (image->bits_per_pixel == 8) {
  316. masks = 1;
  317. } else {
  318. masks = (image->red_mask|image->green_mask|image->blue_mask);
  319. }
  320. bytes_per_pixel = image->bits_per_pixel>>3;
  321. /* Shift to right line */
  322. im_data += image->bytes_per_line * (y - y_off);
  323. /* Shift to right pixel in the line */
  324. im_data += bytes_per_pixel * (x - x_off);
  325. /* Draw the cursor - proper loop */
  326. for (line = 0; line < FFMIN(20, (y_off + height) - y); line++) {
  327. uint8_t *cursor = im_data;
  328. int column;
  329. uint16_t bm_b;
  330. uint16_t bm_w;
  331. bm_b = mousePointerBlack[line];
  332. bm_w = mousePointerWhite[line];
  333. for (column = 0; column < FFMIN(16, (x_off + width) - x); column++) {
  334. apply_masks(cursor, ~(masks*(bm_b&1)), masks*(bm_w&1),
  335. image->bits_per_pixel);
  336. cursor += bytes_per_pixel;
  337. bm_b >>= 1;
  338. bm_w >>= 1;
  339. }
  340. im_data += image->bytes_per_line;
  341. }
  342. }
  343. }
  344. /**
  345. * Reads new data in the image structure.
  346. *
  347. * @param dpy X11 display to grab from
  348. * @param d
  349. * @param image Image where the grab will be put
  350. * @param x Top-Left grabbing rectangle horizontal coordinate
  351. * @param y Top-Left grabbing rectangle vertical coordinate
  352. * @return 0 if error, !0 if successful
  353. */
  354. static int
  355. xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
  356. {
  357. xGetImageReply rep;
  358. xGetImageReq *req;
  359. long nbytes;
  360. if (!image) {
  361. return 0;
  362. }
  363. LockDisplay(dpy);
  364. GetReq(GetImage, req);
  365. /* First set up the standard stuff in the request */
  366. req->drawable = d;
  367. req->x = x;
  368. req->y = y;
  369. req->width = image->width;
  370. req->height = image->height;
  371. req->planeMask = (unsigned int)AllPlanes;
  372. req->format = ZPixmap;
  373. if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
  374. UnlockDisplay(dpy);
  375. SyncHandle();
  376. return 0;
  377. }
  378. nbytes = (long)rep.length << 2;
  379. _XReadPad(dpy, image->data, nbytes);
  380. UnlockDisplay(dpy);
  381. SyncHandle();
  382. return 1;
  383. }
  384. /**
  385. * Grabs a frame from x11 (public device demuxer API).
  386. *
  387. * @param s1 Context from avformat core
  388. * @param pkt Packet holding the brabbed frame
  389. * @return frame size in bytes
  390. */
  391. static int
  392. x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
  393. {
  394. struct x11_grab *s = s1->priv_data;
  395. Display *dpy = s->dpy;
  396. XImage *image = s->image;
  397. int x_off = s->x_off;
  398. int y_off = s->y_off;
  399. int64_t curtime, delay;
  400. struct timespec ts;
  401. /* Calculate the time of the next frame */
  402. s->time_frame += INT64_C(1000000);
  403. /* wait based on the frame rate */
  404. for(;;) {
  405. curtime = av_gettime();
  406. delay = s->time_frame * av_q2d(s->time_base) - curtime;
  407. if (delay <= 0) {
  408. if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
  409. s->time_frame += INT64_C(1000000);
  410. }
  411. break;
  412. }
  413. ts.tv_sec = delay / 1000000;
  414. ts.tv_nsec = (delay % 1000000) * 1000;
  415. nanosleep(&ts, NULL);
  416. }
  417. if (av_new_packet(pkt, s->frame_size) < 0) {
  418. return AVERROR(EIO);
  419. }
  420. pkt->pts = curtime;
  421. if(s->use_shm) {
  422. if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
  423. av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
  424. }
  425. } else {
  426. if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
  427. av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
  428. }
  429. }
  430. {
  431. int pointer_x, pointer_y;
  432. get_pointer_coordinates(&pointer_x, &pointer_y, dpy, s1);
  433. paint_mouse_pointer(image, s, pointer_x, pointer_y);
  434. }
  435. /* XXX: avoid memcpy */
  436. memcpy(pkt->data, image->data, s->frame_size);
  437. return s->frame_size;
  438. }
  439. /**
  440. * Closes x11 frame grabber (public device demuxer API).
  441. *
  442. * @param s1 Context from avformat core
  443. * @return 0 success, !0 failure
  444. */
  445. static int
  446. x11grab_read_close(AVFormatContext *s1)
  447. {
  448. struct x11_grab *x11grab = s1->priv_data;
  449. /* Detach cleanly from shared mem */
  450. if (x11grab->use_shm) {
  451. XShmDetach(x11grab->dpy, &x11grab->shminfo);
  452. shmdt(x11grab->shminfo.shmaddr);
  453. shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
  454. }
  455. /* Destroy X11 image */
  456. if (x11grab->image) {
  457. XDestroyImage(x11grab->image);
  458. x11grab->image = NULL;
  459. }
  460. /* Free X11 display */
  461. XCloseDisplay(x11grab->dpy);
  462. return 0;
  463. }
  464. /** x11 grabber device demuxer declaration */
  465. AVInputFormat x11_grab_device_demuxer =
  466. {
  467. "x11grab",
  468. NULL_IF_CONFIG_SMALL("X11grab"),
  469. sizeof(struct x11_grab),
  470. NULL,
  471. x11grab_read_header,
  472. x11grab_read_packet,
  473. x11grab_read_close,
  474. .flags = AVFMT_NOFILE,
  475. };