]> git.sesse.net Git - ffmpeg/blob - libavdevice/xcbgrab.c
avformat/asfdec_o: use av_packet_alloc() to allocate packets
[ffmpeg] / libavdevice / xcbgrab.c
1 /*
2  * XCB input grabber
3  * Copyright (C) 2014 Luca Barbato <lu_zero@gentoo.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include <stdlib.h>
25 #include <string.h>
26 #include <xcb/xcb.h>
27
28 #if CONFIG_LIBXCB_XFIXES
29 #include <xcb/xfixes.h>
30 #endif
31
32 #if CONFIG_LIBXCB_SHM
33 #include <sys/shm.h>
34 #include <xcb/shm.h>
35 #endif
36
37 #if CONFIG_LIBXCB_SHAPE
38 #include <xcb/shape.h>
39 #endif
40
41 #include "libavutil/internal.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/opt.h"
44 #include "libavutil/parseutils.h"
45 #include "libavutil/time.h"
46
47 #include "libavformat/avformat.h"
48 #include "libavformat/internal.h"
49
50 typedef struct XCBGrabContext {
51     const AVClass *class;
52
53     xcb_connection_t *conn;
54     xcb_screen_t *screen;
55     xcb_window_t window;
56 #if CONFIG_LIBXCB_SHM
57     AVBufferPool *shm_pool;
58 #endif
59     int64_t time_frame;
60     AVRational time_base;
61     int64_t frame_duration;
62
63     xcb_window_t window_id;
64     int x, y;
65     int width, height;
66     int frame_size;
67     int bpp;
68
69     int draw_mouse;
70     int follow_mouse;
71     int show_region;
72     int region_border;
73     int centered;
74     int select_region;
75
76     const char *framerate;
77
78     int has_shm;
79 } XCBGrabContext;
80
81 #define FOLLOW_CENTER -1
82
83 #define OFFSET(x) offsetof(XCBGrabContext, x)
84 #define D AV_OPT_FLAG_DECODING_PARAM
85 static const AVOption options[] = {
86     { "window_id", "Window to capture.", OFFSET(window_id), AV_OPT_TYPE_INT, { .i64 = XCB_NONE }, 0, UINT32_MAX, D },
87     { "x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
88     { "y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
89     { "grab_x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
90     { "grab_y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
91     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL }, 0, 0, D },
92     { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc" }, 0, 0, D },
93     { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
94     { "follow_mouse", "Move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region.",
95       OFFSET(follow_mouse), AV_OPT_TYPE_INT, { .i64 = 0 },  FOLLOW_CENTER, INT_MAX, D, "follow_mouse" },
96     { "centered", "Keep the mouse pointer at the center of grabbing region when following.", 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, D, "follow_mouse" },
97     { "show_region", "Show the grabbing region.", OFFSET(show_region), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
98     { "region_border", "Set the region border thickness.", OFFSET(region_border), AV_OPT_TYPE_INT, { .i64 = 3 }, 1, 128, D },
99     { "select_region", "Select the grabbing region graphically using the pointer.", OFFSET(select_region), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
100     { NULL },
101 };
102
103 static const AVClass xcbgrab_class = {
104     .class_name = "xcbgrab indev",
105     .item_name  = av_default_item_name,
106     .option     = options,
107     .version    = LIBAVUTIL_VERSION_INT,
108     .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
109 };
110
111 static int xcbgrab_reposition(AVFormatContext *s,
112                               xcb_query_pointer_reply_t *p,
113                               xcb_get_geometry_reply_t *geo)
114 {
115     XCBGrabContext *c = s->priv_data;
116     int x = c->x, y = c->y;
117     int w = c->width, h = c->height, f = c->follow_mouse;
118     int p_x, p_y;
119
120     if (!p || !geo)
121         return AVERROR(EIO);
122
123     p_x = p->win_x;
124     p_y = p->win_y;
125
126     if (f == FOLLOW_CENTER) {
127         x = p_x - w / 2;
128         y = p_y - h / 2;
129     } else {
130         int left   = x + f;
131         int right  = x + w - f;
132         int top    = y + f;
133         int bottom = y + h - f;
134         if (p_x > right) {
135             x += p_x - right;
136         } else if (p_x < left) {
137             x -= left - p_x;
138         }
139         if (p_y > bottom) {
140             y += p_y - bottom;
141         } else if (p_y < top) {
142             y -= top - p_y;
143         }
144     }
145
146     c->x = FFMIN(FFMAX(0, x), geo->width  - w);
147     c->y = FFMIN(FFMAX(0, y), geo->height - h);
148
149     return 0;
150 }
151
152 static void xcbgrab_image_reply_free(void *opaque, uint8_t *data)
153 {
154     free(opaque);
155 }
156
157 static int xcbgrab_frame(AVFormatContext *s, AVPacket *pkt)
158 {
159     XCBGrabContext *c = s->priv_data;
160     xcb_get_image_cookie_t iq;
161     xcb_get_image_reply_t *img;
162     xcb_drawable_t drawable = c->window_id;
163     xcb_generic_error_t *e = NULL;
164     uint8_t *data;
165     int length;
166
167     iq  = xcb_get_image(c->conn, XCB_IMAGE_FORMAT_Z_PIXMAP, drawable,
168                         c->x, c->y, c->width, c->height, ~0);
169
170     img = xcb_get_image_reply(c->conn, iq, &e);
171
172     if (e) {
173         av_log(s, AV_LOG_ERROR,
174                "Cannot get the image data "
175                "event_error: response_type:%u error_code:%u "
176                "sequence:%u resource_id:%u minor_code:%u major_code:%u.\n",
177                e->response_type, e->error_code,
178                e->sequence, e->resource_id, e->minor_code, e->major_code);
179         free(e);
180         return AVERROR(EACCES);
181     }
182
183     if (!img)
184         return AVERROR(EAGAIN);
185
186     data   = xcb_get_image_data(img);
187     length = xcb_get_image_data_length(img);
188
189     av_init_packet(pkt);
190
191     pkt->buf = av_buffer_create(data, length, xcbgrab_image_reply_free, img, 0);
192     if (!pkt->buf) {
193         free(img);
194         return AVERROR(ENOMEM);
195     }
196
197     pkt->data = data;
198     pkt->size = length;
199
200     return 0;
201 }
202
203 static int64_t wait_frame(AVFormatContext *s, AVPacket *pkt)
204 {
205     XCBGrabContext *c = s->priv_data;
206     int64_t curtime, delay;
207
208     c->time_frame += c->frame_duration;
209
210     for (;;) {
211         curtime = av_gettime_relative();
212         delay   = c->time_frame - curtime;
213         if (delay <= 0)
214             break;
215         av_usleep(delay);
216     }
217
218     return curtime;
219 }
220
221 #if CONFIG_LIBXCB_SHM
222 static int check_shm(xcb_connection_t *conn)
223 {
224     xcb_shm_query_version_cookie_t cookie = xcb_shm_query_version(conn);
225     xcb_shm_query_version_reply_t *reply;
226
227     reply = xcb_shm_query_version_reply(conn, cookie, NULL);
228     if (reply) {
229         free(reply);
230         return 1;
231     }
232
233     return 0;
234 }
235
236 static void free_shm_buffer(void *opaque, uint8_t *data)
237 {
238     shmdt(data);
239 }
240
241 static AVBufferRef *allocate_shm_buffer(void *opaque, buffer_size_t size)
242 {
243     xcb_connection_t *conn = opaque;
244     xcb_shm_seg_t segment;
245     AVBufferRef *ref;
246     uint8_t *data;
247     int id;
248
249     id = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
250     if (id == -1)
251         return NULL;
252
253     segment = xcb_generate_id(conn);
254     xcb_shm_attach(conn, segment, id, 0);
255     data = shmat(id, NULL, 0);
256     shmctl(id, IPC_RMID, 0);
257     if ((intptr_t)data == -1 || !data)
258         return NULL;
259
260     ref = av_buffer_create(data, size, free_shm_buffer, (void *)(ptrdiff_t)segment, 0);
261     if (!ref)
262         shmdt(data);
263
264     return ref;
265 }
266
267 static int xcbgrab_frame_shm(AVFormatContext *s, AVPacket *pkt)
268 {
269     XCBGrabContext *c = s->priv_data;
270     xcb_shm_get_image_cookie_t iq;
271     xcb_shm_get_image_reply_t *img;
272     xcb_drawable_t drawable = c->window_id;
273     xcb_generic_error_t *e = NULL;
274     AVBufferRef *buf;
275     xcb_shm_seg_t segment;
276
277     buf = av_buffer_pool_get(c->shm_pool);
278     if (!buf) {
279         av_log(s, AV_LOG_ERROR, "Could not get shared memory buffer.\n");
280         return AVERROR(ENOMEM);
281     }
282     segment = (xcb_shm_seg_t)av_buffer_pool_buffer_get_opaque(buf);
283
284     iq = xcb_shm_get_image(c->conn, drawable,
285                            c->x, c->y, c->width, c->height, ~0,
286                            XCB_IMAGE_FORMAT_Z_PIXMAP, segment, 0);
287     img = xcb_shm_get_image_reply(c->conn, iq, &e);
288
289     xcb_flush(c->conn);
290
291     if (e) {
292         av_log(s, AV_LOG_ERROR,
293                "Cannot get the image data "
294                "event_error: response_type:%u error_code:%u "
295                "sequence:%u resource_id:%u minor_code:%u major_code:%u.\n",
296                e->response_type, e->error_code,
297                e->sequence, e->resource_id, e->minor_code, e->major_code);
298
299         free(e);
300         av_buffer_unref(&buf);
301         return AVERROR(EACCES);
302     }
303
304     free(img);
305
306     av_init_packet(pkt);
307
308     pkt->buf = buf;
309     pkt->data = buf->data;
310     pkt->size = c->frame_size;
311
312     return 0;
313 }
314 #endif /* CONFIG_LIBXCB_SHM */
315
316 #if CONFIG_LIBXCB_XFIXES
317 static int check_xfixes(xcb_connection_t *conn)
318 {
319     xcb_xfixes_query_version_cookie_t cookie;
320     xcb_xfixes_query_version_reply_t *reply;
321
322     cookie = xcb_xfixes_query_version(conn, XCB_XFIXES_MAJOR_VERSION,
323                                       XCB_XFIXES_MINOR_VERSION);
324     reply  = xcb_xfixes_query_version_reply(conn, cookie, NULL);
325
326     if (reply) {
327         free(reply);
328         return 1;
329     }
330     return 0;
331 }
332
333 #define BLEND(target, source, alpha) \
334     (target) + ((source) * (255 - (alpha)) + 255 / 2) / 255
335
336 static void xcbgrab_draw_mouse(AVFormatContext *s, AVPacket *pkt,
337                                xcb_query_pointer_reply_t *p,
338                                xcb_get_geometry_reply_t *geo,
339                                int win_x, int win_y)
340 {
341     XCBGrabContext *gr = s->priv_data;
342     uint32_t *cursor;
343     uint8_t *image = pkt->data;
344     int stride     = gr->bpp / 8;
345     xcb_xfixes_get_cursor_image_cookie_t cc;
346     xcb_xfixes_get_cursor_image_reply_t *ci;
347     int cx, cy, x, y, w, h, c_off, i_off;
348
349     cc = xcb_xfixes_get_cursor_image(gr->conn);
350     ci = xcb_xfixes_get_cursor_image_reply(gr->conn, cc, NULL);
351     if (!ci)
352         return;
353
354     cursor = xcb_xfixes_get_cursor_image_cursor_image(ci);
355     if (!cursor)
356         return;
357
358     cx = ci->x - ci->xhot;
359     cy = ci->y - ci->yhot;
360
361     x = FFMAX(cx, win_x + gr->x);
362     y = FFMAX(cy, win_y + gr->y);
363
364     w = FFMIN(cx + ci->width,  win_x + gr->x + gr->width)  - x;
365     h = FFMIN(cy + ci->height, win_y + gr->y + gr->height) - y;
366
367     c_off = x - cx;
368     i_off = x - gr->x - win_x;
369
370     cursor += (y - cy) * ci->width;
371     image  += (y - gr->y - win_y) * gr->width * stride;
372
373     for (y = 0; y < h; y++) {
374         cursor += c_off;
375         image  += i_off * stride;
376         for (x = 0; x < w; x++, cursor++, image += stride) {
377             int r, g, b, a;
378
379             r =  *cursor        & 0xff;
380             g = (*cursor >>  8) & 0xff;
381             b = (*cursor >> 16) & 0xff;
382             a = (*cursor >> 24) & 0xff;
383
384             if (!a)
385                 continue;
386
387             if (a == 255) {
388                 image[0] = r;
389                 image[1] = g;
390                 image[2] = b;
391             } else {
392                 image[0] = BLEND(r, image[0], a);
393                 image[1] = BLEND(g, image[1], a);
394                 image[2] = BLEND(b, image[2], a);
395             }
396
397         }
398         cursor +=  ci->width - w - c_off;
399         image  += (gr->width - w - i_off) * stride;
400     }
401
402     free(ci);
403 }
404 #endif /* CONFIG_LIBXCB_XFIXES */
405
406 static void xcbgrab_update_region(AVFormatContext *s, int win_x, int win_y)
407 {
408     XCBGrabContext *c     = s->priv_data;
409     const uint32_t args[] = { win_x + c->x - c->region_border,
410                               win_y + c->y - c->region_border };
411
412     xcb_configure_window(c->conn,
413                          c->window,
414                          XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y,
415                          args);
416 }
417
418 static int xcbgrab_read_packet(AVFormatContext *s, AVPacket *pkt)
419 {
420     XCBGrabContext *c = s->priv_data;
421     xcb_query_pointer_cookie_t pc;
422     xcb_get_geometry_cookie_t gc;
423     xcb_translate_coordinates_cookie_t tc;
424     xcb_query_pointer_reply_t *p  = NULL;
425     xcb_get_geometry_reply_t *geo = NULL;
426     xcb_translate_coordinates_reply_t *translate = NULL;
427     int ret = 0;
428     int64_t pts;
429     int win_x = 0, win_y = 0;
430
431     wait_frame(s, pkt);
432     pts = av_gettime();
433
434     if (c->follow_mouse || c->draw_mouse) {
435         pc  = xcb_query_pointer(c->conn, c->window_id);
436         gc  = xcb_get_geometry(c->conn, c->window_id);
437         p   = xcb_query_pointer_reply(c->conn, pc, NULL);
438         if (!p) {
439             av_log(s, AV_LOG_ERROR, "Failed to query xcb pointer\n");
440             return AVERROR_EXTERNAL;
441         }
442         geo = xcb_get_geometry_reply(c->conn, gc, NULL);
443         if (!geo) {
444             av_log(s, AV_LOG_ERROR, "Failed to get xcb geometry\n");
445             free(p);
446             return AVERROR_EXTERNAL;
447         }
448     }
449     if (c->window_id != c->screen->root) {
450         tc = xcb_translate_coordinates(c->conn, c->window_id, c->screen->root, 0, 0);
451         translate = xcb_translate_coordinates_reply(c->conn, tc, NULL);
452         if (!translate) {
453             free(p);
454             free(geo);
455             av_log(s, AV_LOG_ERROR, "Failed to translate xcb geometry\n");
456             return AVERROR_EXTERNAL;
457         }
458         win_x = translate->dst_x;
459         win_y = translate->dst_y;
460         free(translate);
461     }
462
463     if (c->follow_mouse && p->same_screen)
464         xcbgrab_reposition(s, p, geo);
465
466     if (c->show_region)
467         xcbgrab_update_region(s, win_x, win_y);
468
469 #if CONFIG_LIBXCB_SHM
470     if (c->has_shm && xcbgrab_frame_shm(s, pkt) < 0) {
471         av_log(s, AV_LOG_WARNING, "Continuing without shared memory.\n");
472         c->has_shm = 0;
473     }
474 #endif
475     if (!c->has_shm)
476         ret = xcbgrab_frame(s, pkt);
477     pkt->dts = pkt->pts = pts;
478     pkt->duration = c->frame_duration;
479
480 #if CONFIG_LIBXCB_XFIXES
481     if (ret >= 0 && c->draw_mouse && p->same_screen)
482         xcbgrab_draw_mouse(s, pkt, p, geo, win_x, win_y);
483 #endif
484
485     free(p);
486     free(geo);
487
488     return ret;
489 }
490
491 static av_cold int xcbgrab_read_close(AVFormatContext *s)
492 {
493     XCBGrabContext *ctx = s->priv_data;
494
495 #if CONFIG_LIBXCB_SHM
496     av_buffer_pool_uninit(&ctx->shm_pool);
497 #endif
498
499     xcb_disconnect(ctx->conn);
500
501     return 0;
502 }
503
504 static xcb_screen_t *get_screen(const xcb_setup_t *setup, int screen_num)
505 {
506     xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup);
507     xcb_screen_t *screen     = NULL;
508
509     for (; it.rem > 0; xcb_screen_next (&it)) {
510         if (!screen_num) {
511             screen = it.data;
512             break;
513         }
514
515         screen_num--;
516     }
517
518     return screen;
519 }
520
521 static int pixfmt_from_pixmap_format(AVFormatContext *s, int depth,
522                                      int *pix_fmt, int *bpp)
523 {
524     XCBGrabContext *c        = s->priv_data;
525     const xcb_setup_t *setup = xcb_get_setup(c->conn);
526     const xcb_format_t *fmt  = xcb_setup_pixmap_formats(setup);
527     int length               = xcb_setup_pixmap_formats_length(setup);
528
529     *pix_fmt = 0;
530
531     while (length--) {
532         if (fmt->depth == depth) {
533             switch (depth) {
534             case 32:
535                 if (fmt->bits_per_pixel == 32)
536                     *pix_fmt = setup->image_byte_order == XCB_IMAGE_ORDER_LSB_FIRST ?
537                                AV_PIX_FMT_BGR0 : AV_PIX_FMT_0RGB;
538                 break;
539             case 24:
540                 if (fmt->bits_per_pixel == 32)
541                     *pix_fmt = setup->image_byte_order == XCB_IMAGE_ORDER_LSB_FIRST ?
542                                AV_PIX_FMT_BGR0 : AV_PIX_FMT_0RGB;
543                 else if (fmt->bits_per_pixel == 24)
544                     *pix_fmt = setup->image_byte_order == XCB_IMAGE_ORDER_LSB_FIRST ?
545                                AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24;
546                 break;
547             case 16:
548                 if (fmt->bits_per_pixel == 16)
549                     *pix_fmt = setup->image_byte_order == XCB_IMAGE_ORDER_LSB_FIRST ?
550                                AV_PIX_FMT_RGB565LE : AV_PIX_FMT_RGB565BE;
551                 break;
552             case 15:
553                 if (fmt->bits_per_pixel == 16)
554                     *pix_fmt = setup->image_byte_order == XCB_IMAGE_ORDER_LSB_FIRST ?
555                                AV_PIX_FMT_RGB555LE : AV_PIX_FMT_RGB555BE;
556                 break;
557             case 8:
558                 if (fmt->bits_per_pixel == 8)
559                     *pix_fmt = AV_PIX_FMT_RGB8;
560                 break;
561             }
562         }
563
564         if (*pix_fmt) {
565             *bpp        = fmt->bits_per_pixel;
566             return 0;
567         }
568
569         fmt++;
570     }
571     avpriv_report_missing_feature(s, "Mapping this pixmap format");
572
573     return AVERROR_PATCHWELCOME;
574 }
575
576 static int create_stream(AVFormatContext *s)
577 {
578     XCBGrabContext *c = s->priv_data;
579     AVStream *st      = avformat_new_stream(s, NULL);
580     xcb_get_geometry_cookie_t gc;
581     xcb_get_geometry_reply_t *geo;
582     int64_t frame_size_bits;
583     int ret;
584
585     if (!st)
586         return AVERROR(ENOMEM);
587
588     ret = av_parse_video_rate(&st->avg_frame_rate, c->framerate);
589     if (ret < 0)
590         return ret;
591
592     avpriv_set_pts_info(st, 64, 1, 1000000);
593
594     gc  = xcb_get_geometry(c->conn, c->window_id);
595     geo = xcb_get_geometry_reply(c->conn, gc, NULL);
596     if (!geo) {
597         av_log(s, AV_LOG_ERROR, "Can't find window '0x%x', aborting.\n", c->window_id);
598         return AVERROR_EXTERNAL;
599     }
600
601     if (!c->width || !c->height) {
602         c->width = geo->width;
603         c->height = geo->height;
604     }
605
606     if (c->x + c->width > geo->width ||
607         c->y + c->height > geo->height) {
608         av_log(s, AV_LOG_ERROR,
609                "Capture area %dx%d at position %d.%d "
610                "outside the screen size %dx%d\n",
611                c->width, c->height,
612                c->x, c->y,
613                geo->width, geo->height);
614         free(geo);
615         return AVERROR(EINVAL);
616     }
617
618     c->time_base  = (AVRational){ st->avg_frame_rate.den,
619                                   st->avg_frame_rate.num };
620     c->frame_duration = av_rescale_q(1, c->time_base, AV_TIME_BASE_Q);
621     c->time_frame = av_gettime_relative();
622
623     ret = pixfmt_from_pixmap_format(s, geo->depth, &st->codecpar->format, &c->bpp);
624     free(geo);
625     if (ret < 0)
626         return ret;
627
628     frame_size_bits = (int64_t)c->width * c->height * c->bpp;
629     if (frame_size_bits / 8 + AV_INPUT_BUFFER_PADDING_SIZE > INT_MAX) {
630         av_log(s, AV_LOG_ERROR, "Captured area is too large\n");
631         return AVERROR_PATCHWELCOME;
632     }
633     c->frame_size = frame_size_bits / 8;
634
635 #if CONFIG_LIBXCB_SHM
636     c->shm_pool = av_buffer_pool_init2(c->frame_size + AV_INPUT_BUFFER_PADDING_SIZE,
637                                            c->conn, allocate_shm_buffer, NULL);
638     if (!c->shm_pool)
639         return AVERROR(ENOMEM);
640 #endif
641
642     st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
643     st->codecpar->codec_id   = AV_CODEC_ID_RAWVIDEO;
644     st->codecpar->width      = c->width;
645     st->codecpar->height     = c->height;
646     st->codecpar->bit_rate   = av_rescale(frame_size_bits, st->avg_frame_rate.num, st->avg_frame_rate.den);
647
648     return ret;
649 }
650
651 static void draw_rectangle(AVFormatContext *s)
652 {
653     XCBGrabContext *c = s->priv_data;
654     xcb_gcontext_t gc = xcb_generate_id(c->conn);
655     uint32_t mask     = XCB_GC_FOREGROUND |
656                         XCB_GC_BACKGROUND |
657                         XCB_GC_LINE_WIDTH |
658                         XCB_GC_LINE_STYLE |
659                         XCB_GC_FILL_STYLE;
660     uint32_t values[] = { c->screen->black_pixel,
661                           c->screen->white_pixel,
662                           c->region_border,
663                           XCB_LINE_STYLE_DOUBLE_DASH,
664                           XCB_FILL_STYLE_SOLID };
665     xcb_rectangle_t r = { 1, 1,
666                           c->width  + c->region_border * 2 - 3,
667                           c->height + c->region_border * 2 - 3 };
668
669     xcb_create_gc(c->conn, gc, c->window, mask, values);
670
671     xcb_poly_rectangle(c->conn, c->window, gc, 1, &r);
672 }
673
674 static void setup_window(AVFormatContext *s)
675 {
676     XCBGrabContext *c = s->priv_data;
677     uint32_t mask     = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
678     uint32_t values[] = { 1,
679                           XCB_EVENT_MASK_EXPOSURE |
680                           XCB_EVENT_MASK_STRUCTURE_NOTIFY };
681     av_unused xcb_rectangle_t rect = { 0, 0, c->width, c->height };
682
683     c->window = xcb_generate_id(c->conn);
684
685     xcb_create_window(c->conn, XCB_COPY_FROM_PARENT,
686                       c->window,
687                       c->screen->root,
688                       c->x - c->region_border,
689                       c->y - c->region_border,
690                       c->width + c->region_border * 2,
691                       c->height + c->region_border * 2,
692                       0,
693                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
694                       XCB_COPY_FROM_PARENT,
695                       mask, values);
696
697 #if CONFIG_LIBXCB_SHAPE
698     xcb_shape_rectangles(c->conn, XCB_SHAPE_SO_SUBTRACT,
699                          XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
700                          c->window,
701                          c->region_border, c->region_border,
702                          1, &rect);
703 #endif
704
705     xcb_map_window(c->conn, c->window);
706
707     draw_rectangle(s);
708 }
709
710 #define CROSSHAIR_CURSOR 34
711
712 static xcb_rectangle_t rectangle_from_corners(xcb_point_t *corner_a,
713                                               xcb_point_t *corner_b)
714 {
715     xcb_rectangle_t rectangle;
716     rectangle.x = FFMIN(corner_a->x, corner_b->x);
717     rectangle.y = FFMIN(corner_a->y, corner_b->y);
718     rectangle.width = FFABS(corner_a->x - corner_b->x);
719     rectangle.height = FFABS(corner_a->y - corner_b->y);
720     return rectangle;
721 }
722
723 static int select_region(AVFormatContext *s)
724 {
725     XCBGrabContext *c = s->priv_data;
726     xcb_connection_t *conn = c->conn;
727     xcb_screen_t *screen = c->screen;
728
729     int ret = 0, done = 0, was_pressed = 0;
730     xcb_cursor_t cursor;
731     xcb_font_t cursor_font;
732     xcb_point_t press_position;
733     xcb_generic_event_t *event;
734     xcb_rectangle_t rectangle = { 0 };
735     xcb_grab_pointer_reply_t *reply;
736     xcb_grab_pointer_cookie_t cookie;
737
738     xcb_window_t root_window = screen->root;
739     xcb_gcontext_t gc = xcb_generate_id(conn);
740     uint32_t mask = XCB_GC_FUNCTION | XCB_GC_SUBWINDOW_MODE;
741     uint32_t values[] = { XCB_GX_INVERT, XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS };
742     xcb_create_gc(conn, gc, root_window, mask, values);
743
744     cursor_font = xcb_generate_id(conn);
745     xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
746     cursor = xcb_generate_id(conn);
747     xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
748                             CROSSHAIR_CURSOR, CROSSHAIR_CURSOR + 1, 0, 0, 0,
749                             0xFFFF, 0xFFFF, 0xFFFF);
750     cookie = xcb_grab_pointer(conn, 0, root_window,
751                               XCB_EVENT_MASK_BUTTON_PRESS |
752                               XCB_EVENT_MASK_BUTTON_RELEASE |
753                               XCB_EVENT_MASK_BUTTON_MOTION,
754                               XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
755                               root_window, cursor, XCB_CURRENT_TIME);
756     reply = xcb_grab_pointer_reply(conn, cookie, NULL);
757     if (!reply || reply->status != XCB_GRAB_STATUS_SUCCESS) {
758         av_log(s, AV_LOG_ERROR,
759                "Failed to select region. Could not grab pointer.\n");
760         ret = AVERROR(EIO);
761         free(reply);
762         goto fail;
763     }
764     free(reply);
765
766     xcb_grab_server(conn);
767
768     while (!done && (event = xcb_wait_for_event(conn))) {
769         switch (event->response_type & ~0x80) {
770         case XCB_BUTTON_PRESS: {
771             xcb_button_press_event_t *press = (xcb_button_press_event_t *)event;
772             press_position = (xcb_point_t){ press->event_x, press->event_y };
773             rectangle.x = press_position.x;
774             rectangle.y = press_position.y;
775             xcb_poly_rectangle(conn, root_window, gc, 1, &rectangle);
776             was_pressed = 1;
777             break;
778         }
779         case XCB_MOTION_NOTIFY: {
780             if (was_pressed) {
781                 xcb_motion_notify_event_t *motion =
782                     (xcb_motion_notify_event_t *)event;
783                 xcb_point_t cursor_position = { motion->event_x, motion->event_y };
784                 xcb_poly_rectangle(conn, root_window, gc, 1, &rectangle);
785                 rectangle = rectangle_from_corners(&press_position, &cursor_position);
786                 xcb_poly_rectangle(conn, root_window, gc, 1, &rectangle);
787             }
788             break;
789         }
790         case XCB_BUTTON_RELEASE: {
791             xcb_poly_rectangle(conn, root_window, gc, 1, &rectangle);
792             done = 1;
793             break;
794         }
795         default:
796             break;
797         }
798         xcb_flush(conn);
799         free(event);
800     }
801     c->width  = rectangle.width;
802     c->height = rectangle.height;
803     if (c->width && c->height) {
804         c->x = rectangle.x;
805         c->y = rectangle.y;
806     } else {
807         c->x = 0;
808         c->y = 0;
809     }
810     xcb_ungrab_server(conn);
811     xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
812     xcb_flush(conn);
813
814 fail:
815     xcb_free_cursor(conn, cursor);
816     xcb_close_font(conn, cursor_font);
817     xcb_free_gc(conn, gc);
818     return ret;
819 }
820
821 static av_cold int xcbgrab_read_header(AVFormatContext *s)
822 {
823     XCBGrabContext *c = s->priv_data;
824     int screen_num, ret;
825     const xcb_setup_t *setup;
826     char *display_name = av_strdup(s->url);
827
828     if (!display_name)
829         return AVERROR(ENOMEM);
830
831     if (!sscanf(s->url, "%[^+]+%d,%d", display_name, &c->x, &c->y)) {
832         *display_name = 0;
833         sscanf(s->url, "+%d,%d", &c->x, &c->y);
834     }
835
836     c->conn = xcb_connect(display_name[0] ? display_name : NULL, &screen_num);
837     av_freep(&display_name);
838
839     if ((ret = xcb_connection_has_error(c->conn))) {
840         av_log(s, AV_LOG_ERROR, "Cannot open display %s, error %d.\n",
841                s->url[0] ? s->url : "default", ret);
842         return AVERROR(EIO);
843     }
844
845     setup = xcb_get_setup(c->conn);
846
847     c->screen = get_screen(setup, screen_num);
848     if (!c->screen) {
849         av_log(s, AV_LOG_ERROR, "The screen %d does not exist.\n",
850                screen_num);
851         xcbgrab_read_close(s);
852         return AVERROR(EIO);
853     }
854
855     if (c->window_id == XCB_NONE)
856         c->window_id = c->screen->root;
857     else {
858         if (c->select_region) {
859             av_log(s, AV_LOG_WARNING, "select_region ignored with window_id.\n");
860             c->select_region = 0;
861         }
862         if (c->follow_mouse) {
863             av_log(s, AV_LOG_WARNING, "follow_mouse ignored with window_id.\n");
864             c->follow_mouse = 0;
865         }
866     }
867
868     if (c->select_region) {
869         ret = select_region(s);
870         if (ret < 0) {
871             xcbgrab_read_close(s);
872             return ret;
873         }
874     }
875
876     ret = create_stream(s);
877
878     if (ret < 0) {
879         xcbgrab_read_close(s);
880         return ret;
881     }
882
883 #if CONFIG_LIBXCB_SHM
884     c->has_shm = check_shm(c->conn);
885 #endif
886
887 #if CONFIG_LIBXCB_XFIXES
888     if (c->draw_mouse) {
889         if (!(c->draw_mouse = check_xfixes(c->conn))) {
890             av_log(s, AV_LOG_WARNING,
891                    "XFixes not available, cannot draw the mouse.\n");
892         }
893         if (c->bpp < 24) {
894             avpriv_report_missing_feature(s, "%d bits per pixel screen",
895                                           c->bpp);
896             c->draw_mouse = 0;
897         }
898     }
899 #endif
900
901     if (c->show_region)
902         setup_window(s);
903
904     return 0;
905 }
906
907 AVInputFormat ff_xcbgrab_demuxer = {
908     .name           = "x11grab",
909     .long_name      = NULL_IF_CONFIG_SMALL("X11 screen capture, using XCB"),
910     .priv_data_size = sizeof(XCBGrabContext),
911     .read_header    = xcbgrab_read_header,
912     .read_packet    = xcbgrab_read_packet,
913     .read_close     = xcbgrab_read_close,
914     .flags          = AVFMT_NOFILE,
915     .priv_class     = &xcbgrab_class,
916 };