x11grab.c 16 KB

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