x11grab.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 nomouse;
  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->nomouse= 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. #if 0
  208. GetColorInfo (image, &c_info);
  209. if ( c_info.alpha_mask == 0xff000000 && image->green_mask == 0x0000ff00) {
  210. /* byte order is relevant here, not endianness
  211. * endianness is handled by avcodec, but atm no such thing
  212. * as having ABGR, instead of ARGB in a word. Since we
  213. * need this for Solaris/SPARC, but need to do the conversion
  214. * for every frame we do it outside of this loop, cf. below
  215. * this matches both ARGB32 and ABGR32 */
  216. input_pixfmt = PIX_FMT_ARGB32;
  217. } else {
  218. av_log(s1, AV_LOG_ERROR,"image depth %i not supported ... aborting\n", image->bits_per_pixel);
  219. return AVERROR(EIO);
  220. }
  221. #endif
  222. input_pixfmt = PIX_FMT_RGB32;
  223. break;
  224. default:
  225. av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
  226. ret = AVERROR(EINVAL);
  227. goto out;
  228. }
  229. x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
  230. x11grab->dpy = dpy;
  231. x11grab->time_base = (AVRational){framerate.den, framerate.num};
  232. x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
  233. x11grab->x_off = x_off;
  234. x11grab->y_off = y_off;
  235. x11grab->image = image;
  236. x11grab->use_shm = use_shm;
  237. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  238. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  239. st->codec->width = x11grab->width;
  240. st->codec->height = x11grab->height;
  241. st->codec->pix_fmt = input_pixfmt;
  242. st->codec->time_base = x11grab->time_base;
  243. st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;
  244. out:
  245. return ret;
  246. }
  247. /**
  248. * Paint a mouse pointer in an X11 image.
  249. *
  250. * @param image image to paint the mouse pointer to
  251. * @param s context used to retrieve original grabbing rectangle
  252. * coordinates
  253. */
  254. static void
  255. paint_mouse_pointer(XImage *image, struct x11_grab *s)
  256. {
  257. int x_off = s->x_off;
  258. int y_off = s->y_off;
  259. int width = s->width;
  260. int height = s->height;
  261. Display *dpy = s->dpy;
  262. XFixesCursorImage *xcim;
  263. int x, y;
  264. int line, column;
  265. int to_line, to_column;
  266. int pixstride = image->bits_per_pixel >> 3;
  267. /* Warning: in its insanity, xlib provides unsigned image data through a
  268. * char* pointer, so we have to make it uint8_t to make things not break.
  269. * Anyone who performs further investigation of the xlib API likely risks
  270. * permanent brain damage. */
  271. uint8_t *pix = image->data;
  272. /* Code doesn't currently support 16-bit or PAL8 */
  273. if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
  274. return;
  275. xcim = XFixesGetCursorImage(dpy);
  276. x = xcim->x - xcim->xhot;
  277. y = xcim->y - xcim->yhot;
  278. to_line = FFMIN((y + xcim->height), (height + y_off));
  279. to_column = FFMIN((x + xcim->width), (width + x_off));
  280. for (line = FFMAX(y, y_off); line < to_line; line++) {
  281. for (column = FFMAX(x, x_off); column < to_column; column++) {
  282. int xcim_addr = (line - y) * xcim->width + column - x;
  283. int image_addr = ((line - y_off) * width + column - x_off) * pixstride;
  284. int r = (uint8_t)(xcim->pixels[xcim_addr] >> 0);
  285. int g = (uint8_t)(xcim->pixels[xcim_addr] >> 8);
  286. int b = (uint8_t)(xcim->pixels[xcim_addr] >> 16);
  287. int a = (uint8_t)(xcim->pixels[xcim_addr] >> 24);
  288. if (a == 255) {
  289. pix[image_addr+0] = r;
  290. pix[image_addr+1] = g;
  291. pix[image_addr+2] = b;
  292. } else if (a) {
  293. /* pixel values from XFixesGetCursorImage come premultiplied by alpha */
  294. pix[image_addr+0] = r + (pix[image_addr+0]*(255-a) + 255/2) / 255;
  295. pix[image_addr+1] = g + (pix[image_addr+1]*(255-a) + 255/2) / 255;
  296. pix[image_addr+2] = b + (pix[image_addr+2]*(255-a) + 255/2) / 255;
  297. }
  298. }
  299. }
  300. XFree(xcim);
  301. xcim = NULL;
  302. }
  303. /**
  304. * Read new data in the image structure.
  305. *
  306. * @param dpy X11 display to grab from
  307. * @param d
  308. * @param image Image where the grab will be put
  309. * @param x Top-Left grabbing rectangle horizontal coordinate
  310. * @param y Top-Left grabbing rectangle vertical coordinate
  311. * @return 0 if error, !0 if successful
  312. */
  313. static int
  314. xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
  315. {
  316. xGetImageReply rep;
  317. xGetImageReq *req;
  318. long nbytes;
  319. if (!image) {
  320. return 0;
  321. }
  322. LockDisplay(dpy);
  323. GetReq(GetImage, req);
  324. /* First set up the standard stuff in the request */
  325. req->drawable = d;
  326. req->x = x;
  327. req->y = y;
  328. req->width = image->width;
  329. req->height = image->height;
  330. req->planeMask = (unsigned int)AllPlanes;
  331. req->format = ZPixmap;
  332. if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
  333. UnlockDisplay(dpy);
  334. SyncHandle();
  335. return 0;
  336. }
  337. nbytes = (long)rep.length << 2;
  338. _XReadPad(dpy, image->data, nbytes);
  339. UnlockDisplay(dpy);
  340. SyncHandle();
  341. return 1;
  342. }
  343. /**
  344. * Grab a frame from x11 (public device demuxer API).
  345. *
  346. * @param s1 Context from avformat core
  347. * @param pkt Packet holding the brabbed frame
  348. * @return frame size in bytes
  349. */
  350. static int
  351. x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
  352. {
  353. struct x11_grab *s = s1->priv_data;
  354. Display *dpy = s->dpy;
  355. XImage *image = s->image;
  356. int x_off = s->x_off;
  357. int y_off = s->y_off;
  358. int64_t curtime, delay;
  359. struct timespec ts;
  360. /* Calculate the time of the next frame */
  361. s->time_frame += INT64_C(1000000);
  362. /* wait based on the frame rate */
  363. for(;;) {
  364. curtime = av_gettime();
  365. delay = s->time_frame * av_q2d(s->time_base) - curtime;
  366. if (delay <= 0) {
  367. if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
  368. s->time_frame += INT64_C(1000000);
  369. }
  370. break;
  371. }
  372. ts.tv_sec = delay / 1000000;
  373. ts.tv_nsec = (delay % 1000000) * 1000;
  374. nanosleep(&ts, NULL);
  375. }
  376. av_init_packet(pkt);
  377. pkt->data = image->data;
  378. pkt->size = s->frame_size;
  379. pkt->pts = curtime;
  380. if(s->use_shm) {
  381. if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
  382. av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
  383. }
  384. } else {
  385. if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
  386. av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
  387. }
  388. }
  389. if(!s->nomouse){
  390. paint_mouse_pointer(image, s);
  391. }
  392. return s->frame_size;
  393. }
  394. /**
  395. * Close x11 frame grabber (public device demuxer API).
  396. *
  397. * @param s1 Context from avformat core
  398. * @return 0 success, !0 failure
  399. */
  400. static int
  401. x11grab_read_close(AVFormatContext *s1)
  402. {
  403. struct x11_grab *x11grab = s1->priv_data;
  404. /* Detach cleanly from shared mem */
  405. if (x11grab->use_shm) {
  406. XShmDetach(x11grab->dpy, &x11grab->shminfo);
  407. shmdt(x11grab->shminfo.shmaddr);
  408. shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
  409. }
  410. /* Destroy X11 image */
  411. if (x11grab->image) {
  412. XDestroyImage(x11grab->image);
  413. x11grab->image = NULL;
  414. }
  415. /* Free X11 display */
  416. XCloseDisplay(x11grab->dpy);
  417. return 0;
  418. }
  419. #define OFFSET(x) offsetof(struct x11_grab, x)
  420. #define DEC AV_OPT_FLAG_DECODING_PARAM
  421. static const AVOption options[] = {
  422. { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = "vga"}, 0, 0, DEC },
  423. { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
  424. { NULL },
  425. };
  426. static const AVClass x11_class = {
  427. .class_name = "X11grab indev",
  428. .item_name = av_default_item_name,
  429. .option = options,
  430. .version = LIBAVUTIL_VERSION_INT,
  431. };
  432. /** x11 grabber device demuxer declaration */
  433. AVInputFormat ff_x11_grab_device_demuxer =
  434. {
  435. "x11grab",
  436. NULL_IF_CONFIG_SMALL("X11grab"),
  437. sizeof(struct x11_grab),
  438. NULL,
  439. x11grab_read_header,
  440. x11grab_read_packet,
  441. x11grab_read_close,
  442. .flags = AVFMT_NOFILE,
  443. .priv_class = &x11_class,
  444. };