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.

533 lines
17KB

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