]> git.sesse.net Git - ffmpeg/blob - libavdevice/kmsgrab.c
kmsgrab: Do not require the modifier to stay constant.
[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 // Required for compatibility when building against libdrm < 2.4.83.
31 #ifndef DRM_FORMAT_MOD_INVALID
32 #define DRM_FORMAT_MOD_INVALID ((1ULL << 56) - 1)
33 #endif
34
35 #include "libavutil/hwcontext.h"
36 #include "libavutil/hwcontext_drm.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/pixfmt.h"
41 #include "libavutil/pixdesc.h"
42 #include "libavutil/time.h"
43
44 #include "libavformat/avformat.h"
45 #include "libavformat/internal.h"
46
47 typedef struct KMSGrabContext {
48     const AVClass *class;
49
50     AVBufferRef *device_ref;
51     AVHWDeviceContext *device;
52     AVDRMDeviceContext *hwctx;
53     int fb2_available;
54
55     AVBufferRef *frames_ref;
56     AVHWFramesContext *frames;
57
58     uint32_t plane_id;
59     uint32_t drm_format;
60     unsigned int width;
61     unsigned int height;
62
63     int64_t frame_delay;
64     int64_t frame_last;
65
66     const char *device_path;
67     enum AVPixelFormat format;
68     int64_t drm_format_modifier;
69     int64_t source_plane;
70     int64_t source_crtc;
71     AVRational framerate;
72 } KMSGrabContext;
73
74 static void kmsgrab_free_desc(void *opaque, uint8_t *data)
75 {
76     AVDRMFrameDescriptor *desc = (AVDRMFrameDescriptor*)data;
77     int i;
78
79     for (i = 0; i < desc->nb_objects; i++)
80         close(desc->objects[i].fd);
81
82     av_free(desc);
83 }
84
85 static void kmsgrab_free_frame(void *opaque, uint8_t *data)
86 {
87     AVFrame *frame = (AVFrame*)data;
88
89     av_frame_free(&frame);
90 }
91
92 static int kmsgrab_get_fb(AVFormatContext *avctx,
93                           drmModePlane *plane,
94                           AVDRMFrameDescriptor *desc)
95 {
96     KMSGrabContext *ctx = avctx->priv_data;
97     drmModeFB *fb = NULL;
98     int err, fd;
99
100     fb = drmModeGetFB(ctx->hwctx->fd, plane->fb_id);
101     if (!fb) {
102         err = errno;
103         av_log(avctx, AV_LOG_ERROR, "Failed to get framebuffer "
104                "%"PRIu32": %s.\n", plane->fb_id, strerror(err));
105         err = AVERROR(err);
106         goto fail;
107     }
108     if (fb->width != ctx->width || fb->height != ctx->height) {
109         av_log(avctx, AV_LOG_ERROR, "Plane %"PRIu32" framebuffer "
110                "dimensions changed: now %"PRIu32"x%"PRIu32".\n",
111                ctx->plane_id, fb->width, fb->height);
112         err = AVERROR(EIO);
113         goto fail;
114     }
115     if (!fb->handle) {
116         av_log(avctx, AV_LOG_ERROR, "No handle set on framebuffer.\n");
117         err = AVERROR(EIO);
118         goto fail;
119     }
120
121     err = drmPrimeHandleToFD(ctx->hwctx->fd, fb->handle, O_RDONLY, &fd);
122     if (err < 0) {
123         err = errno;
124         av_log(avctx, AV_LOG_ERROR, "Failed to get PRIME fd from "
125                "framebuffer handle: %s.\n", strerror(err));
126         err = AVERROR(err);
127         goto fail;
128     }
129
130     *desc = (AVDRMFrameDescriptor) {
131         .nb_objects = 1,
132         .objects[0] = {
133             .fd               = fd,
134             .size             = fb->height * fb->pitch,
135             .format_modifier  = ctx->drm_format_modifier,
136         },
137         .nb_layers = 1,
138         .layers[0] = {
139             .format           = ctx->drm_format,
140             .nb_planes        = 1,
141             .planes[0] = {
142                 .object_index = 0,
143                 .offset       = 0,
144                 .pitch        = fb->pitch,
145             },
146         },
147     };
148
149     err = 0;
150 fail:
151     drmModeFreeFB(fb);
152     return err;
153 }
154
155 #if HAVE_LIBDRM_GETFB2
156 static int kmsgrab_get_fb2(AVFormatContext *avctx,
157                            drmModePlane *plane,
158                            AVDRMFrameDescriptor *desc)
159 {
160     KMSGrabContext *ctx = avctx->priv_data;
161     drmModeFB2 *fb;
162     int err, i, nb_objects;
163     uint64_t modifier = ctx->drm_format_modifier;
164
165     fb = drmModeGetFB2(ctx->hwctx->fd, plane->fb_id);
166     if (!fb) {
167         err = errno;
168         av_log(avctx, AV_LOG_ERROR, "Failed to get framebuffer "
169                "%"PRIu32": %s.\n", plane->fb_id, strerror(err));
170         return AVERROR(err);
171     }
172     if (fb->pixel_format != ctx->drm_format) {
173         av_log(avctx, AV_LOG_ERROR, "Plane %"PRIu32" framebuffer "
174                "format changed: now %"PRIx32".\n",
175                ctx->plane_id, fb->pixel_format);
176         err = AVERROR(EIO);
177         goto fail;
178     }
179     if (fb->width != ctx->width || fb->height != ctx->height) {
180         av_log(avctx, AV_LOG_ERROR, "Plane %"PRIu32" framebuffer "
181                "dimensions changed: now %"PRIu32"x%"PRIu32".\n",
182                ctx->plane_id, fb->width, fb->height);
183         err = AVERROR(EIO);
184         goto fail;
185     }
186     if (!fb->handles[0]) {
187         av_log(avctx, AV_LOG_ERROR, "No handle set on framebuffer.\n");
188         err = AVERROR(EIO);
189         goto fail;
190     }
191
192     if (fb->flags & DRM_MODE_FB_MODIFIERS)
193         modifier = fb->modifier;
194
195     *desc = (AVDRMFrameDescriptor) {
196         .nb_layers = 1,
197         .layers[0] = {
198             .format = ctx->drm_format,
199         },
200     };
201
202     nb_objects = 0;
203     for (i = 0; i < 4 && fb->handles[i]; i++) {
204         size_t size;
205         int dup = 0, j, obj;
206
207         size = fb->offsets[i] + fb->height * fb->pitches[i];
208
209         for (j = 0; j < i; j++) {
210             if (fb->handles[i] == fb->handles[j]) {
211                 dup = 1;
212                 break;
213             }
214         }
215         if (dup) {
216             obj = desc->layers[0].planes[j].object_index;
217
218             if (desc->objects[j].size < size)
219                 desc->objects[j].size = size;
220
221             desc->layers[0].planes[i] = (AVDRMPlaneDescriptor) {
222                 .object_index = obj,
223                 .offset       = fb->offsets[i],
224                 .pitch        = fb->pitches[i],
225             };
226
227         } else {
228             int fd;
229             err = drmPrimeHandleToFD(ctx->hwctx->fd, fb->handles[i],
230                                      O_RDONLY, &fd);
231             if (err < 0) {
232                 err = errno;
233                 av_log(avctx, AV_LOG_ERROR, "Failed to get PRIME fd from "
234                        "framebuffer handle: %s.\n", strerror(err));
235                 err = AVERROR(err);
236                 goto fail;
237             }
238
239             obj = nb_objects++;
240             desc->objects[obj] = (AVDRMObjectDescriptor) {
241                 .fd              = fd,
242                 .size            = size,
243                 .format_modifier = modifier,
244             };
245             desc->layers[0].planes[i] = (AVDRMPlaneDescriptor) {
246                 .object_index = obj,
247                 .offset       = fb->offsets[i],
248                 .pitch        = fb->pitches[i],
249             };
250         }
251     }
252     desc->nb_objects = nb_objects;
253     desc->layers[0].nb_planes = i;
254
255     err = 0;
256 fail:
257     drmModeFreeFB2(fb);
258     return err;
259 }
260 #endif
261
262 static int kmsgrab_read_packet(AVFormatContext *avctx, AVPacket *pkt)
263 {
264     KMSGrabContext *ctx = avctx->priv_data;
265     drmModePlane *plane = NULL;
266     AVDRMFrameDescriptor *desc = NULL;
267     AVFrame *frame = NULL;
268     int64_t now;
269     int err;
270
271     now = av_gettime();
272     if (ctx->frame_last) {
273         int64_t delay;
274         while (1) {
275             delay = ctx->frame_last + ctx->frame_delay - now;
276             if (delay <= 0)
277                 break;
278             av_usleep(delay);
279             now = av_gettime();
280         }
281     }
282     ctx->frame_last = now;
283
284     plane = drmModeGetPlane(ctx->hwctx->fd, ctx->plane_id);
285     if (!plane) {
286         err = errno;
287         av_log(avctx, AV_LOG_ERROR, "Failed to get plane "
288                "%"PRIu32": %s.\n", ctx->plane_id, strerror(err));
289         err = AVERROR(err);
290         goto fail;
291     }
292     if (!plane->fb_id) {
293         av_log(avctx, AV_LOG_ERROR, "Plane %"PRIu32" no longer has "
294                "an associated framebuffer.\n", ctx->plane_id);
295         err = AVERROR(EIO);
296         goto fail;
297     }
298
299     desc = av_mallocz(sizeof(*desc));
300     if (!desc) {
301         err = AVERROR(ENOMEM);
302         goto fail;
303     }
304
305 #if HAVE_LIBDRM_GETFB2
306     if (ctx->fb2_available)
307         err = kmsgrab_get_fb2(avctx, plane, desc);
308     else
309 #endif
310         err = kmsgrab_get_fb(avctx, plane, desc);
311     if (err < 0)
312         goto fail;
313
314     frame = av_frame_alloc();
315     if (!frame) {
316         err = AVERROR(ENOMEM);
317         goto fail;
318     }
319
320     frame->hw_frames_ctx = av_buffer_ref(ctx->frames_ref);
321     if (!frame->hw_frames_ctx) {
322         err = AVERROR(ENOMEM);
323         goto fail;
324     }
325
326     frame->buf[0] = av_buffer_create((uint8_t*)desc, sizeof(*desc),
327                                      &kmsgrab_free_desc, avctx, 0);
328     if (!frame->buf[0]) {
329         err = AVERROR(ENOMEM);
330         goto fail;
331     }
332
333     frame->data[0] = (uint8_t*)desc;
334     frame->format  = AV_PIX_FMT_DRM_PRIME;
335     frame->width   = ctx->width;
336     frame->height  = ctx->height;
337
338     drmModeFreePlane(plane);
339     plane = NULL;
340     desc  = NULL;
341
342     pkt->buf = av_buffer_create((uint8_t*)frame, sizeof(*frame),
343                                 &kmsgrab_free_frame, avctx, 0);
344     if (!pkt->buf) {
345         err = AVERROR(ENOMEM);
346         goto fail;
347     }
348
349     pkt->data   = (uint8_t*)frame;
350     pkt->size   = sizeof(*frame);
351     pkt->pts    = now;
352     pkt->flags |= AV_PKT_FLAG_TRUSTED;
353
354     return 0;
355
356 fail:
357     drmModeFreePlane(plane);
358     av_freep(&desc);
359     av_frame_free(&frame);
360     return err;
361 }
362
363 static const struct {
364     enum AVPixelFormat pixfmt;
365     uint32_t drm_format;
366 } kmsgrab_formats[] = {
367     // Monochrome.
368 #ifdef DRM_FORMAT_R8
369     { AV_PIX_FMT_GRAY8,    DRM_FORMAT_R8       },
370 #endif
371 #ifdef DRM_FORMAT_R16
372     { AV_PIX_FMT_GRAY16LE, DRM_FORMAT_R16      },
373     { AV_PIX_FMT_GRAY16BE, DRM_FORMAT_R16      | DRM_FORMAT_BIG_ENDIAN },
374 #endif
375     // <8-bit RGB.
376     { AV_PIX_FMT_BGR8,     DRM_FORMAT_BGR233   },
377     { AV_PIX_FMT_RGB555LE, DRM_FORMAT_XRGB1555 },
378     { AV_PIX_FMT_RGB555BE, DRM_FORMAT_XRGB1555 | DRM_FORMAT_BIG_ENDIAN },
379     { AV_PIX_FMT_BGR555LE, DRM_FORMAT_XBGR1555 },
380     { AV_PIX_FMT_BGR555BE, DRM_FORMAT_XBGR1555 | DRM_FORMAT_BIG_ENDIAN },
381     { AV_PIX_FMT_RGB565LE, DRM_FORMAT_RGB565   },
382     { AV_PIX_FMT_RGB565BE, DRM_FORMAT_RGB565   | DRM_FORMAT_BIG_ENDIAN },
383     { AV_PIX_FMT_BGR565LE, DRM_FORMAT_BGR565   },
384     { AV_PIX_FMT_BGR565BE, DRM_FORMAT_BGR565   | DRM_FORMAT_BIG_ENDIAN },
385     // 8-bit RGB.
386     { AV_PIX_FMT_RGB24,    DRM_FORMAT_RGB888   },
387     { AV_PIX_FMT_BGR24,    DRM_FORMAT_BGR888   },
388     { AV_PIX_FMT_0RGB,     DRM_FORMAT_BGRX8888 },
389     { AV_PIX_FMT_0BGR,     DRM_FORMAT_RGBX8888 },
390     { AV_PIX_FMT_RGB0,     DRM_FORMAT_XBGR8888 },
391     { AV_PIX_FMT_BGR0,     DRM_FORMAT_XRGB8888 },
392     { AV_PIX_FMT_ARGB,     DRM_FORMAT_BGRA8888 },
393     { AV_PIX_FMT_ABGR,     DRM_FORMAT_RGBA8888 },
394     { AV_PIX_FMT_RGBA,     DRM_FORMAT_ABGR8888 },
395     { AV_PIX_FMT_BGRA,     DRM_FORMAT_ARGB8888 },
396     // 10-bit RGB.
397     { AV_PIX_FMT_X2RGB10LE, DRM_FORMAT_XRGB2101010 },
398     { AV_PIX_FMT_X2RGB10BE, DRM_FORMAT_XRGB2101010 | DRM_FORMAT_BIG_ENDIAN },
399     // 8-bit YUV 4:2:0.
400     { AV_PIX_FMT_NV12,     DRM_FORMAT_NV12     },
401     // 8-bit YUV 4:2:2.
402     { AV_PIX_FMT_YUYV422,  DRM_FORMAT_YUYV     },
403     { AV_PIX_FMT_YVYU422,  DRM_FORMAT_YVYU     },
404     { AV_PIX_FMT_UYVY422,  DRM_FORMAT_UYVY     },
405 };
406
407 static av_cold int kmsgrab_read_header(AVFormatContext *avctx)
408 {
409     KMSGrabContext *ctx = avctx->priv_data;
410     drmModePlaneRes *plane_res = NULL;
411     drmModePlane *plane = NULL;
412     drmModeFB *fb = NULL;
413 #if HAVE_LIBDRM_GETFB2
414     drmModeFB2 *fb2 = NULL;
415 #endif
416     AVStream *stream;
417     int err, i;
418
419     err = av_hwdevice_ctx_create(&ctx->device_ref, AV_HWDEVICE_TYPE_DRM,
420                                  ctx->device_path, NULL, 0);
421     if (err < 0) {
422         av_log(avctx, AV_LOG_ERROR, "Failed to open DRM device.\n");
423         return err;
424     }
425     ctx->device = (AVHWDeviceContext*) ctx->device_ref->data;
426     ctx->hwctx  = (AVDRMDeviceContext*)ctx->device->hwctx;
427
428     err = drmSetClientCap(ctx->hwctx->fd,
429                           DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
430     if (err < 0) {
431         av_log(avctx, AV_LOG_WARNING, "Failed to set universal planes "
432                "capability: primary planes will not be usable.\n");
433     }
434
435     if (ctx->source_plane > 0) {
436         plane = drmModeGetPlane(ctx->hwctx->fd, ctx->source_plane);
437         if (!plane) {
438             err = errno;
439             av_log(avctx, AV_LOG_ERROR, "Failed to get plane %"PRId64": "
440                    "%s.\n", ctx->source_plane, strerror(err));
441             err = AVERROR(err);
442             goto fail;
443         }
444
445         if (plane->fb_id == 0) {
446             av_log(avctx, AV_LOG_ERROR, "Plane %"PRId64" does not have "
447                    "an attached framebuffer.\n", ctx->source_plane);
448             err = AVERROR(EINVAL);
449             goto fail;
450         }
451     } else {
452         plane_res = drmModeGetPlaneResources(ctx->hwctx->fd);
453         if (!plane_res) {
454             err = errno;
455             av_log(avctx, AV_LOG_ERROR, "Failed to get plane "
456                    "resources: %s.\n", strerror(err));
457             err = AVERROR(err);
458             goto fail;
459         }
460
461         for (i = 0; i < plane_res->count_planes; i++) {
462             plane = drmModeGetPlane(ctx->hwctx->fd,
463                                     plane_res->planes[i]);
464             if (!plane) {
465                 err = errno;
466                 av_log(avctx, AV_LOG_VERBOSE, "Failed to get "
467                        "plane %"PRIu32": %s.\n",
468                        plane_res->planes[i], strerror(err));
469                 continue;
470             }
471
472             av_log(avctx, AV_LOG_DEBUG, "Plane %"PRIu32": "
473                    "CRTC %"PRIu32" FB %"PRIu32".\n",
474                    plane->plane_id, plane->crtc_id, plane->fb_id);
475
476             if ((ctx->source_crtc > 0 &&
477                  plane->crtc_id != ctx->source_crtc) ||
478                 plane->fb_id == 0) {
479                 // Either not connected to the target source CRTC
480                 // or not active.
481                 drmModeFreePlane(plane);
482                 plane = NULL;
483                 continue;
484             }
485
486             break;
487         }
488
489         if (i == plane_res->count_planes) {
490             if (ctx->source_crtc > 0) {
491                 av_log(avctx, AV_LOG_ERROR, "No usable planes found on "
492                        "CRTC %"PRId64".\n", ctx->source_crtc);
493             } else {
494                 av_log(avctx, AV_LOG_ERROR, "No usable planes found.\n");
495             }
496             err = AVERROR(EINVAL);
497             goto fail;
498         }
499
500         av_log(avctx, AV_LOG_INFO, "Using plane %"PRIu32" to "
501                "locate framebuffers.\n", plane->plane_id);
502     }
503
504     ctx->plane_id = plane->plane_id;
505
506 #if HAVE_LIBDRM_GETFB2
507     fb2 = drmModeGetFB2(ctx->hwctx->fd, plane->fb_id);
508     if (!fb2 && errno == ENOSYS) {
509         av_log(avctx, AV_LOG_INFO, "GETFB2 not supported, "
510                "will try to use GETFB instead.\n");
511     } else if (!fb2) {
512         err = errno;
513         av_log(avctx, AV_LOG_ERROR, "Failed to get "
514                "framebuffer %"PRIu32": %s.\n",
515                plane->fb_id, strerror(err));
516         err = AVERROR(err);
517         goto fail;
518     } else {
519         av_log(avctx, AV_LOG_INFO, "Template framebuffer is "
520                "%"PRIu32": %"PRIu32"x%"PRIu32" "
521                "format %"PRIx32" modifier %"PRIx64" flags %"PRIx32".\n",
522                fb2->fb_id, fb2->width, fb2->height,
523                fb2->pixel_format, fb2->modifier, fb2->flags);
524
525         ctx->width  = fb2->width;
526         ctx->height = fb2->height;
527
528         if (!fb2->handles[0]) {
529             av_log(avctx, AV_LOG_ERROR, "No handle set on framebuffer: "
530                    "maybe you need some additional capabilities?\n");
531             err = AVERROR(EINVAL);
532             goto fail;
533         }
534
535         for (i = 0; i < FF_ARRAY_ELEMS(kmsgrab_formats); i++) {
536             if (kmsgrab_formats[i].drm_format == fb2->pixel_format) {
537                 if (ctx->format != AV_PIX_FMT_NONE &&
538                     ctx->format != kmsgrab_formats[i].pixfmt) {
539                     av_log(avctx, AV_LOG_ERROR, "Framebuffer pixel format "
540                            "%"PRIx32" does not match expected format.\n",
541                            fb2->pixel_format);
542                     err = AVERROR(EINVAL);
543                     goto fail;
544                 }
545                 ctx->drm_format = fb2->pixel_format;
546                 ctx->format     = kmsgrab_formats[i].pixfmt;
547                 break;
548             }
549         }
550         if (i == FF_ARRAY_ELEMS(kmsgrab_formats)) {
551             av_log(avctx, AV_LOG_ERROR, "Framebuffer pixel format "
552                    "%"PRIx32" is not a known supported format.\n",
553                    fb2->pixel_format);
554             err = AVERROR(EINVAL);
555             goto fail;
556         }
557
558         if (fb2->flags & DRM_MODE_FB_MODIFIERS) {
559             if (ctx->drm_format_modifier != DRM_FORMAT_MOD_INVALID &&
560                 ctx->drm_format_modifier != fb2->modifier) {
561                 av_log(avctx, AV_LOG_ERROR, "Framebuffer format modifier "
562                        "%"PRIx64" does not match expected modifier.\n",
563                        fb2->modifier);
564                 err = AVERROR(EINVAL);
565                 goto fail;
566             } else {
567                 ctx->drm_format_modifier = fb2->modifier;
568             }
569         }
570         av_log(avctx, AV_LOG_VERBOSE, "Format is %s, from "
571                "DRM format %"PRIx32" modifier %"PRIx64".\n",
572                av_get_pix_fmt_name(ctx->format),
573                ctx->drm_format, ctx->drm_format_modifier);
574
575         ctx->fb2_available = 1;
576     }
577 #endif
578
579     if (!ctx->fb2_available) {
580         if (ctx->format == AV_PIX_FMT_NONE) {
581             // Backward compatibility: assume BGR0 if no format supplied.
582             ctx->format = AV_PIX_FMT_BGR0;
583         }
584         for (i = 0; i < FF_ARRAY_ELEMS(kmsgrab_formats); i++) {
585             if (kmsgrab_formats[i].pixfmt == ctx->format) {
586                 ctx->drm_format = kmsgrab_formats[i].drm_format;
587                 break;
588             }
589         }
590         if (i >= FF_ARRAY_ELEMS(kmsgrab_formats)) {
591             av_log(avctx, AV_LOG_ERROR, "Unsupported format %s.\n",
592                    av_get_pix_fmt_name(ctx->format));
593             return AVERROR(EINVAL);
594         }
595
596         fb = drmModeGetFB(ctx->hwctx->fd, plane->fb_id);
597         if (!fb) {
598             err = errno;
599             av_log(avctx, AV_LOG_ERROR, "Failed to get "
600                    "framebuffer %"PRIu32": %s.\n",
601                    plane->fb_id, strerror(err));
602             err = AVERROR(err);
603             goto fail;
604         }
605
606         av_log(avctx, AV_LOG_INFO, "Template framebuffer is %"PRIu32": "
607                "%"PRIu32"x%"PRIu32" %"PRIu32"bpp %"PRIu32"b depth.\n",
608                fb->fb_id, fb->width, fb->height, fb->bpp, fb->depth);
609
610         ctx->width  = fb->width;
611         ctx->height = fb->height;
612
613         if (!fb->handle) {
614             av_log(avctx, AV_LOG_ERROR, "No handle set on framebuffer: "
615                    "maybe you need some additional capabilities?\n");
616             err = AVERROR(EINVAL);
617             goto fail;
618         }
619     }
620
621     stream = avformat_new_stream(avctx, NULL);
622     if (!stream) {
623         err = AVERROR(ENOMEM);
624         goto fail;
625     }
626
627     stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
628     stream->codecpar->codec_id   = AV_CODEC_ID_WRAPPED_AVFRAME;
629     stream->codecpar->width      = ctx->width;
630     stream->codecpar->height     = ctx->height;
631     stream->codecpar->format     = AV_PIX_FMT_DRM_PRIME;
632
633     avpriv_set_pts_info(stream, 64, 1, 1000000);
634
635     ctx->frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
636     if (!ctx->frames_ref) {
637         err = AVERROR(ENOMEM);
638         goto fail;
639     }
640     ctx->frames = (AVHWFramesContext*)ctx->frames_ref->data;
641
642     ctx->frames->format    = AV_PIX_FMT_DRM_PRIME;
643     ctx->frames->sw_format = ctx->format,
644     ctx->frames->width     = ctx->width;
645     ctx->frames->height    = ctx->height;
646
647     err = av_hwframe_ctx_init(ctx->frames_ref);
648     if (err < 0) {
649         av_log(avctx, AV_LOG_ERROR, "Failed to initialise "
650                "hardware frames context: %d.\n", err);
651         goto fail;
652     }
653
654     ctx->frame_delay = av_rescale_q(1, (AVRational) { ctx->framerate.den,
655                 ctx->framerate.num }, AV_TIME_BASE_Q);
656
657     err = 0;
658 fail:
659     drmModeFreePlaneResources(plane_res);
660     drmModeFreePlane(plane);
661     drmModeFreeFB(fb);
662 #if HAVE_LIBDRM_GETFB2
663     drmModeFreeFB2(fb2);
664 #endif
665     return err;
666 }
667
668 static av_cold int kmsgrab_read_close(AVFormatContext *avctx)
669 {
670     KMSGrabContext *ctx = avctx->priv_data;
671
672     av_buffer_unref(&ctx->frames_ref);
673     av_buffer_unref(&ctx->device_ref);
674
675     return 0;
676 }
677
678 #define OFFSET(x) offsetof(KMSGrabContext, x)
679 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
680 static const AVOption options[] = {
681     { "device", "DRM device path",
682       OFFSET(device_path), AV_OPT_TYPE_STRING,
683       { .str = "/dev/dri/card0" }, 0, 0, FLAGS },
684     { "format", "Pixel format for framebuffer",
685       OFFSET(format), AV_OPT_TYPE_PIXEL_FMT,
686       { .i64 = AV_PIX_FMT_NONE }, -1, INT32_MAX, FLAGS },
687     { "format_modifier", "DRM format modifier for framebuffer",
688       OFFSET(drm_format_modifier), AV_OPT_TYPE_INT64,
689       { .i64 = DRM_FORMAT_MOD_INVALID }, 0, INT64_MAX, FLAGS },
690     { "crtc_id", "CRTC ID to define capture source",
691       OFFSET(source_crtc), AV_OPT_TYPE_INT64,
692       { .i64 = 0 }, 0, UINT32_MAX, FLAGS },
693     { "plane_id", "Plane ID to define capture source",
694       OFFSET(source_plane), AV_OPT_TYPE_INT64,
695       { .i64 = 0 }, 0, UINT32_MAX, FLAGS },
696     { "framerate", "Framerate to capture at",
697       OFFSET(framerate), AV_OPT_TYPE_RATIONAL,
698       { .dbl = 30.0 }, 0, 1000, FLAGS },
699     { NULL },
700 };
701
702 static const AVClass kmsgrab_class = {
703     .class_name = "kmsgrab indev",
704     .item_name  = av_default_item_name,
705     .option     = options,
706     .version    = LIBAVUTIL_VERSION_INT,
707     .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
708 };
709
710 AVInputFormat ff_kmsgrab_demuxer = {
711     .name           = "kmsgrab",
712     .long_name      = NULL_IF_CONFIG_SMALL("KMS screen capture"),
713     .priv_data_size = sizeof(KMSGrabContext),
714     .read_header    = &kmsgrab_read_header,
715     .read_packet    = &kmsgrab_read_packet,
716     .read_close     = &kmsgrab_read_close,
717     .flags          = AVFMT_NOFILE,
718     .priv_class     = &kmsgrab_class,
719 };