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