Statistics
| Branch: | Revision:

ffmpeg / libavdevice / x11grab.c @ 62a0525d

History | View | Annotate | Download (16.4 KB)

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
/**
33
 * @file libavdevice/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 "config.h"
39
#include "libavformat/avformat.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

    
49
/**
50
 * X11 Device Demuxer context
51
 */
52
struct x11_grab
53
{
54
    int frame_size;          /**< Size in bytes of a grabbed frame */
55
    AVRational time_base;    /**< Time base */
56
    int64_t time_frame;      /**< Current time */
57

    
58
    int height;              /**< Height of the grab frame */
59
    int width;               /**< Width of the grab frame */
60
    int x_off;               /**< Horizontal top-left corner coordinate */
61
    int y_off;               /**< Vertical top-left corner coordinate */
62

    
63
    Display *dpy;            /**< X11 display from which x11grab grabs frames */
64
    XImage *image;           /**< X11 image holding the grab */
65
    int use_shm;             /**< !0 when using XShm extension */
66
    XShmSegmentInfo shminfo; /**< When using XShm, keeps track of XShm infos */
67
    int mouse_warning_shown;
68
};
69

    
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>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
    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

    
94
    param = av_strdup(s1->filename);
95
    offset = strchr(param, '+');
96
    if (offset) {
97
        sscanf(offset, "%d,%d", &x_off, &y_off);
98
        *offset= 0;
99
    }
100

    
101
    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);
102

    
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

    
109
    if (!ap || ap->width <= 0 || ap->height <= 0 || ap->time_base.den <= 0) {
110
        av_log(s1, AV_LOG_ERROR, "AVParameters don't have video size and/or rate. Use -s and -r.\n");
111
        return AVERROR(EIO);
112
    }
113

    
114
    st = av_new_stream(s1, 0);
115
    if (!st) {
116
        return AVERROR(ENOMEM);
117
    }
118
    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
119

    
120
    use_shm = XShmQueryExtension(dpy);
121
    av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not");
122

    
123
    if(use_shm) {
124
        int scr = XDefaultScreen(dpy);
125
        image = XShmCreateImage(dpy,
126
                                DefaultVisual(dpy, scr),
127
                                DefaultDepth(dpy, scr),
128
                                ZPixmap,
129
                                NULL,
130
                                &x11grab->shminfo,
131
                                ap->width, ap->height);
132
        x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
133
                                        image->bytes_per_line * image->height,
134
                                        IPC_CREAT|0777);
135
        if (x11grab->shminfo.shmid == -1) {
136
            av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
137
            return AVERROR(ENOMEM);
138
        }
139
        x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
140
        x11grab->shminfo.readOnly = False;
141

    
142
        if (!XShmAttach(dpy, &x11grab->shminfo)) {
143
            av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
144
            /* needs some better error subroutine :) */
145
            return AVERROR(EIO);
146
        }
147
    } else {
148
        image = XGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)),
149
                          x_off,y_off,
150
                          ap->width,ap->height,
151
                          AllPlanes, ZPixmap);
152
    }
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(EIO);
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(EIO);
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(EIO);
205
        }
206
#endif
207
        input_pixfmt = PIX_FMT_RGB32;
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

    
214
    x11grab->frame_size = ap->width * ap->height * image->bits_per_pixel/8;
215
    x11grab->dpy = dpy;
216
    x11grab->width = ap->width;
217
    x11grab->height = ap->height;
218
    x11grab->time_base  = ap->time_base;
219
    x11grab->time_frame = av_gettime() / av_q2d(ap->time_base);
220
    x11grab->x_off = x_off;
221
    x11grab->y_off = y_off;
222
    x11grab->image = image;
223
    x11grab->use_shm = use_shm;
224
    x11grab->mouse_warning_shown = 0;
225

    
226
    st->codec->codec_type = CODEC_TYPE_VIDEO;
227
    st->codec->codec_id = CODEC_ID_RAWVIDEO;
228
    st->codec->width = ap->width;
229
    st->codec->height = ap->height;
230
    st->codec->pix_fmt = input_pixfmt;
231
    st->codec->time_base = ap->time_base;
232
    st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(ap->time_base) * 8;
233

    
234
    return 0;
235
}
236

    
237
/**
238
 * Get pointer coordinates from X11.
239
 *
240
 * @param x Integer where horizontal coordinate will be returned
241
 * @param y Integer where vertical coordinate will be returned
242
 * @param dpy X11 display from where pointer coordinates are retrieved
243
 * @param s1 Context used for logging errors if necessary
244
 */
