Browse code

lavd: Add KMS screen grabber

Mark Thompson authored on 2017/09/03 02:14:27
Showing 6 changed files
... ...
@@ -47,6 +47,7 @@ version <next>:
47 47
 - SUP/PGS subtitle muxer
48 48
 - convolve video filter
49 49
 - VP9 tile threading support
50
+- KMS screen grabber
50 51
 
51 52
 version 3.3:
52 53
 - CrystalHD decoder moved to new decode API
... ...
@@ -3050,6 +3050,7 @@ gdigrab_indev_select="bmp_decoder"
3050 3050
 iec61883_indev_deps="libiec61883"
3051 3051
 jack_indev_deps="jack"
3052 3052
 jack_indev_deps_any="sem_timedwait dispatch_dispatch_h"
3053
+kmsgrab_indev_deps="libdrm"
3053 3054
 lavfi_indev_deps="avfilter"
3054 3055
 libcdio_indev_deps="libcdio"
3055 3056
 libdc1394_indev_deps="libdc1394"
... ...
@@ -32,6 +32,7 @@ OBJS-$(CONFIG_FBDEV_OUTDEV)              += fbdev_enc.o \
32 32
 OBJS-$(CONFIG_GDIGRAB_INDEV)             += gdigrab.o
33 33
 OBJS-$(CONFIG_IEC61883_INDEV)            += iec61883.o
34 34
 OBJS-$(CONFIG_JACK_INDEV)                += jack.o timefilter.o
35
+OBJS-$(CONFIG_KMSGRAB_INDEV)             += kmsgrab.o
35 36
 OBJS-$(CONFIG_LAVFI_INDEV)               += lavfi.o
36 37
 OBJS-$(CONFIG_OPENAL_INDEV)              += openal-dec.o
37 38
 OBJS-$(CONFIG_OPENGL_OUTDEV)             += opengl_enc.o
... ...
@@ -53,6 +53,7 @@ static void register_all(void)
53 53
     REGISTER_INDEV   (GDIGRAB,          gdigrab);
54 54
     REGISTER_INDEV   (IEC61883,         iec61883);
55 55
     REGISTER_INDEV   (JACK,             jack);
56
+    REGISTER_INDEV   (KMSGRAB,          kmsgrab);
56 57
     REGISTER_INDEV   (LAVFI,            lavfi);
57 58
     REGISTER_INDEV   (OPENAL,           openal);
58 59
     REGISTER_OUTDEV  (OPENGL,           opengl);
