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.

479 lines
15KB

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