245
static void
246
get_pointer_coordinates(int *x, int *y, Display *dpy, AVFormatContext *s1)
247
{
248
    Window mrootwindow, childwindow;
249
    int dummy;
250

    
251
    mrootwindow = DefaultRootWindow(dpy);
252

    
253
    if (XQueryPointer(dpy, mrootwindow, &mrootwindow, &childwindow,
254
                      x, y, &dummy, &dummy, (unsigned int*)&dummy)) {
255
    } else {
256
        struct x11_grab *s = s1->priv_data;
257
        if (!s->mouse_warning_shown) {
258
            av_log(s1, AV_LOG_INFO, "couldn't find mouse pointer\n");
259
            s->mouse_warning_shown = 1;
260
        }
261
        *x = -1;
262
        *y = -1;
263
    }
264
}
265

    
266
/**
267
 * Mouse painting helper function that applies an 'and' and 'or' mask pair to
268
 * '*dst' pixel. It actually draws a mouse pointer pixel to grabbed frame.
269
 *
270
 * @param dst Destination pixel
271
 * @param and Part of the mask that must be applied using a bitwise 'and'
272
 *            operator
273
 * @param or  Part of the mask that must be applied using a bitwise 'or'
274
 *            operator
275
 * @param bits_per_pixel Bits per pixel used in the grabbed image
276
 */
277
static void inline
278
apply_masks(uint8_t *dst, int and, int or, int bits_per_pixel)
279
{
280
    switch (bits_per_pixel) {
281
    case 32:
282
        *(uint32_t*)dst = (*(uint32_t*)dst & and) | or;
283
        break;
284
    case 16:
285
        *(uint16_t*)dst = (*(uint16_t*)dst & and) | or;
286
        break;
287
    case 8:
288
        *dst = !!or;
289
        break;
290
    }
291
}
292

    
293
/**
294
 * Paints a mouse pointer in an X11 image.
295
 *
296
 * @param image image to paint the mouse pointer to
297
 * @param s context used to retrieve original grabbing rectangle
298
 *          coordinates
299
 * @param x Mouse pointer coordinate
300
 * @param y Mouse pointer coordinate
301
 */
302
static void
303
paint_mouse_pointer(XImage *image, struct x11_grab *s, int x, int y)
304
{
305
    /* 16x20x1bpp bitmap for the black channel of the mouse pointer */
306
    static const uint16_t const mousePointerBlack[] =
307
        {
308
            0x0000, 0x0003, 0x0005, 0x0009, 0x0011,
309
            0x0021, 0x0041, 0x0081, 0x0101, 0x0201,
310
            0x03c1, 0x0049, 0x0095, 0x0093, 0x0120,
311
            0x0120, 0x0240, 0x0240, 0x0380, 0x0000
312
        };
313

    
314
    /* 16x20x1bpp bitmap for the white channel of the mouse pointer */
315
    static const uint16_t const mousePointerWhite[] =
316
        {
317
            0x0000, 0x0000, 0x0002, 0x0006, 0x000e,
318
            0x001e, 0x003e, 0x007e, 0x00fe, 0x01fe,
319
            0x003e, 0x0036, 0x0062, 0x0060, 0x00c0,
320
            0x00c0, 0x0180, 0x0180, 0x0000, 0x0000
321
        };
322

    
323
    int x_off = s->x_off;
324
    int y_off = s->y_off;
325
    int width = s->width;
326
    int height = s->height;
327

    
328
    if (   x - x_off >= 0 && x < width + x_off
329
        && y - y_off >= 0 && y < height + y_off) {
330
        uint8_t *im_data = (uint8_t*)image->data;
331
        int bytes_per_pixel;
332
        int line;
333
        int masks;
334

    
335
        /* Select correct masks and pixel size */
336
        if (image->bits_per_pixel == 8) {
337
            masks = 1;
338
        } else {
339
            masks = (image->red_mask|image->green_mask|image->blue_mask);
340
        }
341
        bytes_per_pixel = image->bits_per_pixel>>3;
342

    
343
        /* Shift to right line */
344
        im_data += image->bytes_per_line * (y - y_off);
345
        /* Shift to right pixel in the line */
346
        im_data += bytes_per_pixel * (x - x_off);
347

    
348
        /* Draw the cursor - proper loop */
349
        for (line = 0; line < FFMIN(20, (y_off + height) - y); line++) {
350
            uint8_t *cursor = im_data;
351
            int column;
352
            uint16_t bm_b;
353
            uint16_t bm_w;
354

    
355
            bm_b = mousePointerBlack[line];
356
            bm_w = mousePointerWhite[line];
357

    
358
            for (column = 0; column < FFMIN(16, (x_off + width) - x); column++) {
359
                apply_masks(cursor, ~(masks*(bm_b&1)), masks*(bm_w&1),
360
                            image->bits_per_pixel);
361
                cursor += bytes_per_pixel;
362
                bm_b >>= 1;
363
                bm_w >>= 1;
364
            }
365
            im_data += image->bytes_per_line;
366
        }
367
    }
368
}
369

    
370

    
371
/**
372
 * Reads new data in the image structure.
373
 *
374
 * @param dpy X11 display to grab from
375
 * @param d
376
 * @param image Image where the grab will be put
377
 * @param x Top-Left grabbing rectangle horizontal coordinate
378
 * @param y Top-Left grabbing rectangle vertical coordinate
379
 * @return 0 if error, !0 if successful
380
 */
