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.

524 lines
16KB

  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 libavdevice/x11grab.c
  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 <time.h>
  39. #include <X11/X.h>
  40. #include <X11/Xlib.h>
  41. #include <X11/Xlibint.h>
  42. #include <X11/Xproto.h>
  43. #include <X11/Xutil.h>
  44. #include <sys/shm.h>
  45. #include <X11/extensions/XShm.h>
  46. /**
  47. * X11 Device Demuxer context
  48. */
  49. struct x11_grab
  50. {
  51. int frame_size; /**< Size in bytes of a grabbed frame */
  52. AVRational time_base; /**< Time base */
  53. int64_t time_frame; /**< Current time */
  54. int height; /**< Height of the grab frame */
  55. int width; /**< Width of the grab frame */
  56. int x_off; /**< Horizontal top-left corner coordinate */
  57. int y_off; /**< Vertical top-left corner coordinate */
  58. Display *dpy; /**< X11 display from which x11grab grabs frames */
  59. XImage *image; /**< X11 image holding the grab */
  60. int use_shm; /**< !0 when using XShm extension */
  61. XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
  62. int mouse_warning_shown;
  63. };
  64. /**
  65. * Initializes the x11 grab device demuxer (public device demuxer API).
  66. *
  67. * @param s1 Context from avformat core
  68. * @param ap Parameters from avformat core
  69. * @return <ul>
  70. * <li>AVERROR(ENOMEM) no memory left</li>
  71. * <li>AVERROR(EIO) other failure case</li>
  72. * <li>0 success</li>
  73. * </ul>
  74. */
  75. static int
  76. x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
  77. {
  78. struct x11_grab *x11grab = s1->priv_data;
  79. Display *dpy;
  80. AVStream *st = NULL;
  81. int input_pixfmt;
  82. XImage *image;
  83. int x_off = 0;
  84. int y_off = 0;
  85. int use_shm;
  86. char *param, *offset;
  87. param = av_strdup(s1->filename);
  88. offset = strchr(param, '+');
  89. if (offset) {
  90. sscanf(offset, "%d,%d", &x_off, &y_off);
  91. *offset= 0;
  92. }
  93. av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n", s1->filename, param, x_off, y_off, ap->width, ap->height);
  94. dpy = XOpenDisplay(param);
  95. if(!dpy) {
  96. av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
  97. return AVERROR(EIO);
  98. }
  99. if (!ap || ap->width <= 0 || ap->height <= 0 || ap->time_base.den <= 0) {
  100. av_log(s1, AV_LOG_ERROR, "AVParameters don't have video size and/or rate. Use -s and -r.\n");
  101. return AVERROR(EIO);
  102. }
  103. st = av_new_stream(s1, 0);
  104. if (!st) {
  105. return AVERROR(ENOMEM);
  106. }
  107. av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  108. use_shm = XShmQueryExtension(dpy);
  109. av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not");
  110. if(use_shm) {
  111. int scr = XDefaultScreen(dpy);
  112. image = XShmCreateImage(dpy,
  113. DefaultVisual(dpy, scr),
  114. DefaultDepth(dpy, scr),
  115. ZPixmap,
  116. NULL,
  117. &x11grab->shminfo,
  118. ap->width, ap->height);
  119. x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
  120. image->bytes_per_line * image->height,
  121. IPC_CREAT|0777);
  122. if (x11grab->shminfo.shmid == -1) {
  123. av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
  124. return AVERROR(ENOMEM);
  125. }
  126. x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
  127. x11grab->shminfo.readOnly = False;
  128. if (!XShmAttach(dpy, &x11grab->shminfo)) {
  129. av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
  130. /* needs some better error subroutine :) */
  131. return AVERROR(EIO);
  132. }
  133. } else {
  134. image = XGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)),
  135. x_off,y_off,
  136. ap->width,ap->height,
  137. AllPlanes, ZPixmap);
  138. }
  139. switch (image->bits_per_pixel) {
  140. case 8:
  141. av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
  142. input_pixfmt = PIX_FMT_PAL8;
  143. break;
  144. case 16:
  145. if ( image->red_mask == 0xf800 &&
  146. image->green_mask == 0x07e0 &&
  147. image->blue_mask == 0x001f ) {
  148. av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
  149. input_pixfmt = PIX_FMT_RGB565;
  150. } else if (image->red_mask == 0x7c00 &&
  151. image->green_mask == 0x03e0 &&
  152. image->blue_mask == 0x001f ) {
  153. av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
  154. input_pixfmt = PIX_FMT_RGB555;
  155. } else {
  156. av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
  157. 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);
  158. return AVERROR(EIO);
  159. }
  160. break;
  161. case 24:
  162. if ( image->red_mask == 0xff0000 &&
  163. image->green_mask == 0x00ff00 &&
  164. image->blue_mask == 0x0000ff ) {
  165. input_pixfmt = PIX_FMT_BGR24;
  166. } else if ( image->red_mask == 0x0000ff &&
  167. image->green_mask == 0x00ff00 &&
  168. image->blue_mask == 0xff0000 ) {
  169. input_pixfmt = PIX_FMT_RGB24;
  170. } else {
  171. av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
  172. 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);
  173. return AVERROR(EIO);
  174. }
  175. break;
  176. case 32:
  177. #if 0
  178. GetColorInfo (image, &c_info);
  179. if ( c_info.alpha_mask == 0xff000000 && image->green_mask == 0x0000ff00) {
  180. /* byte order is relevant here, not endianness
  181. * endianness is handled by avcodec, but atm no such thing
  182. * as having ABGR, instead of ARGB in a word. Since we
  183. * need this for Solaris/SPARC, but need to do the conversion
  184. * for every frame we do it outside of this loop, cf. below
  185. * this matches both ARGB32 and ABGR32 */
  186. input_pixfmt = PIX_FMT_ARGB32;
  187. } else {
  188. av_log(s1, AV_LOG_ERROR,"image depth %i not supported ... aborting\n", image->bits_per_pixel);
  189. return AVERROR(EIO);
  190. }
  191. #endif
  192. input_pixfmt = PIX_FMT_RGB32;
  193. break;
  194. default:
  195. av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
  196. return -1;
  197. }
  198. x11grab->frame_size = ap->width * ap->height * image->bits_per_pixel/8;
  199. x11grab->dpy = dpy;
  200. x11grab->width = ap->width;
  201. x11grab->height = ap->height;
  202. x11grab->time_base = ap->time_base;
  203. x11grab->time_frame = av_gettime() / av_q2d(ap->time_base);
  204. x11grab->x_off = x_off;
  205. x11grab->y_off = y_off;
  206. x11grab->image = image;
  207. x11grab->use_shm = use_shm;
  208. x11grab->mouse_warning_shown = 0;
  209. st->codec->codec_type = CODEC_TYPE_VIDEO;
  210. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  211. st->codec->width = ap->width;
  212. st->codec->height = ap->height;
  213. st->codec->pix_fmt = input_pixfmt;
  214. st->codec->time_base = ap->time_base;
  215. st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(ap->time_base) * 8;
  216. return 0;
  217. }
  218. /**
  219. * Get pointer coordinates from X11.
  220. *
  221. * @param x Integer where horizontal coordinate will be returned
  222. * @param y Integer where vertical coordinate will be returned
  223. * @param dpy X11 display from where pointer coordinates are retrieved
  224. * @param s1 Context used for logging errors if necessary
  225. */
  226. static void
  227. get_pointer_coordinates(int *x, int *y, Display *dpy, AVFormatContext *s1)
  228. {
  229. Window mrootwindow, childwindow;
  230. int dummy;
  231. mrootwindow = DefaultRootWindow(dpy);
  232. if (XQueryPointer(dpy, mrootwindow, &mrootwindow, &childwindow,
  233. x, y, &dummy, &dummy, (unsigned int*)&dummy)) {
  234. } else {
  235. struct x11_grab *s = s1->priv_data;
  236. if (!s->mouse_warning_shown) {
  237. av_log(s1, AV_LOG_INFO, "couldn't find mouse pointer\n");
  238. s->mouse_warning_shown = 1;
  239. }
  240. *x = -1;
  241. *y = -1;
  242. }
  243. }
  244. /**
  245. * Mouse painting helper function that applies an 'and' and 'or' mask pair to
  246. * '*dst' pixel. It actually draws a mouse pointer pixel to grabbed frame.
  247. *
  248. * @param dst Destination pixel
  249. * @param and Part of the mask that must be applied using a bitwise 'and'
  250. * operator
  251. * @param or Part of the mask that must be applied using a bitwise 'or'
  252. * operator
  253. * @param bits_per_pixel Bits per pixel used in the grabbed image
  254. */
  255. static void inline
  256. apply_masks(uint8_t *dst, int and, int or, int bits_per_pixel)
  257. {
  258. switch (bits_per_pixel) {
  259. case 32:
  260. *(uint32_t*)dst = (*(uint32_t*)dst & and) | or;
  261. break;
  262. case 16:
  263. *(uint16_t*)dst = (*(uint16_t*)dst & and) | or;
  264. break;
  265. case 8:
  266. *dst = !!or;
  267. break;
  268. }
  269. }
  270. /**
  271. * Paints a mouse pointer in an X11 image.
  272. *
  273. * @param image image to paint the mouse pointer to
  274. * @param s context used to retrieve original grabbing rectangle
  275. * coordinates
  276. * @param x Mouse pointer coordinate
  277. * @param y Mouse pointer coordinate
  278. */
  279. static void
  280. paint_mouse_pointer(XImage *image, struct x11_grab *s, int x, int y)
  281. {
  282. /* 16x20x1bpp bitmap for the black channel of the mouse pointer */
  283. static const uint16_t const mousePointerBlack[] =
  284. {
  285. 0x0000, 0x0003, 0x0005, 0x0009, 0x0011,
  286. 0x0021, 0x0041, 0x0081, 0x0101, 0x0201,
  287. 0x03c1, 0x0049, 0x0095, 0x0093, 0x0120,
  288. 0x0120, 0x0240, 0x0240, 0x0380, 0x0000
  289. };
  290. /* 16x20x1bpp bitmap for the white channel of the mouse pointer */
  291. static const uint16_t const mousePointerWhite[] =
  292. {
  293. 0x0000, 0x0000, 0x0002, 0x0006, 0x000e,
  294. 0x001e, 0x003e, 0x007e, 0x00fe, 0x01fe,
  295. 0x003e, 0x0036, 0x0062, 0x0060, 0x00c0,
  296. 0x00c0, 0x0180, 0x0180, 0x0000, 0x0000
  297. };
  298. int x_off = s->x_off;
  299. int y_off = s->y_off;
  300. int width = s->width;
  301. int height = s->height;
  302. if ( x - x_off >= 0 && x < width + x_off
  303. && y - y_off >= 0 && y < height + y_off) {
  304. uint8_t *im_data = (uint8_t*)image->data;
  305. int bytes_per_pixel;
  306. int line;
  307. int masks;
  308. /* Select correct masks and pixel size */
  309. if (image->bits_per_pixel == 8) {
  310. masks = 1;
  311. } else {
  312. masks = (image->red_mask|image->green_mask|image->blue_mask);
  313. }
  314. bytes_per_pixel = image->bits_per_pixel>>3;
  315. /* Shift to right line */
  316. im_data += image->bytes_per_line * (y - y_off);
  317. /* Shift to right pixel in the line */
  318. im_data += bytes_per_pixel * (x - x_off);
  319. /* Draw the cursor - proper loop */
  320. for (line = 0; line < FFMIN(20, (y_off + height) - y); line++) {
  321. uint8_t *cursor = im_data;
  322. int column;
  323. uint16_t bm_b;
  324. uint16_t bm_w;
  325. bm_b = mousePointerBlack[line];
  326. bm_w = mousePointerWhite[line];
  327. for (column = 0; column < FFMIN(16, (x_off + width) - x); column++) {
  328. apply_masks(cursor, ~(masks*(bm_b&1)), masks*(bm_w&1),
  329. image->bits_per_pixel);
  330. cursor += bytes_per_pixel;
  331. bm_b >>= 1;
  332. bm_w >>= 1;
  333. }
  334. im_data += image->bytes_per_line;
  335. }
  336. }
  337. }
  338. /**
  339. * Reads new data in the image structure.
  340. *
  341. * @param dpy X11 display to grab from
  342. * @param d
  343. * @param image Image where the grab will be put
  344. * @param x Top-Left grabbing rectangle horizontal coordinate
  345. * @param y Top-Left grabbing rectangle vertical coordinate
  346. * @return 0 if error, !0 if successful
  347. */
  348. static int
  349. xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
  350. {
  351. xGetImageReply rep;
  352. xGetImageReq *req;
  353. long nbytes;
  354. if (!image) {
  355. return 0;
  356. }
  357. LockDisplay(dpy);
  358. GetReq(GetImage, req);
  359. /* First set up the standard stuff in the request */
  360. req->drawable = d;
  361. req->x = x;
  362. req->y = y;
  363. req->width = image->width;
  364. req->height = image->height;
  365. req->planeMask = (unsigned int)AllPlanes;
  366. req->format = ZPixmap;
  367. if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
  368. UnlockDisplay(dpy);
  369. SyncHandle();
  370. return 0;
  371. }
  372. nbytes = (long)rep.length << 2;
  373. _XReadPad(dpy, image->data, nbytes);
  374. UnlockDisplay(dpy);
  375. SyncHandle();
  376. return 1;
  377. }
  378. /**
  379. * Grabs a frame from x11 (public device demuxer API).
  380. *
  381. * @param s1 Context from avformat core
  382. * @param pkt Packet holding the brabbed frame
  383. * @return frame size in bytes
  384. */
  385. static int
  386. x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
  387. {
  388. struct x11_grab *s = s1->priv_data;
  389. Display *dpy = s->dpy;
  390. XImage *image = s->image;
  391. int x_off = s->x_off;
  392. int y_off = s->y_off;
  393. int64_t curtime, delay;
  394. struct timespec ts;
  395. /* Calculate the time of the next frame */
  396. s->time_frame += INT64_C(1000000);
  397. /* wait based on the frame rate */
  398. for(;;) {
  399. curtime = av_gettime();
  400. delay = s->time_frame * av_q2d(s->time_base) - curtime;
  401. if (delay <= 0) {
  402. if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
  403. s->time_frame += INT64_C(1000000);
  404. }
  405. break;
  406. }
  407. ts.tv_sec = delay / 1000000;
  408. ts.tv_nsec = (delay % 1000000) * 1000;
  409. nanosleep(&ts, NULL);
  410. }
  411. if (av_new_packet(pkt, s->frame_size) < 0) {
  412. return AVERROR(EIO);
  413. }
  414. pkt->pts = curtime;
  415. if(s->use_shm) {
  416. if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
  417. av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
  418. }
  419. } else {
  420. if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
  421. av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
  422. }
  423. }
  424. {
  425. int pointer_x, pointer_y;
  426. get_pointer_coordinates(&pointer_x, &pointer_y, dpy, s1);
  427. paint_mouse_pointer(image, s, pointer_x, pointer_y);
  428. }
  429. /* XXX: avoid memcpy */
  430. memcpy(pkt->data, image->data, s->frame_size);
  431. return s->frame_size;
  432. }
  433. /**
  434. * Closes x11 frame grabber (public device demuxer API).
  435. *
  436. * @param s1 Context from avformat core
  437. * @return 0 success, !0 failure
  438. */
  439. static int
  440. x11grab_read_close(AVFormatContext *s1)
  441. {
  442. struct x11_grab *x11grab = s1->priv_data;
  443. /* Detach cleanly from shared mem */
  444. if (x11grab->use_shm) {
  445. XShmDetach(x11grab->dpy, &x11grab->shminfo);
  446. shmdt(x11grab->shminfo.shmaddr);
  447. shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
  448. }
  449. /* Destroy X11 image */
  450. if (x11grab->image) {
  451. XDestroyImage(x11grab->image);
  452. x11grab->image = NULL;
  453. }
  454. /* Free X11 display */
  455. XCloseDisplay(x11grab->dpy);
  456. return 0;
  457. }
  458. /** x11 grabber device demuxer declaration */
  459. AVInputFormat x11_grab_device_demuxer =
  460. {
  461. "x11grab",
  462. NULL_IF_CONFIG_SMALL("X11grab"),
  463. sizeof(struct x11_grab),
  464. NULL,
  465. x11grab_read_header,
  466. x11grab_read_packet,
  467. x11grab_read_close,
  468. .flags = AVFMT_NOFILE,
  469. };