avdevice: Add missing header for NULL_IF_CONFIG_SMALL
[libav.git] / 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 Libav.
6 *
7 * Libav 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 * Libav 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 Libav; 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 <xcb/xcb.h>
26
27 #if CONFIG_LIBXCB_XFIXES
28 #include <xcb/xfixes.h>
29 #endif
30
31 #if CONFIG_LIBXCB_SHM
32 #include <sys/shm.h>
33 #include <xcb/shm.h>
34 #endif
35
36 #include "libavutil/internal.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/time.h"
41
42 #include "libavformat/avformat.h"
43 #include "libavformat/internal.h"
44
45 typedef struct XCBGrabContext {
46 const AVClass *class;
47
48 xcb_connection_t *conn;
49 xcb_screen_t *screen;
50 xcb_window_t window;
51 #if CONFIG_LIBXCB_SHM
52 xcb_shm_seg_t segment;
53 #endif
54 int64_t time_frame;
55 AVRational time_base;
56
57 int x, y;
58 int width, height;
59 int frame_size;
60 int bpp;
61
62 int draw_mouse;
63 int follow_mouse;
64 int show_region;
65 int region_border;
66 int centered;
67
68 const char *video_size;
69 const char *framerate;
70
71 int has_shm;
72 } XCBGrabContext;
73
74 #define FOLLOW_CENTER -1
75
76 #define OFFSET(x) offsetof(XCBGrabContext, x)
77 #define D AV_OPT_FLAG_DECODING_PARAM
78 static const AVOption options[] = {
79 { "x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
80 { "y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
81 { "grab_x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
82 { "grab_y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
83 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = "vga" }, 0, 0, D },
84 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc" }, 0, 0, D },
85 { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
86 { "follow_mouse", "Move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region.",
87 OFFSET(follow_mouse), AV_OPT_TYPE_INT, { .i64 = 0 }, FOLLOW_CENTER, INT_MAX, D, "follow_mouse" },
88 { "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" },
89 { "show_region", "Show the grabbing region.", OFFSET(show_region), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
90 { "region_border", "Set the region border thickness.", OFFSET(region_border), AV_OPT_TYPE_INT, { .i64 = 3 }, 1, 128, D },
91 { NULL },
92 };
93
94 static const AVClass xcbgrab_class = {
95 .class_name = "xcbgrab indev",
96 .item_name = av_default_item_name,
97 .option = options,
98 .version = LIBAVUTIL_VERSION_INT,
99 };
100
101 static int xcbgrab_reposition(AVFormatContext *s,
102 xcb_query_pointer_reply_t *p,
103 xcb_get_geometry_reply_t *geo)
104 {
105 XCBGrabContext *c = s->priv_data;
106 int x = c->x, y = c->y;
107 int w = c->width, h = c->height, f = c->follow_mouse;
108 int p_x, p_y;
109
110 if (!p || !geo)
111 return AVERROR(EIO);
112
113 p_x = p->win_x;
114 p_y = p->win_y;
115
116 if (f == FOLLOW_CENTER) {
117 x = p_x - w / 2;
118 y = p_y - h / 2;
119 } else {
120 int left = x + f;
121 int right = x + w - f;
122 int top = y + f;
123 int bottom = y + h + f;
124 if (p_x > right) {
125 x += p_x - right;
126 } else if (p_x < left) {
127 x -= left - p_x;
128 }
129 if (p_y > bottom) {
130 y += p_y - bottom;
131 } else if (p_y < top) {
132 y -= top - p_y;
133 }
134 }
135
136 c->x = FFMIN(FFMAX(0, x), geo->width - w);
137 c->y = FFMIN(FFMAX(0, y), geo->height - h);
138
139 return 0;
140 }
141
142 static int xcbgrab_frame(AVFormatContext *s, AVPacket *pkt)
143 {
144 XCBGrabContext *c = s->priv_data;
145 xcb_get_image_cookie_t iq;
146 xcb_get_image_reply_t *img;
147 xcb_drawable_t drawable = c->screen->root;
148 uint8_t *data;
149 int length, ret;
150
151 iq = xcb_get_image(c->conn, XCB_IMAGE_FORMAT_Z_PIXMAP, drawable,
152 c->x, c->y, c->width, c->height, ~0);
153
154 img = xcb_get_image_reply(c->conn, iq, NULL);
155 if (!img)
156 return AVERROR(EAGAIN);
157
158 data = xcb_get_image_data(img);
159 length = xcb_get_image_data_length(img);
160
161 ret = av_new_packet(pkt, length);
162
163 if (!ret)
164 memcpy(pkt->data, data, length);
165
166 free(img);
167
168 return ret;
169 }
170
171 static void wait_frame(AVFormatContext *s, AVPacket *pkt)
172 {
173 XCBGrabContext *c = s->priv_data;
174 int64_t curtime, delay;
175 int64_t frame_time = av_rescale_q(1, c->time_base, AV_TIME_BASE_Q);
176
177 c->time_frame += frame_time;
178
179 for (;;) {
180 curtime = av_gettime();
181 delay = c->time_frame - curtime;
182 if (delay <= 0)
183 break;
184 av_usleep(delay);
185 }
186
187 pkt->pts = curtime;
188 }
189
190 #if CONFIG_LIBXCB_SHM
191 static int check_shm(xcb_connection_t *conn)
192 {
193 xcb_shm_query_version_cookie_t cookie = xcb_shm_query_version(conn);
194 xcb_shm_query_version_reply_t *reply;
195
196 reply = xcb_shm_query_version_reply(conn, cookie, NULL);
197 if (reply) {
198 free(reply);
199 return 1;
200 }
201
202 return 0;
203 }
204
205 static void dealloc_shm(void *unused, uint8_t *data)
206 {
207 shmdt(data);
208 }
209
210 static int xcbgrab_frame_shm(AVFormatContext *s, AVPacket *pkt)
211 {
212 XCBGrabContext *c = s->priv_data;
213 xcb_shm_get_image_cookie_t iq;
214 xcb_shm_get_image_reply_t *img;
215 xcb_drawable_t drawable = c->screen->root;
216 uint8_t *data;
217 int size = c->frame_size + FF_INPUT_BUFFER_PADDING_SIZE;
218 int id = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
219 xcb_generic_error_t *e = NULL;
220
221 if (id == -1) {
222 char errbuf[1024];
223 int err = AVERROR(errno);
224 av_strerror(err, errbuf, sizeof(errbuf));
225 av_log(s, AV_LOG_ERROR, "Cannot get %d bytes of shared memory: %s.\n",
226 size, errbuf);
227 return err;
228 }
229
230 xcb_shm_attach(c->conn, c->segment, id, 0);
231
232 iq = xcb_shm_get_image(c->conn, drawable,
233 c->x, c->y, c->width, c->height, ~0,
234 XCB_IMAGE_FORMAT_Z_PIXMAP, c->segment, 0);
235
236 xcb_shm_detach(c->conn, c->segment);
237
238 img = xcb_shm_get_image_reply(c->conn, iq, &e);
239
240 xcb_flush(c->conn);
241
242 if (e) {
243 av_log(s, AV_LOG_ERROR,
244 "Cannot get the image data "
245 "event_error: response_type:%u error_code:%u "
246 "sequence:%u resource_id:%u minor_code:%u major_code:%u.\n",
247 e->response_type, e->error_code,
248 e->sequence, e->resource_id, e->minor_code, e->major_code);
249
250 shmctl(id, IPC_RMID, 0);
251 return AVERROR(EACCES);
252 }
253
254 free(img);
255
256 data = shmat(id, NULL, 0);
257 shmctl(id, IPC_RMID, 0);
258
259 if ((intptr_t)data == -1)
260 return AVERROR(errno);
261
262 pkt->buf = av_buffer_create(data, size, dealloc_shm, NULL, 0);
263 if (!pkt->buf) {
264 shmdt(data);
265 return AVERROR(ENOMEM);
266 }
267
268 pkt->data = pkt->buf->data;
269 pkt->size = c->frame_size;
270
271 return 0;
272 }
273 #endif /* CONFIG_LIBXCB_SHM */
274
275 #if CONFIG_LIBXCB_XFIXES
276 static int check_xfixes(xcb_connection_t *conn)
277 {
278 xcb_xfixes_query_version_cookie_t cookie;
279 xcb_xfixes_query_version_reply_t *reply;
280
281 cookie = xcb_xfixes_query_version(conn, XCB_XFIXES_MAJOR_VERSION,
282 XCB_XFIXES_MINOR_VERSION);
283 reply = xcb_xfixes_query_version_reply(conn, cookie, NULL);
284
285 if (reply) {
286 free(reply);
287 return 1;
288 }
289 return 0;
290 }
291
292 #define BLEND(target, source, alpha) \
293 (target) + ((source) * (255 - (alpha)) + 255 / 2) / 255
294
295 static void xcbgrab_draw_mouse(AVFormatContext *s, AVPacket *pkt,
296 xcb_query_pointer_reply_t *p,
297 xcb_get_geometry_reply_t *geo)
298 {
299 XCBGrabContext *gr = s->priv_data;
300 uint32_t *cursor;
301 uint8_t *image = pkt->data;
302 int stride = gr->bpp / 8;
303 xcb_xfixes_get_cursor_image_cookie_t cc;
304 xcb_xfixes_get_cursor_image_reply_t *ci;
305 int cx, cy, x, y, w, h, c_off, i_off;
306
307 cc = xcb_xfixes_get_cursor_image(gr->conn);
308 ci = xcb_xfixes_get_cursor_image_reply(gr->conn, cc, NULL);
309 if (!ci)
310 return;
311
312 cursor = xcb_xfixes_get_cursor_image_cursor_image(ci);
313 if (!cursor)
314 return;
315
316 cx = ci->x - ci->xhot;
317 cy = ci->y - ci->yhot;
318
319 x = FFMAX(cx, gr->x);
320 y = FFMAX(cy, gr->y);
321
322 w = FFMIN(cx + ci->width, gr->x + gr->width) - x;
323 h = FFMIN(cy + ci->height, gr->y + gr->height) - y;
324
325 c_off = x - cx;
326 i_off = x - gr->x;
327
328 cursor += (y - cy) * ci->width;
329 image += (y - gr->y) * gr->width * stride;
330
331 for (y = 0; y < h; y++) {
332 cursor += c_off;
333 image += i_off * stride;
334 for (x = 0; x < w; x++, cursor++, image += stride) {
335 int r, g, b, a;
336
337 r = *cursor & 0xff;
338 g = (*cursor >> 8) & 0xff;
339 b = (*cursor >> 16) & 0xff;
340 a = (*cursor >> 24) & 0xff;
341
342 if (!a)
343 continue;
344
345 if (a == 255) {
346 image[0] = r;
347 image[1] = g;
348 image[2] = b;
349 } else {
350 image[0] = BLEND(r, image[0], a);
351 image[1] = BLEND(g, image[1], a);
352 image[2] = BLEND(b, image[2], a);
353 }
354
355 }
356 cursor += ci->width - w - c_off;
357 image += (gr->width - w - i_off) * stride;
358 }
359
360 free(ci);
361 }
362 #endif /* CONFIG_LIBXCB_XFIXES */
363
364 static void xcbgrab_update_region(AVFormatContext *s)
365 {
366 XCBGrabContext *c = s->priv_data;
367 const uint32_t args[] = { c->x - c->region_border,
368 c->y - c->region_border };
369
370 xcb_configure_window(c->conn,
371 c->window,
372 XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y,
373 args);
374 }
375
376 static int xcbgrab_read_packet(AVFormatContext *s, AVPacket *pkt)
377 {
378 XCBGrabContext *c = s->priv_data;
379 xcb_query_pointer_cookie_t pc;
380 xcb_get_geometry_cookie_t gc;
381 xcb_query_pointer_reply_t *p = NULL;
382 xcb_get_geometry_reply_t *geo = NULL;
383 int ret = 0;
384
385 wait_frame(s, pkt);
386
387 if (c->follow_mouse || c->draw_mouse) {
388 pc = xcb_query_pointer(c->conn, c->screen->root);
389 gc = xcb_get_geometry(c->conn, c->screen->root);
390 p = xcb_query_pointer_reply(c->conn, pc, NULL);
391 geo = xcb_get_geometry_reply(c->conn, gc, NULL);
392 }
393
394 if (c->follow_mouse && p->same_screen)
395 xcbgrab_reposition(s, p, geo);
396
397 if (c->show_region)
398 xcbgrab_update_region(s);
399
400 #if CONFIG_LIBXCB_SHM
401 if (c->has_shm && xcbgrab_frame_shm(s, pkt) < 0)
402 c->has_shm = 0;
403 #endif
404 if (!c->has_shm)
405 ret = xcbgrab_frame(s, pkt);
406
407 #if CONFIG_LIBXCB_XFIXES
408 if (c->draw_mouse && p->same_screen)
409 xcbgrab_draw_mouse(s, pkt, p, geo);
410 #endif
411
412 free(p);
413 free(geo);
414
415 return ret;
416 }
417
418 static av_cold int xcbgrab_read_close(AVFormatContext *s)
419 {
420 XCBGrabContext *ctx = s->priv_data;
421
422 xcb_disconnect(ctx->conn);
423
424 return 0;
425 }
426
427 static xcb_screen_t *get_screen(const xcb_setup_t *setup, int screen_num)
428 {
429 xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup);
430 xcb_screen_t *screen = NULL;
431
432 for (; it.rem > 0; xcb_screen_next (&it)) {
433 if (!screen_num) {
434 screen = it.data;
435 break;
436 }
437
438 screen_num--;
439 }
440
441 return screen;
442 }
443
444 static int pixfmt_from_pixmap_format(AVFormatContext *s, int depth,
445 int *pix_fmt)
446 {
447 XCBGrabContext *c = s->priv_data;
448 const xcb_setup_t *setup = xcb_get_setup(c->conn);
449 const xcb_format_t *fmt = xcb_setup_pixmap_formats(setup);
450 int length = xcb_setup_pixmap_formats_length(setup);
451
452 *pix_fmt = 0;
453
454 while (length--) {
455 if (fmt->depth == depth) {
456 switch (depth) {
457 case 32:
458 if (fmt->bits_per_pixel == 32)
459 *pix_fmt = AV_PIX_FMT_ARGB;
460 break;
461 case 24:
462 if (fmt->bits_per_pixel == 32)
463 *pix_fmt = AV_PIX_FMT_RGB32;
464 else if (fmt->bits_per_pixel == 24)
465 *pix_fmt = AV_PIX_FMT_RGB24;
466 break;
467 case 16:
468 if (fmt->bits_per_pixel == 16)
469 *pix_fmt = AV_PIX_FMT_RGB565;
470 break;
471 case 15:
472 if (fmt->bits_per_pixel == 16)
473 *pix_fmt = AV_PIX_FMT_RGB555;
474 break;
475 case 8:
476 if (fmt->bits_per_pixel == 8)
477 *pix_fmt = AV_PIX_FMT_RGB8;
478 break;
479 }
480 }
481
482 if (*pix_fmt) {
483 c->bpp = fmt->bits_per_pixel;
484 c->frame_size = c->width * c->height * fmt->bits_per_pixel / 8;
485 return 0;
486 }
487
488 fmt++;
489 }
490 av_log(s, AV_LOG_ERROR, "Pixmap format not mappable.\n");
491
492 return AVERROR_PATCHWELCOME;
493 }
494
495 static int create_stream(AVFormatContext *s)
496 {
497 XCBGrabContext *c = s->priv_data;
498 AVStream *st = avformat_new_stream(s, NULL);
499 xcb_get_geometry_cookie_t gc;
500 xcb_get_geometry_reply_t *geo;
501 int ret;
502
503 if (!st)
504 return AVERROR(ENOMEM);
505
506 ret = av_parse_video_size(&c->width, &c->height, c->video_size);
507 if (ret < 0)
508 return ret;
509
510 ret = av_parse_video_rate(&st->avg_frame_rate, c->framerate);
511 if (ret < 0)
512 return ret;
513
514 avpriv_set_pts_info(st, 64, 1, 1000000);
515
516 gc = xcb_get_geometry(c->conn, c->screen->root);
517 geo = xcb_get_geometry_reply(c->conn, gc, NULL);
518
519 c->width = FFMIN(geo->width, c->width);
520 c->height = FFMIN(geo->height, c->height);
521 c->time_base = (AVRational){ st->avg_frame_rate.den,
522 st->avg_frame_rate.num };
523 c->time_frame = av_gettime();
524
525 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
526 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
527 st->codec->width = c->width;
528 st->codec->height = c->height;
529 st->codec->time_base = c->time_base;
530
531 ret = pixfmt_from_pixmap_format(s, geo->depth, &st->codec->pix_fmt);
532
533 free(geo);
534
535 return ret;
536 }
537
538 static void draw_rectangle(AVFormatContext *s)
539 {
540 XCBGrabContext *c = s->priv_data;
541 xcb_gcontext_t gc = xcb_generate_id(c->conn);
542 uint32_t mask = XCB_GC_FOREGROUND |
543 XCB_GC_BACKGROUND |
544 XCB_GC_LINE_WIDTH |
545 XCB_GC_LINE_STYLE |
546 XCB_GC_FILL_STYLE;
547 uint32_t values[] = { c->screen->black_pixel,
548 c->screen->white_pixel,
549 c->region_border,
550 XCB_LINE_STYLE_DOUBLE_DASH,
551 XCB_FILL_STYLE_SOLID };
552 xcb_rectangle_t r = { 1, 1,
553 c->width + c->region_border * 2 - 3,
554 c->height + c->region_border * 2 - 3 };
555
556 xcb_create_gc(c->conn, gc, c->window, mask, values);
557
558 xcb_poly_rectangle(c->conn, c->window, gc, 1, &r);
559 }
560
561 static void setup_window(AVFormatContext *s)
562 {
563 XCBGrabContext *c = s->priv_data;
564 uint32_t mask = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
565 uint32_t values[] = { 1,
566 XCB_EVENT_MASK_EXPOSURE |
567 XCB_EVENT_MASK_STRUCTURE_NOTIFY };
568 xcb_rectangle_t rect = { 0, 0, c->width, c->height };
569
570 c->window = xcb_generate_id(c->conn);
571
572 xcb_create_window(c->conn, XCB_COPY_FROM_PARENT,
573 c->window,
574 c->screen->root,
575 c->x - c->region_border,
576 c->y - c->region_border,
577 c->width + c->region_border * 2,
578 c->height + c->region_border * 2,
579 0,
580 XCB_WINDOW_CLASS_INPUT_OUTPUT,
581 XCB_COPY_FROM_PARENT,
582 mask, values);
583
584 xcb_shape_rectangles(c->conn, XCB_SHAPE_SO_SUBTRACT,
585 XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
586 c->window,
587 c->region_border, c->region_border,
588 1, &rect);
589
590 xcb_map_window(c->conn, c->window);
591
592 draw_rectangle(s);
593 }
594
595 static av_cold int xcbgrab_read_header(AVFormatContext *s)
596 {
597 XCBGrabContext *c = s->priv_data;
598 int screen_num, ret;
599 const xcb_setup_t *setup;
600 char *host = s->filename[0] ? s->filename : NULL;
601 const char *opts = strchr(s->filename, '+');
602
603 if (opts) {
604 sscanf(opts, "%d,%d", &c->x, &c->y);
605 host = av_strdup(s->filename);
606 if (!host)
607 return AVERROR(ENOMEM);
608 host[opts - s->filename] = '\0';
609 }
610
611 c->conn = xcb_connect(host, &screen_num);
612
613 if ((ret = xcb_connection_has_error(c->conn))) {
614 av_log(s, AV_LOG_ERROR, "Cannot open display %s, error %d.\n",
615 s->filename[0] ? host : "default", ret);
616 if (opts)
617 av_freep(&host);
618 return AVERROR(EIO);
619 }
620
621 if (opts)
622 av_freep(&host);
623
624 setup = xcb_get_setup(c->conn);
625
626 c->screen = get_screen(setup, screen_num);
627 if (!c->screen) {
628 av_log(s, AV_LOG_ERROR, "The screen %d does not exist.\n",
629 screen_num);
630 xcbgrab_read_close(s);
631 return AVERROR(EIO);
632 }
633
634 ret = create_stream(s);
635
636 if (ret < 0) {
637 xcbgrab_read_close(s);
638 return ret;
639 }
640
641 #if CONFIG_LIBXCB_SHM
642 if ((c->has_shm = check_shm(c->conn)))
643 c->segment = xcb_generate_id(c->conn);
644 #endif
645
646 #if CONFIG_LIBXCB_XFIXES
647 if (c->draw_mouse) {
648 if (!(c->draw_mouse = check_xfixes(c->conn))) {
649 av_log(s, AV_LOG_WARNING,
650 "XFixes not available, cannot draw the mouse.\n");
651 }
652 if (c->bpp < 24) {
653 avpriv_report_missing_feature(s, "%d bits per pixel screen",
654 c->bpp);
655 c->draw_mouse = 0;
656 }
657 }
658 #endif
659
660 if (c->show_region)
661 setup_window(s);
662
663 return 0;
664 }
665
666 AVInputFormat ff_x11grab_xcb_demuxer = {
667 .name = "x11grab",
668 .long_name = NULL_IF_CONFIG_SMALL("X11 screen capture, using XCB"),
669 .priv_data_size = sizeof(XCBGrabContext),
670 .read_header = xcbgrab_read_header,
671 .read_packet = xcbgrab_read_packet,
672 .read_close = xcbgrab_read_close,
673 .flags = AVFMT_NOFILE,
674 .priv_class = &xcbgrab_class,
675 };