You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

478 lines
15KB

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