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