381
static int
382
xget_zpixmap(Display *dpy, Drawable d, XImage *image, int x, int y)
383
{
384
    xGetImageReply rep;
385
    xGetImageReq *req;
386
    long nbytes;
387

    
388
    if (!image) {
389
        return 0;
390
    }
391

    
392
    LockDisplay(dpy);
393
    GetReq(GetImage, req);
394

    
395
    /* First set up the standard stuff in the request */
396
    req->drawable = d;
397
    req->x = x;
398
    req->y = y;
399
    req->width = image->width;
400
    req->height = image->height;
401
    req->planeMask = (unsigned int)AllPlanes;
402
    req->format = ZPixmap;
403

    
404
    if (!_XReply(dpy, (xReply *)&rep, 0, xFalse) || !rep.length) {
405
        UnlockDisplay(dpy);
406
        SyncHandle();
407
        return 0;
408
    }
409

    
410
    nbytes = (long)rep.length << 2;
411
    _XReadPad(dpy, image->data, nbytes);
412

    
413
    UnlockDisplay(dpy);
414
    SyncHandle();
415
    return 1;
416
}
417

    
418
/**
419
 * Grabs a frame from x11 (public device demuxer API).
420
 *
421
 * @param s1 Context from avformat core
422
 * @param pkt Packet holding the brabbed frame
423
 * @return frame size in bytes
424
 */
425
static int
426
x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
427
{
428
    struct x11_grab *s = s1->priv_data;
429
    Display *dpy = s->dpy;
430
    XImage *image = s->image;
431
    int x_off = s->x_off;
432
    int y_off = s->y_off;
433

    
434
    int64_t curtime, delay;
435
    struct timespec ts;
436

    
437
    /* Calculate the time of the next frame */
438
    s->time_frame += INT64_C(1000000);
439

    
440
    /* wait based on the frame rate */
441
    for(;;) {
442
        curtime = av_gettime();
443
        delay = s->time_frame * av_q2d(s->time_base) - curtime;
444
        if (delay <= 0) {
445
            if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
446
                s->time_frame += INT64_C(1000000);
447
            }
448
            break;
449
        }
450
        ts.tv_sec = delay / 1000000;
451
        ts.tv_nsec = (delay % 1000000) * 1000;
452
        nanosleep(&ts, NULL);
453
    }
454

    
455
    if (av_new_packet(pkt, s->frame_size) < 0) {
456
        return AVERROR(EIO);
457
    }
458

    
459
    pkt->pts = curtime;
460

    
461
    if(s->use_shm) {
462
        if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {
463
            av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
464
        }
465
    } else {
466
        if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {
467
            av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
468
        }
469
    }
470

    
471
    {
472
        int pointer_x, pointer_y;
473
        get_pointer_coordinates(&pointer_x, &pointer_y, dpy, s1);
474
        paint_mouse_pointer(image, s, pointer_x, pointer_y);
475
    }
476

    
477

    
478
    /* XXX: avoid memcpy */
479
    memcpy(pkt->data, image->data, s->frame_size);
480
    return s->frame_size;
481
}
482

    
483
/**
484
 * Closes x11 frame grabber (public device demuxer API).
485
 *
486
 * @param s1 Context from avformat core
487
 * @return 0 success, !0 failure
488
 */
489
static int
490
x11grab_read_close(AVFormatContext *s1)
491
{
492
    struct x11_grab *x11grab = s1->priv_data;
493

    
494
    /* Detach cleanly from shared mem */
495
    if (x11grab->use_shm) {
496
        XShmDetach(x11grab->dpy, &x11grab->shminfo);
497
        shmdt(x11grab->shminfo.shmaddr);
498
        shmctl(x11grab->shminfo.shmid, IPC_RMID, NULL);
499
    }
500

    
501
    /* Destroy X11 image */
502
    if (x11grab->image) {
503
        XDestroyImage(x11grab->image);
504
        x11grab->image = NULL;
505
    }
506

    
507
    /* Free X11 display */
508
    XCloseDisplay(x11grab->dpy);
509
    return 0;
510
}
511

    
512
/** x11 grabber device demuxer declaration */
513
AVInputFormat x11_grab_device_demuxer =
514
{
515
    "x11grab",
516
    NULL_IF_CONFIG_SMALL("X11grab"),
517
    sizeof(struct x11_grab),
518
    NULL,
519
    x11grab_read_header,
520
    x11grab_read_packet,
521
    x11grab_read_close,
522
    .flags = AVFMT_NOFILE,
523
};