59 60
new file mode 100644
... ...
@@ -0,0 +1,455 @@
0
+/*
1
+ * KMS/DRM input device
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include <fcntl.h>
21
+#include <unistd.h>
22
+
23
+#include <drm.h>
24
+#include <drm_fourcc.h>
25
+#include <drm_mode.h>
26
+#include <xf86drm.h>
27
+#include <xf86drmMode.h>
28
+
29
+#include "libavutil/hwcontext.h"
30
+#include "libavutil/hwcontext_drm.h"
31
+#include "libavutil/internal.h"
32
+#include "libavutil/mathematics.h"
33
+#include "libavutil/opt.h"
34
+#include "libavutil/pixfmt.h"
35
+#include "libavutil/pixdesc.h"
36
+#include "libavutil/time.h"
37
+
38
+#include "libavformat/avformat.h"
39
+#include "libavformat/internal.h"
40
+
41
+typedef struct KMSGrabContext {
42
+    const AVClass *class;
43
+
44
+    AVBufferRef *device_ref;
45
+    AVHWDeviceContext *device;
46
+    AVDRMDeviceContext *hwctx;
47
+
48
+    AVBufferRef *frames_ref;
49
+    AVHWFramesContext *frames;
50
+
51
+    uint32_t plane_id;
52
+    uint32_t drm_format;
53
+    unsigned int width;
54
+    unsigned int height;
55
+
56
+    int64_t frame_delay;
57
+    int64_t frame_last;
58
+
59
+    const char *device_path;
60
+    enum AVPixelFormat format;
61
+    int64_t drm_format_modifier;
62
+    int64_t source_plane;
63
+    int64_t source_crtc;
64
+    AVRational framerate;
65
+} KMSGrabContext;
66
+
67
+static void kmsgrab_free_desc(void *opaque, uint8_t *data)
68
+{
69
+    AVDRMFrameDescriptor *desc = (AVDRMFrameDescriptor*)data;
70
+
71
+    close(desc->objects[0].fd);
72
+
73
+    av_free(desc);
74
+}
75
+
76
+static void kmsgrab_free_frame(void *opaque, uint8_t *data)
77
+{
78
+    AVFrame *frame = (AVFrame*)data;
79
+
80
+    av_frame_free(&frame);
81
+}
82
+
83
+static int kmsgrab_read_packet(AVFormatContext *avctx, AVPacket *pkt)
84
+{
85
+    KMSGrabContext *ctx = avctx->priv_data;
86
+    drmModePlane *plane;
87
+    drmModeFB *fb;
88
+    AVDRMFrameDescriptor *desc;
89
+    AVFrame *frame;
90
+    int64_t now;
91
+    int err, fd;
92
+
93
+    now = av_gettime();
94
+    if (ctx->frame_last) {
95
+        int64_t delay;
96
+        while (1) {
97
+            delay = ctx->frame_last + ctx->frame_delay - now;
98
+            if (delay <= 0)
99
+                break;
100
+            av_usleep(delay);
101
+            now = av_gettime();
102
+        }
103
+    }
104
+    ctx->frame_last = now;
105
+
106
+    plane = drmModeGetPlane(ctx->hwctx->fd, ctx->plane_id);
107
+    if (!plane) {
108
+        av_log(avctx, AV_LOG_ERROR, "Failed to get plane "
109
+               "%"PRIu32".\n", ctx->plane_id);
110
+        return AVERROR(EIO);
111
+    }
112
+    if (!plane->fb_id) {
113
+        av_log(avctx, AV_LOG_ERROR, "Plane %"PRIu32" no longer has "
114
+               "an associated framebuffer.\n", ctx->plane_id);
115
+        return AVERROR(EIO);
116
+    }
117
+
118
+    fb = drmModeGetFB(ctx->hwctx->fd, plane->fb_id);
119
+    if (!fb) {
120
+        av_log(avctx, AV_LOG_ERROR, "Failed to get framebuffer "
121
+               "%"PRIu32".\n", plane->fb_id);
122
+        return AVERROR(EIO);
123
+    }
124
+    if (fb->width != ctx->width || fb->height != ctx->height) {
125
+        av_log(avctx, AV_LOG_ERROR, "Plane %"PRIu32" framebuffer "
126
+               "dimensions changed: now %"PRIu32"x%"PRIu32".\n",
127
+               ctx->plane_id, fb->width, fb->height);
128
+        return AVERROR(EIO);
129
+    }
130
+    if (!fb->handle) {
131
+        av_log(avctx, AV_LOG_ERROR, "No handle set on framebuffer.\n");
132
+        return AVERROR(EIO);
133
+    }
134
+
135
+    err = drmPrimeHandleToFD(ctx->hwctx->fd, fb->handle, O_RDONLY, &fd);
136
+    if (err < 0) {
137
+        err = errno;
138
+        av_log(avctx, AV_LOG_ERROR, "Failed to get PRIME fd from "
139
+               "framebuffer handle: %s.\n", strerror(errno));
140
+        return AVERROR(err);
141
+    }
142
+
143
+    desc = av_mallocz(sizeof(*desc));
144
+    if (!desc)
145
+        return AVERROR(ENOMEM);
146
+
147
+    *desc = (AVDRMFrameDescriptor) {
148
+        .nb_objects = 1,
149
+        .objects[0] = {
150
+            .fd               = fd,
151
+            .size             = fb->height * fb->pitch,
152
+            .format_modifier  = ctx->drm_format_modifier,
153
+        },
154
+        .nb_layers = 1,
155
+        .layers[0] = {
156
+            .format           = ctx->drm_format,
157
+            .nb_planes        = 1,
158
+            .planes[0] = {
159
+                .object_index = 0,
160
+                .offset       = 0,
161
+                .pitch        = fb->pitch,
162
+            },
163
+        },
164
+    };
165
+
166
+    frame = av_frame_alloc();
167
+    if (!frame)
168
+        return AVERROR(ENOMEM);
169
+
170
+    frame->hw_frames_ctx = av_buffer_ref(ctx->frames_ref);
171
+    if (!frame->hw_frames_ctx)
172
+        return AVERROR(ENOMEM);
173
+
174
+    frame->buf[0] = av_buffer_create((uint8_t*)desc, sizeof(*desc),
175
+                                     &kmsgrab_free_desc, avctx, 0);
176
+    if (!frame->buf[0])
177
+        return AVERROR(ENOMEM);
178
+
179
+    frame->data[0] = (uint8_t*)desc;
180
+    frame->format  = AV_PIX_FMT_DRM_PRIME;
181
+    frame->width   = fb->width;
182
+    frame->height  = fb->height;
183
+
184
+    drmModeFreeFB(fb);
185
+    drmModeFreePlane(plane);
186
+
187
+    pkt->buf = av_buffer_create((uint8_t*)frame, sizeof(*frame),
188
+                                &kmsgrab_free_frame, avctx, 0);
189
+    if (!pkt->buf)
190
+        return AVERROR(ENOMEM);
191
+
192
+    pkt->data  = (uint8_t*)frame;
193
+    pkt->size  = sizeof(*frame);
194
+    pkt->pts   = now;
195
+    pkt->flags = AV_PKT_FLAG_TRUSTED;
196
+
197
+    return 0;
198
+}
199
+
200
+static const struct {
201
+    enum AVPixelFormat pixfmt;
202
+    uint32_t drm_format;
203
+} kmsgrab_formats[] = {
204
+    { AV_PIX_FMT_GRAY8,    DRM_FORMAT_R8       },
205
+    { AV_PIX_FMT_GRAY16LE, DRM_FORMAT_R16      },
206
+    { AV_PIX_FMT_RGB24,    DRM_FORMAT_RGB888   },
207
+    { AV_PIX_FMT_BGR24,    DRM_FORMAT_BGR888   },
208
+    { AV_PIX_FMT_0RGB,     DRM_FORMAT_XRGB8888 },
209
+    { AV_PIX_FMT_0BGR,     DRM_FORMAT_XBGR8888 },
210
+    { AV_PIX_FMT_RGB0,     DRM_FORMAT_RGBX8888 },
211
+    { AV_PIX_FMT_BGR0,     DRM_FORMAT_BGRX8888 },
212
+    { AV_PIX_FMT_ARGB,     DRM_FORMAT_ARGB8888 },
213
+    { AV_PIX_FMT_ABGR,     DRM_FORMAT_ABGR8888 },
214
+    { AV_PIX_FMT_RGBA,     DRM_FORMAT_RGBA8888 },
215
+    { AV_PIX_FMT_BGRA,     DRM_FORMAT_BGRA8888 },
216
+    { AV_PIX_FMT_YUYV422,  DRM_FORMAT_YUYV     },
217
+    { AV_PIX_FMT_YVYU422,  DRM_FORMAT_YVYU     },
218
+    { AV_PIX_FMT_UYVY422,  DRM_FORMAT_UYVY     },
219
+    { AV_PIX_FMT_NV12,     DRM_FORMAT_NV12     },
220
+    { AV_PIX_FMT_YUV420P,  DRM_FORMAT_YUV420   },
221
+    { AV_PIX_FMT_YUV422P,  DRM_FORMAT_YUV422   },
222
+    { AV_PIX_FMT_YUV444P,  DRM_FORMAT_YUV444   },
223
+};
224
+
225
+static av_cold int kmsgrab_read_header(AVFormatContext *avctx)
226
+{
227
+    KMSGrabContext *ctx = avctx->priv_data;
228
+    drmModePlaneRes *plane_res = NULL;
229
+    drmModePlane *plane = NULL;
230
+    drmModeFB *fb = NULL;
231
+    AVStream *stream;
232
+    int err, i;
233
+
234
+    for (i = 0; i < FF_ARRAY_ELEMS(kmsgrab_formats); i++) {
235
+        if (kmsgrab_formats[i].pixfmt == ctx->format) {
236
+            ctx->drm_format = kmsgrab_formats[i].drm_format;
237
+            break;
238
+        }
239
+    }
240
+    if (i >= FF_ARRAY_ELEMS(kmsgrab_formats)) {
241
+        av_log(avctx, AV_LOG_ERROR, "Unsupported format %s.\n",
242
+               av_get_pix_fmt_name(ctx->format));
243
+        return AVERROR(EINVAL);
244
+    }
245
+
246
+    err = av_hwdevice_ctx_create(&ctx->device_ref, AV_HWDEVICE_TYPE_DRM,
247
+                                 ctx->device_path, NULL, 0);
248
+    if (err < 0) {
249
+        av_log(avctx, AV_LOG_ERROR, "Failed to open DRM device.\n");
250
+        return err;
251
+    }
252
+    ctx->device = (AVHWDeviceContext*) ctx->device_ref->data;
253
+    ctx->hwctx  = (AVDRMDeviceContext*)ctx->device->hwctx;
254
+
255
+    err = drmSetClientCap(ctx->hwctx->fd,
256
+                          DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
257
+    if (err < 0) {
258
+        av_log(avctx, AV_LOG_WARNING, "Failed to set universal planes "
259
+               "capability: primary planes will not be usable.\n");
260
+    }
261
+
262
+    if (ctx->source_plane > 0) {
263
+        plane = drmModeGetPlane(ctx->hwctx->fd, ctx->source_plane);
264
+        if (!plane) {
265
+            err = errno;
266
+            av_log(avctx, AV_LOG_ERROR, "Failed to get plane %"PRId64": "
267
+                   "%s.\n", ctx->source_plane, strerror(err));
268
+            err = AVERROR(err);
269
+            goto fail;
270
+        }
271
+
272
+        if (plane->fb_id == 0) {
273
+            av_log(avctx, AV_LOG_ERROR, "Plane %"PRId64" does not have "
274
+                   "an attached framebuffer.\n", ctx->source_plane);
275
+            err = AVERROR(EINVAL);
276
+            goto fail;
277
+        }
278
+    } else {
279
+        plane_res = drmModeGetPlaneResources(ctx->hwctx->fd);
280
+        if (!plane_res) {
281
+            av_log(avctx, AV_LOG_ERROR, "Failed to get plane "
282
+                   "resources: %s.\n", strerror(errno));
283
+            err = AVERROR(EINVAL);
284
+            goto fail;
285
+        }
286
+
287
+        for (i = 0; i < plane_res->count_planes; i++) {
288
+            plane = drmModeGetPlane(ctx->hwctx->fd,
289
+                                    plane_res->planes[i]);
290
+            if (!plane) {
291
+                err = errno;
292
+                av_log(avctx, AV_LOG_VERBOSE, "Failed to get "
293
+                       "plane %"PRIu32": %s.\n",
294
+                       plane_res->planes[i], strerror(err));
295
+                continue;
296
+            }
297
+
298
+            av_log(avctx, AV_LOG_DEBUG, "Plane %"PRIu32": "
299
+                   "CRTC %"PRIu32" FB %"PRIu32".\n",
300
+                   plane->plane_id, plane->crtc_id, plane->fb_id);
301
+
302
+            if ((ctx->source_crtc > 0 &&
303
+                 plane->crtc_id != ctx->source_crtc) ||
304
+                plane->fb_id == 0) {
305
+                // Either not connected to the target source CRTC
306
+                // or not active.
307
+                drmModeFreePlane(plane);
308
+                plane = NULL;
309
+                continue;
310
+            }
311
+
312
+            break;
313
+        }
314
+
315
+        if (i == plane_res->count_planes) {
316
+            if (ctx->source_crtc > 0) {
317
+                av_log(avctx, AV_LOG_ERROR, "No usable planes found on "
318
+                       "CRTC %"PRId64".\n", ctx->source_crtc);
319
+            } else {
320
+                av_log(avctx, AV_LOG_ERROR, "No usable planes found.\n");
321
+            }
322
+            err = AVERROR(EINVAL);
323
+            goto fail;
324
+        }
325
+
326
+        av_log(avctx, AV_LOG_INFO, "Using plane %"PRIu32" to "
327
+               "locate framebuffers.\n", plane->plane_id);
328
+    }
329
+
330
+    ctx->plane_id = plane->plane_id;
331
+
332
+    fb = drmModeGetFB(ctx->hwctx->fd, plane->fb_id);
333
+    if (!fb) {
334
+        err = errno;
335
+        av_log(avctx, AV_LOG_ERROR, "Failed to get "
336
+               "framebuffer %"PRIu32": %s.\n",
337
+               plane->fb_id, strerror(err));
338
+        err = AVERROR(err);
339
+        goto fail;
340
+    }
341
+
342
+    av_log(avctx, AV_LOG_INFO, "Template framebuffer is %"PRIu32": "
343
+           "%"PRIu32"x%"PRIu32" %"PRIu32"bpp %"PRIu32"b depth.\n",
344
+           fb->fb_id, fb->width, fb->height, fb->bpp, fb->depth);
345
+
346
+    ctx->width  = fb->width;
347
+    ctx->height = fb->height;
348
+
349
+    if (!fb->handle) {
350
+        av_log(avctx, AV_LOG_ERROR, "No handle set on framebuffer: "
351
+               "maybe you need some additional capabilities?\n");
352
+        err = AVERROR(EINVAL);
353
+        goto fail;
354
+    }
355
+
356
+    stream = avformat_new_stream(avctx, NULL);
357
+    if (!stream) {
358
+        err = AVERROR(ENOMEM);
359
+        goto fail;
360
+    }
361
+
362
+    stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
363
+    stream->codecpar->codec_id   = AV_CODEC_ID_WRAPPED_AVFRAME;
364
+    stream->codecpar->width      = fb->width;
365
+    stream->codecpar->height     = fb->height;
366
+    stream->codecpar->format     = AV_PIX_FMT_DRM_PRIME;
367
+
368
+    avpriv_set_pts_info(stream, 64, 1, 1000000);
369
+
370
+    ctx->frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
371
+    if (!ctx->frames_ref) {
372
+        err = AVERROR(ENOMEM);
373
+        goto fail;
374
+    }
375
+    ctx->frames = (AVHWFramesContext*)ctx->frames_ref->data;
376
+
377
+    ctx->frames->format    = AV_PIX_FMT_DRM_PRIME;
378
+    ctx->frames->sw_format = ctx->format,
379
+    ctx->frames->width     = fb->width;
380
+    ctx->frames->height    = fb->height;
381
+
382
+    err = av_hwframe_ctx_init(ctx->frames_ref);
383
+    if (err < 0) {
384
+        av_log(avctx, AV_LOG_ERROR, "Failed to initialise "
385
+               "hardware frames context: %d.\n", err);
386
+        goto fail;
387
+    }
388
+
389
+    ctx->frame_delay = av_rescale_q(1, (AVRational) { ctx->framerate.den,
390
+                ctx->framerate.num }, AV_TIME_BASE_Q);
391
+
392
+    err = 0;
393
+fail:
394
+    if (plane_res)
395
+        drmModeFreePlaneResources(plane_res);
396
+    if (plane)
397
+        drmModeFreePlane(plane);
398
+    if (fb)
399
+        drmModeFreeFB(fb);
400
+
401
+    return err;
402
+}
403
+
404
+static av_cold int kmsgrab_read_close(AVFormatContext *avctx)
405
+{
406
+    KMSGrabContext *ctx = avctx->priv_data;
407
+
408
+    av_buffer_unref(&ctx->frames_ref);
409
+    av_buffer_unref(&ctx->device_ref);
410
+
411
+    return 0;
412
+}
413
+
414
+#define OFFSET(x) offsetof(KMSGrabContext, x)
415
+#define FLAGS AV_OPT_FLAG_DECODING_PARAM
416
+static const AVOption options[] = {
417
+    { "device", "DRM device path",
418
+      OFFSET(device_path), AV_OPT_TYPE_STRING,
419
+      { .str = "/dev/dri/card0" }, 0, 0, FLAGS },
420
+    { "format", "Pixel format for framebuffer",
421
+      OFFSET(format), AV_OPT_TYPE_PIXEL_FMT,
422
+      { .i64 = AV_PIX_FMT_BGR0 }, 0, UINT32_MAX, FLAGS },
423
+    { "format_modifier", "DRM format modifier for framebuffer",
424
+      OFFSET(drm_format_modifier), AV_OPT_TYPE_INT64,
425
+      { .i64 = DRM_FORMAT_MOD_NONE }, 0, INT64_MAX, FLAGS },
426
+    { "crtc_id", "CRTC ID to define capture source",
427
+      OFFSET(source_crtc), AV_OPT_TYPE_INT64,
428
+      { .i64 = 0 }, 0, UINT32_MAX, FLAGS },
429
+    { "plane_id", "Plane ID to define capture source",
430
+      OFFSET(source_plane), AV_OPT_TYPE_INT64,
431
+      { .i64 = 0 }, 0, UINT32_MAX, FLAGS },
432
+    { "framerate", "Framerate to capture at",
433
+      OFFSET(framerate), AV_OPT_TYPE_RATIONAL,
434
+      { .dbl = 30.0 }, 0, 1000, FLAGS },
435
+    { NULL },
436
+};
437
+
438
+static const AVClass kmsgrab_class = {
439
+    .class_name = "kmsgrab indev",
440
+    .item_name  = av_default_item_name,
441
+    .option     = options,
442
+    .version    = LIBAVUTIL_VERSION_INT,
443
+};
444
+
445
+AVInputFormat ff_kmsgrab_demuxer = {
446
+    .name           = "kmsgrab",
447
+    .long_name      = NULL_IF_CONFIG_SMALL("KMS screen capture"),
448
+    .priv_data_size = sizeof(KMSGrabContext),
449
+    .read_header    = &kmsgrab_read_header,
450
+    .read_packet    = &kmsgrab_read_packet,
451
+    .read_close     = &kmsgrab_read_close,
452
+    .flags          = AVFMT_NOFILE,
453
+    .priv_class     = &kmsgrab_class,
454
+};
... ...
@@ -29,7 +29,7 @@
29 29
 
30 30
 #define LIBAVDEVICE_VERSION_MAJOR  57
31 31
 #define LIBAVDEVICE_VERSION_MINOR   8
32
-#define LIBAVDEVICE_VERSION_MICRO 100
32
+#define LIBAVDEVICE_VERSION_MICRO 101
33 33
 
34 34
 #define LIBAVDEVICE_VERSION_INT AV_VERSION_INT(LIBAVDEVICE_VERSION_MAJOR, \
35 35
                                                LIBAVDEVICE_VERSION_MINOR, \