x11grab.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. * @file
  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 "libavutil/log.h"
  39. #include "libavutil/opt.h"
  40. #include "libavutil/parseutils.h"
  41. #include <time.h>
  42. #include <X11/X.h>
  43. #include <X11/Xlib.h>
  44. #include <X11/Xlibint.h>
  45. #include <X11/Xproto.h>
  46. #include <X11/Xutil.h>
  47. #include <sys/shm.h>
  48. #include <X11/extensions/XShm.h>
  49. #include <X11/extensions/Xfixes.h>
  50. /**
  51. * X11 Device Demuxer context
  52. */
  53. struct x11_grab
  54. {
  55. const AVClass *class; /**< Class for private options. */
  56. int frame_size; /**< Size in bytes of a grabbed frame */
  57. AVRational time_base; /**< Time base */
  58. int64_t time_frame; /**< Current time */
  59. char *video_size; /**< String describing video size, set by a private option. */
  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 nomouse;
  69. };
  70. /**
  71. * Initialize 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. enum PixelFormat input_pixfmt;
  88. XImage *image;
  89. int x_off = 0;
  90. int y_off = 0;
  91. int use_shm;
  92. char *param, *offset;
  93. int ret = 0;
  94. param = av_strdup(s1->filename);
  95. offset = strchr(param, '+');
  96. if (offset) {
  97. sscanf(offset, "%d,%d", &x_off, &y_off);
  98. x11grab->nomouse= strstr(offset, "nomouse");
  99. *offset= 0;
  100. }
  101. if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) {
  102. av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
  103. goto out;
  104. }
  105. #if FF_API_FORMAT_PARAMETERS
  106. if (ap->width > 0)
  107. x11grab->width = ap->width;
  108. if (ap->height > 0)
  109. x11grab->height = ap->height;
  110. #endif
  111. av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
  112. s1->filename, param, x_off, y_off, x11grab->width, x11grab->height);
  113. dpy = XOpenDisplay(param);
  114. if(!dpy) {
  115. av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
  116. ret = AVERROR(EIO);
  117. goto out;
  118. }
  119. if (ap->time_base.den <= 0) {
  120. av_log(s1, AV_LOG_ERROR, "AVParameters don't have video size and/or rate. Use -s and -r.\n");
  121. ret = AVERROR(EINVAL);
  122. goto out;
  123. }
  124. st = av_new_stream(s1, 0);
  125. if (!st) {
  126. ret = AVERROR(ENOMEM);
  127. goto out;
  128. }
  129. av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  130. use_shm = XShmQueryExtension(dpy);
  131. av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not");
  132. if(use_shm) {
  133. int scr = XDefaultScreen(dpy);
  134. image = XShmCreateImage(dpy,
  135. DefaultVisual(dpy, scr),
  136. DefaultDepth(dpy, scr),
  137. ZPixmap,
  138. NULL,
  139. &x11grab->shminfo,
  140. x11grab->width, x11grab->height);
  141. x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
  142. image->bytes_per_line * image->height,
  143. IPC_CREAT|0777);
  144. if (x11grab->shminfo.shmid == -1) {
  145. av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
  146. ret = AVERROR(ENOMEM);
  147. goto out;
  148. }
  149. x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
  150. x11grab->shminfo.readOnly = False;
  151. if (!XShmAttach(dpy, &x11grab->shminfo)) {
  152. av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
  153. /* needs some better error subroutine :) */
  154. ret = AVERROR(EIO);
  155. goto out;
  156. }
  157. } else {
  158. image = XGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)),
  159. x_off,y_off,
  160. x11grab->width, x11grab->height,
  161. AllPlanes, ZPixmap);
  162. }
  163. switch (image->bits_per_pixel) {
  164. case 8:
  165. av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
  166. input_pixfmt = PIX_FMT_PAL8;
  167. break;
  168. case 16:
  169. if ( image->red_mask == 0xf800 &&
  170. image->green_mask == 0x07e0 &&
  171. image->blue_mask == 0x001f ) {
  172. av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
  173. input_pixfmt = PIX_FMT_RGB565;
  174. } else if (image->red_mask == 0x7c00 &&
  175. image->green_mask == 0x03e0 &&
  176. image->blue_mask == 0x001f ) {
  177. av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
  178. input_pixfmt = PIX_FMT_RGB555;
  179. } else {
  180. av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
  181. 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);
  182. ret = AVERROR(EIO);
  183. goto out;
  184. }
  185. break;
  186. case 24:
  187. if ( image->red_mask == 0xff0000 &&
  188. image->green_mask == 0x00ff00 &&
  189. image->blue_mask == 0x0000ff ) {
  190. input_pixfmt = PIX_FMT_BGR24;
  191. } else if ( image->red_mask == 0x0000ff &&
  192. image->green_mask == 0x00ff00 &&
  193. image->blue_mask == 0xff0000 ) {
  194. input_pixfmt = PIX_FMT_RGB24;
  195. } else {
  196. av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
  197. 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);
  198. ret = AVERROR(EIO);
  199. goto out;
  200. }
  201. break;
  202. case 32:
  203. #if 0
  204. GetColorInfo (image, &c_info);
  205. if ( c_info.alpha_mask == 0xff000000 && image->green_mask == 0x0000ff00) {
  206. /* byte order is relevant here, not endianness
  207. * endianness is handled by avcodec, but atm no such thing
  208. * as having ABGR, instead of ARGB in a word. Since we
  209. * need this for Solaris/SPARC, but need to do the conversion
  210. * for every frame we do it outside of this loop, cf. below
  211. * this matches both ARGB32 and ABGR32 */
  212. input_pixfmt = PIX_FMT_ARGB32;
  213. } else {
  214. av_log(s1, AV_LOG_ERROR,"image depth %i not supported ... aborting\n", image->bits_per_pixel);
  215. return AVERROR(EIO);
  216. }
  217. #endif
  218. input_pixfmt = PIX_FMT_RGB32;
  219. break;
  220. default:
  221. av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
  222. ret = AVERROR(EINVAL);
  223. goto out;
  224. }
  225. x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
  226. x11grab->dpy = dpy;
  227. x11grab->time_base = ap->time_base;
  228. x11grab->time_frame = av_gettime() / av_q2d(ap->time_base);
  229. x11grab->x_off = x_off;
  230. x11grab->y_off = y_off;
  231. x11grab->image = image;
  232. x11grab->use_shm = use_shm;
  233. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  234. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  235. st->codec->width = x11grab->width;
  236. st->codec->height = x11grab->height;
  237. st->codec->pix_fmt = input_pixfmt;
  238. st->codec->time_base = ap->time_base;
  239. st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(ap->time_base) * 8;
  240. out:
  241. av_freep(&x11grab->video_size);
  242. return ret;
  243. }
  244. /**
  245. * Paint a mouse pointer in an X11 image.
  246. *
  247. * @param image image to paint the mouse pointer to
  248. * @param s context used to retrieve original grabbing rectangle
  249. * coordinates
  250. */
  251. static void
  252. paint_mouse_pointer(XImage *image, struct x11_grab *s)
  253. {
  254. int x_off = s->x_off;
  255. int y_off = s->y_off;
  256. int width = s->width;
  257. int height = s->height;
  258. Display *dpy = s->dpy;
  259. XFixesCursorImage *xcim;
  260. int x, y;
  261. int line, column;
  262. int to_line, to_column;
  263. int pixstride = image->bits_per_pixel >> 3;
  264. /* Warning: in its insanity, xlib provides unsigned image data through a
  265. * char* pointer, so we have to make it uint8_t to make things not break.
  266. * Anyone who performs further investigation of the xlib API likely risks
  267. * permanent brain damage. */
  268. uint8_t *pix = image->data;
  269. /* Code doesn't currently support 16-bit or PAL8 */
  270. if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
  271. return;
  272. xcim = XFixesGetCursorImage(dpy);
  273. x = xcim->x - xcim->xhot;
  274. y = xcim->y - xcim->yhot;
  275. to_line = FFMIN((y + xcim->height), (height + y_off));
  276. to_column = FFMIN((x + xcim->width), (width + x_off));
  277. for (line = FFMAX(y, y_off); line < to_line; line++) {
  278. for (column = FFMAX(x, x_off); column < to_column; column++) {
  279. int xcim_addr = (line - y) * xcim->width + column - x;
  280. int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
  281. int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
  282. int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
  283. int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
  284. int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
  285. if (a == 255) {
  286. pix[image_addr+0] = r;
  287. pix[image_addr+1] = g;
  288. pix[image_addr+2] = b;
  289. } else if (a) {
  290. /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
  291. pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
  292. pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
  293. pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
  294. }
  295. }
  296. }
  297. XFree(xcim);
  298. xcim = NULL;
  299. }
  300. /**
  301. * Read new data in the image structure.
  302. *
  303. * @param dpy X11 display to grab from
  304. * @param d
  305. * @param image Image where the grab will be put
  306. * @param x Top-Left grabbing rectangle horizontal coordinate
  307. * @param y Top-Left grabbing rectangle vertical coordinate
  308. * @return 0 if error, !0 if successful
  309. */
  310. static int
  311. xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
  312. {
  313. xGetImageReply rep;
  314. xGetImageReq *req;
  315. long nbytes;
  316. if (!image) {
  317. return 0;
  318. }
  319. LockDisplay(dpy);
  320. GetReq(GetImage, req);
  321. /* First set up the standard stuff in the request */
  322. req->drawable = d;
  323. req->x = x;
  324. req->y = y;
  325. req->width = image->width;
  326. req->height = image->height;
  327. req->planeMask = (unsigned int)AllPlanes;
  328. req->format = ZPixmap;
  329. if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
  330. UnlockDisplay(dpy);
  331. SyncHandle();
  332. return 0;
  333. }
  334. nbytes = (long)rep.length << 2;
  335. _XReadPad(dpy, image->data, nbytes);
  336. UnlockDisplay(dpy);
  337. SyncHandle();
  338. return 1;
  339. }
  340. /**
  341. * Grab a frame from x11 (public device demuxer API).
  342. *
  343. * @param s1 Context from avformat core
  344. * @param pkt Packet holding the brabbed frame
  345. * @return frame size in bytes
  346. */
  347. static int
  348. x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
  349. {
  350. struct x11_grab *s = s1->priv_data;
  351. Display *dpy = s->dpy;
  352. XImage *image = s->image;
  353. int x_off = s->x_off;
  354. int y_off = s->y_off;
  355. int64_t curtime, delay;
  356. struct timespec ts;
  357. /* Calculate the time of the next frame */
  358. s->time_frame += INT64_C(1000000);
  359. /* wait based on the frame rate */
  360. for(;;) {
  361. curtime = av_gettime();
  362. delay = s->time_frame * av_q2d(s->time_base) - curtime;
  363. if (delay <= 0) {
  364. if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
  365. s->time_frame += INT64_C(1000000);
  366. }
  367. break;
  368. }
  369. ts.tv_sec = delay / 1000000;
  370. ts.tv_nsec = (delay % 1000000) * 1000;
  371. nanosleep(&ts, NULL);
  372. }
  373. if (av_new_packet(pkt, s->frame_size) < 0) {
  374. return AVERROR(EIO);
  375. }
  376. pkt->pts = curtime;
  377. if(s->use_shm) {
  378. if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
  379. av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
  380. }
  381. } else {
  382. if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
  383. av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
  384. }
  385. }
  386. if(!s->nomouse){
  387. paint_mouse_pointer(image, s);
  388. }
  389. /* XXX: avoid memcpy */
  390. memcpy(pkt->data, image->data, s->frame_size);
  391. return s->frame_size;
  392. }
  393. /**
  394. * Close x11 frame grabber (public device demuxer API).
  395. *
  396. * @param s1 Context from avformat core
  397. * @return 0 success, !0 failure
  398. */
  399. static int
  400. x11grab_read_close(AVFormatContext *s1)
  401. {
  402. struct x11_grab *x11grab = s1->priv_data;
  403. /* Detach cleanly from shared mem */
  404. if (x11grab->use_shm) {
  405. XShmDetach(x11grab->dpy, &x11grab->shminfo);
  406. shmdt(x11grab->shminfo.shmaddr);
  407. shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
  408. }
  409. /* Destroy X11 image */
  410. if (x11grab->image) {
  411. XDestroyImage(x11grab->image);
  412. x11grab->image = NULL;
  413. }
  414. /* Free X11 display */
  415. XCloseDisplay(x11grab->dpy);
  416. return 0;
  417. }
  418. #define OFFSET(x) offsetof(struct x11_grab, x)
  419. #define DEC AV_OPT_FLAG_DECODING_PARAM
  420. static const AVOption options[] = {
  421. { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = "vga"}, 0, 0, DEC },
  422. { NULL },
  423. };
  424. static const AVClass x11_class = {
  425. .class_name = "X11grab indev",
  426. .item_name = av_default_item_name,
  427. .option = options,
  428. .version = LIBAVUTIL_VERSION_INT,
  429. };
  430. /** x11 grabber device demuxer declaration */
  431. AVInputFormat ff_x11_grab_device_demuxer =
  432. {
  433. "x11grab",
  434. NULL_IF_CONFIG_SMALL("X11grab"),
  435. sizeof(struct x11_grab),
  436. NULL,
  437. x11grab_read_header,
  438. x11grab_read_packet,
  439. x11grab_read_close,
  440. .flags = AVFMT_NOFILE,
  441. .priv_class = &x11_class,
  442. };