]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_hwmap.c
avcodec: libdav1d AV1 decoder wrapper.
[ffmpeg] / libavfilter / vf_hwmap.c
1 /*
2  * This file is part of Libav.
3  *
4  * Libav is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * Libav is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with Libav; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include "libavutil/buffer.h"
20 #include "libavutil/hwcontext.h"
21 #include "libavutil/log.h"
22 #include "libavutil/opt.h"
23 #include "libavutil/pixdesc.h"
24
25 #include "avfilter.h"
26 #include "formats.h"
27 #include "internal.h"
28 #include "video.h"
29
30 typedef struct HWMapContext {
31     const AVClass *class;
32
33     AVBufferRef   *hwframes_ref;
34
35     int            mode;
36     char          *derive_device_type;
37     int            reverse;
38 } HWMapContext;
39
40 static int hwmap_query_formats(AVFilterContext *avctx)
41 {
42     ff_formats_ref(ff_all_formats(AVMEDIA_TYPE_VIDEO),
43                    &avctx->inputs[0]->out_formats);
44     ff_formats_ref(ff_all_formats(AVMEDIA_TYPE_VIDEO),
45                    &avctx->outputs[0]->in_formats);
46     return 0;
47 }
48
49 static int hwmap_config_output(AVFilterLink *outlink)
50 {
51     AVFilterContext *avctx = outlink->src;
52     HWMapContext      *ctx = avctx->priv;
53     AVFilterLink   *inlink = avctx->inputs[0];
54     AVHWFramesContext *hwfc;
55     AVBufferRef *device;
56     const AVPixFmtDescriptor *desc;
57     int err, device_is_derived;
58
59     av_log(avctx, AV_LOG_DEBUG, "Configure hwmap %s -> %s.\n",
60            av_get_pix_fmt_name(inlink->format),
61            av_get_pix_fmt_name(outlink->format));
62
63     av_buffer_unref(&ctx->hwframes_ref);
64
65     device = avctx->hw_device_ctx;
66     device_is_derived = 0;
67
68     if (inlink->hw_frames_ctx) {
69         hwfc = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
70
71         if (ctx->derive_device_type) {
72             enum AVHWDeviceType type;
73
74             type = av_hwdevice_find_type_by_name(ctx->derive_device_type);
75             if (type == AV_HWDEVICE_TYPE_NONE) {
76                 av_log(avctx, AV_LOG_ERROR, "Invalid device type.\n");
77                 err = AVERROR(EINVAL);
78                 goto fail;
79             }
80
81             err = av_hwdevice_ctx_create_derived(&device, type,
82                                                  hwfc->device_ref, 0);
83             if (err < 0) {
84                 av_log(avctx, AV_LOG_ERROR, "Failed to created derived "
85                        "device context: %d.\n", err);
86                 goto fail;
87             }
88             device_is_derived = 1;
89         }
90
91         desc = av_pix_fmt_desc_get(outlink->format);
92         if (!desc) {
93             err = AVERROR(EINVAL);
94             goto fail;
95         }
96
97         if (inlink->format == hwfc->format &&
98             (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) &&
99             !ctx->reverse) {
100             // Map between two hardware formats (including the case of
101             // undoing an existing mapping).
102
103             if (!device) {
104                 av_log(avctx, AV_LOG_ERROR, "A device reference is "
105                        "required to map to a hardware format.\n");
106                 err = AVERROR(EINVAL);
107                 goto fail;
108             }
109
110             err = av_hwframe_ctx_create_derived(&ctx->hwframes_ref,
111                                                 outlink->format,
112                                                 device,
113                                                 inlink->hw_frames_ctx, 0);
114             if (err < 0) {
115                 av_log(avctx, AV_LOG_ERROR, "Failed to create derived "
116                        "frames context: %d.\n", err);
117                 goto fail;
118             }
119
120         } else if (inlink->format == hwfc->format &&
121                    (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) &&
122                    ctx->reverse) {
123             // Map between two hardware formats, but do it in reverse.
124             // Make a new hwframe context for the target type, and then
125             // overwrite the input hwframe context with a derived context
126             // mapped from that back to the source type.
127             AVBufferRef *source;
128             AVHWFramesContext *frames;
129
130             ctx->hwframes_ref = av_hwframe_ctx_alloc(device);
131             if (!ctx->hwframes_ref) {
132                 err = AVERROR(ENOMEM);
133                 goto fail;
134             }
135             frames = (AVHWFramesContext*)ctx->hwframes_ref->data;
136
137             frames->format    = outlink->format;
138             frames->sw_format = hwfc->sw_format;
139             frames->width     = hwfc->width;
140             frames->height    = hwfc->height;
141
142             if (avctx->extra_hw_frames >= 0)
143                 frames->initial_pool_size = 2 + avctx->extra_hw_frames;
144
145             err = av_hwframe_ctx_init(ctx->hwframes_ref);
146             if (err < 0) {
147                 av_log(avctx, AV_LOG_ERROR, "Failed to initialise "
148                        "target frames context: %d.\n", err);
149                 goto fail;
150             }
151
152             err = av_hwframe_ctx_create_derived(&source,
153                                                 inlink->format,
154                                                 hwfc->device_ref,
155                                                 ctx->hwframes_ref,
156                                                 ctx->mode);
157             if (err < 0) {
158                 av_log(avctx, AV_LOG_ERROR, "Failed to create "
159                        "derived source frames context: %d.\n", err);
160                 goto fail;
161             }
162
163             // Here is the naughty bit.  This overwriting changes what
164             // ff_get_video_buffer() in the previous filter returns -
165             // it will now give a frame allocated here mapped back to
166             // the format it expects.  If there were any additional
167             // constraints on the output frames there then this may
168             // break nastily.
169             av_buffer_unref(&inlink->hw_frames_ctx);
170             inlink->hw_frames_ctx = source;
171
172         } else if ((outlink->format == hwfc->format &&
173                     inlink->format  == hwfc->sw_format) ||
174                    inlink->format == hwfc->format) {
175             // Map from a hardware format to a software format, or
176             // undo an existing such mapping.
177
178             ctx->hwframes_ref = av_buffer_ref(inlink->hw_frames_ctx);
179             if (!ctx->hwframes_ref) {
180                 err = AVERROR(ENOMEM);
181                 goto fail;
182             }
183
184         } else {
185             // Non-matching formats - not supported.
186
187             av_log(avctx, AV_LOG_ERROR, "Unsupported formats for "
188                    "hwmap: from %s (%s) to %s.\n",
189                    av_get_pix_fmt_name(inlink->format),
190                    av_get_pix_fmt_name(hwfc->format),
191                    av_get_pix_fmt_name(outlink->format));
192             err = AVERROR(EINVAL);
193             goto fail;
194         }
195     } else if (avctx->hw_device_ctx) {
196         // Map from a software format to a hardware format.  This
197         // creates a new hwframe context like hwupload, but then
198         // returns frames mapped from that to the previous link in
199         // order to fill them without an additional copy.
200
201         if (!device) {
202             av_log(avctx, AV_LOG_ERROR, "A device reference is "
203                    "required to create new frames with reverse "
204                    "mapping.\n");
205             err = AVERROR(EINVAL);
206             goto fail;
207         }
208
209         ctx->reverse = 1;
210
211         ctx->hwframes_ref = av_hwframe_ctx_alloc(device);
212         if (!ctx->hwframes_ref) {
213             err = AVERROR(ENOMEM);
214             goto fail;
215         }
216         hwfc = (AVHWFramesContext*)ctx->hwframes_ref->data;
217
218         hwfc->format    = outlink->format;
219         hwfc->sw_format = inlink->format;
220         hwfc->width     = inlink->w;
221         hwfc->height    = inlink->h;
222
223         if (avctx->extra_hw_frames >= 0)
224             hwfc->initial_pool_size = 2 + avctx->extra_hw_frames;
225
226         err = av_hwframe_ctx_init(ctx->hwframes_ref);
227         if (err < 0) {
228             av_log(avctx, AV_LOG_ERROR, "Failed to create frame "
229                    "context for reverse mapping: %d.\n", err);
230             goto fail;
231         }
232
233     } else {
234         av_log(avctx, AV_LOG_ERROR, "Mapping requires a hardware "
235                "context (a device, or frames on input).\n");
236         return AVERROR(EINVAL);
237     }
238
239     outlink->hw_frames_ctx = av_buffer_ref(ctx->hwframes_ref);
240     if (!outlink->hw_frames_ctx) {
241         err = AVERROR(ENOMEM);
242         goto fail;
243     }
244
245     outlink->w = inlink->w;
246     outlink->h = inlink->h;
247
248     if (device_is_derived)
249         av_buffer_unref(&device);
250     return 0;
251
252 fail:
253     if (device_is_derived)
254         av_buffer_unref(&device);
255     av_buffer_unref(&ctx->hwframes_ref);
256     return err;
257 }
258
259 static AVFrame *hwmap_get_buffer(AVFilterLink *inlink, int w, int h)
260 {
261     AVFilterContext *avctx = inlink->dst;
262     AVFilterLink  *outlink = avctx->outputs[0];
263     HWMapContext      *ctx = avctx->priv;
264
265     if (ctx->reverse && !inlink->hw_frames_ctx) {
266         AVFrame *src, *dst;
267         int err;
268
269         src = ff_get_video_buffer(outlink, w, h);
270         if (!src) {
271             av_log(avctx, AV_LOG_ERROR, "Failed to allocate source "
272                    "frame for software mapping.\n");
273             return NULL;
274         }
275
276         dst = av_frame_alloc();
277         if (!dst) {
278             av_frame_free(&src);
279             return NULL;
280         }
281
282         err = av_hwframe_map(dst, src, ctx->mode);
283         if (err) {
284             av_log(avctx, AV_LOG_ERROR, "Failed to map frame to "
285                    "software: %d.\n", err);
286             av_frame_free(&src);
287             av_frame_free(&dst);
288             return NULL;
289         }
290
291         av_frame_free(&src);
292         return dst;
293     } else {
294         return ff_default_get_video_buffer(inlink, w, h);
295     }
296 }
297
298 static int hwmap_filter_frame(AVFilterLink *link, AVFrame *input)
299 {
300     AVFilterContext *avctx = link->dst;
301     AVFilterLink  *outlink = avctx->outputs[0];
302     HWMapContext      *ctx = avctx->priv;
303     AVFrame *map = NULL;
304     int err;
305
306     av_log(ctx, AV_LOG_DEBUG, "Filter input: %s, %ux%u (%"PRId64").\n",
307            av_get_pix_fmt_name(input->format),
308            input->width, input->height, input->pts);
309
310     map = av_frame_alloc();
311     if (!map) {
312         err = AVERROR(ENOMEM);
313         goto fail;
314     }
315
316     map->format = outlink->format;
317     map->hw_frames_ctx = av_buffer_ref(ctx->hwframes_ref);
318     if (!map->hw_frames_ctx) {
319         err = AVERROR(ENOMEM);
320         goto fail;
321     }
322
323     if (ctx->reverse && !input->hw_frames_ctx) {
324         // If we mapped backwards from hardware to software, we need
325         // to attach the hardware frame context to the input frame to
326         // make the mapping visible to av_hwframe_map().
327         input->hw_frames_ctx = av_buffer_ref(ctx->hwframes_ref);
328         if (!input->hw_frames_ctx) {
329             err = AVERROR(ENOMEM);
330             goto fail;
331         }
332     }
333
334     err = av_hwframe_map(map, input, ctx->mode);
335     if (err < 0) {
336         av_log(avctx, AV_LOG_ERROR, "Failed to map frame: %d.\n", err);
337         goto fail;
338     }
339
340     err = av_frame_copy_props(map, input);
341     if (err < 0)
342         goto fail;
343
344     av_frame_free(&input);
345
346     av_log(ctx, AV_LOG_DEBUG, "Filter output: %s, %ux%u (%"PRId64").\n",
347            av_get_pix_fmt_name(map->format),
348            map->width, map->height, map->pts);
349
350     return ff_filter_frame(outlink, map);
351
352 fail:
353     av_frame_free(&input);
354     av_frame_free(&map);
355     return err;
356 }
357
358 static av_cold void hwmap_uninit(AVFilterContext *avctx)
359 {
360     HWMapContext *ctx = avctx->priv;
361
362     av_buffer_unref(&ctx->hwframes_ref);
363 }
364
365 #define OFFSET(x) offsetof(HWMapContext, x)
366 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM)
367 static const AVOption hwmap_options[] = {
368     { "mode", "Frame mapping mode",
369       OFFSET(mode), AV_OPT_TYPE_FLAGS,
370       { .i64 = AV_HWFRAME_MAP_READ | AV_HWFRAME_MAP_WRITE },
371       0, INT_MAX, FLAGS, "mode" },
372
373     { "read", "Mapping should be readable",
374       0, AV_OPT_TYPE_CONST, { .i64 = AV_HWFRAME_MAP_READ },
375       INT_MIN, INT_MAX, FLAGS, "mode" },
376     { "write", "Mapping should be writeable",
377       0, AV_OPT_TYPE_CONST, { .i64 = AV_HWFRAME_MAP_WRITE },
378       INT_MIN, INT_MAX, FLAGS, "mode" },
379     { "overwrite", "Mapping will always overwrite the entire frame",
380       0, AV_OPT_TYPE_CONST, { .i64 = AV_HWFRAME_MAP_OVERWRITE },
381       INT_MIN, INT_MAX, FLAGS, "mode" },
382     { "direct", "Mapping should not involve any copying",
383       0, AV_OPT_TYPE_CONST, { .i64 = AV_HWFRAME_MAP_DIRECT },
384       INT_MIN, INT_MAX, FLAGS, "mode" },
385
386     { "derive_device", "Derive a new device of this type",
387       OFFSET(derive_device_type), AV_OPT_TYPE_STRING,
388       { .str = NULL }, 0, 0, FLAGS },
389     { "reverse", "Map in reverse (create and allocate in the sink)",
390       OFFSET(reverse), AV_OPT_TYPE_INT,
391       { .i64 = 0 }, 0, 1, FLAGS },
392
393     { NULL },
394 };
395
396 static const AVClass hwmap_class = {
397     .class_name = "hwmap",
398     .item_name  = av_default_item_name,
399     .option     = hwmap_options,
400     .version    = LIBAVUTIL_VERSION_INT,
401 };
402
403 static const AVFilterPad hwmap_inputs[] = {
404     {
405         .name             = "default",
406         .type             = AVMEDIA_TYPE_VIDEO,
407         .get_video_buffer = &hwmap_get_buffer,
408         .filter_frame     = &hwmap_filter_frame,
409     },
410     { NULL }
411 };
412
413 static const AVFilterPad hwmap_outputs[] = {
414     {
415         .name         = "default",
416         .type         = AVMEDIA_TYPE_VIDEO,
417         .config_props = &hwmap_config_output,
418     },
419     { NULL }
420 };
421
422 AVFilter ff_vf_hwmap = {
423     .name           = "hwmap",
424     .description    = NULL_IF_CONFIG_SMALL("Map hardware frames"),
425     .uninit         = &hwmap_uninit,
426     .priv_size      = sizeof(HWMapContext),
427     .priv_class     = &hwmap_class,
428     .query_formats  = &hwmap_query_formats,
429     .inputs         = hwmap_inputs,
430     .outputs        = hwmap_outputs,
431     .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
432 };