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.

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