]> git.sesse.net Git - ffmpeg/blob - libavutil/hwcontext.c
lavu/hwcontext: Add support for HW -> HW transfers
[ffmpeg] / libavutil / hwcontext.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include "config.h"
20
21 #include "buffer.h"
22 #include "common.h"
23 #include "hwcontext.h"
24 #include "hwcontext_internal.h"
25 #include "imgutils.h"
26 #include "log.h"
27 #include "mem.h"
28 #include "pixdesc.h"
29 #include "pixfmt.h"
30
31 static const HWContextType * const hw_table[] = {
32 #if CONFIG_CUDA
33     &ff_hwcontext_type_cuda,
34 #endif
35 #if CONFIG_D3D11VA
36     &ff_hwcontext_type_d3d11va,
37 #endif
38 #if CONFIG_LIBDRM
39     &ff_hwcontext_type_drm,
40 #endif
41 #if CONFIG_DXVA2
42     &ff_hwcontext_type_dxva2,
43 #endif
44 #if CONFIG_OPENCL
45     &ff_hwcontext_type_opencl,
46 #endif
47 #if CONFIG_QSV
48     &ff_hwcontext_type_qsv,
49 #endif
50 #if CONFIG_VAAPI
51     &ff_hwcontext_type_vaapi,
52 #endif
53 #if CONFIG_VDPAU
54     &ff_hwcontext_type_vdpau,
55 #endif
56 #if CONFIG_VIDEOTOOLBOX
57     &ff_hwcontext_type_videotoolbox,
58 #endif
59 #if CONFIG_MEDIACODEC
60     &ff_hwcontext_type_mediacodec,
61 #endif
62     NULL,
63 };
64
65 static const char *const hw_type_names[] = {
66     [AV_HWDEVICE_TYPE_CUDA]   = "cuda",
67     [AV_HWDEVICE_TYPE_DRM]    = "drm",
68     [AV_HWDEVICE_TYPE_DXVA2]  = "dxva2",
69     [AV_HWDEVICE_TYPE_D3D11VA] = "d3d11va",
70     [AV_HWDEVICE_TYPE_OPENCL] = "opencl",
71     [AV_HWDEVICE_TYPE_QSV]    = "qsv",
72     [AV_HWDEVICE_TYPE_VAAPI]  = "vaapi",
73     [AV_HWDEVICE_TYPE_VDPAU]  = "vdpau",
74     [AV_HWDEVICE_TYPE_VIDEOTOOLBOX] = "videotoolbox",
75     [AV_HWDEVICE_TYPE_MEDIACODEC] = "mediacodec",
76 };
77
78 enum AVHWDeviceType av_hwdevice_find_type_by_name(const char *name)
79 {
80     int type;
81     for (type = 0; type < FF_ARRAY_ELEMS(hw_type_names); type++) {
82         if (hw_type_names[type] && !strcmp(hw_type_names[type], name))
83             return type;
84     }
85     return AV_HWDEVICE_TYPE_NONE;
86 }
87
88 const char *av_hwdevice_get_type_name(enum AVHWDeviceType type)
89 {
90     if (type > AV_HWDEVICE_TYPE_NONE &&
91         type < FF_ARRAY_ELEMS(hw_type_names))
92         return hw_type_names[type];
93     else
94         return NULL;
95 }
96
97 enum AVHWDeviceType av_hwdevice_iterate_types(enum AVHWDeviceType prev)
98 {
99     enum AVHWDeviceType next;
100     int i, set = 0;
101     for (i = 0; hw_table[i]; i++) {
102         if (prev != AV_HWDEVICE_TYPE_NONE && hw_table[i]->type <= prev)
103             continue;
104         if (!set || hw_table[i]->type < next) {
105             next = hw_table[i]->type;
106             set = 1;
107         }
108     }
109     return set ? next : AV_HWDEVICE_TYPE_NONE;
110 }
111
112 static const AVClass hwdevice_ctx_class = {
113     .class_name = "AVHWDeviceContext",
114     .item_name  = av_default_item_name,
115     .version    = LIBAVUTIL_VERSION_INT,
116 };
117
118 static void hwdevice_ctx_free(void *opaque, uint8_t *data)
119 {
120     AVHWDeviceContext *ctx = (AVHWDeviceContext*)data;
121
122     /* uninit might still want access the hw context and the user
123      * free() callback might destroy it, so uninit has to be called first */
124     if (ctx->internal->hw_type->device_uninit)
125         ctx->internal->hw_type->device_uninit(ctx);
126
127     if (ctx->free)
128         ctx->free(ctx);
129
130     av_buffer_unref(&ctx->internal->source_device);
131
132     av_freep(&ctx->hwctx);
133     av_freep(&ctx->internal->priv);
134     av_freep(&ctx->internal);
135     av_freep(&ctx);
136 }
137
138 AVBufferRef *av_hwdevice_ctx_alloc(enum AVHWDeviceType type)
139 {
140     AVHWDeviceContext *ctx;
141     AVBufferRef *buf;
142     const HWContextType *hw_type = NULL;
143     int i;
144
145     for (i = 0; hw_table[i]; i++) {
146         if (hw_table[i]->type == type) {
147             hw_type = hw_table[i];
148             break;
149         }
150     }
151     if (!hw_type)
152         return NULL;
153
154     ctx = av_mallocz(sizeof(*ctx));
155     if (!ctx)
156         return NULL;
157
158     ctx->internal = av_mallocz(sizeof(*ctx->internal));
159     if (!ctx->internal)
160         goto fail;
161
162     if (hw_type->device_priv_size) {
163         ctx->internal->priv = av_mallocz(hw_type->device_priv_size);
164         if (!ctx->internal->priv)
165             goto fail;
166     }
167
168     if (hw_type->device_hwctx_size) {
169         ctx->hwctx = av_mallocz(hw_type->device_hwctx_size);
170         if (!ctx->hwctx)
171             goto fail;
172     }
173
174     buf = av_buffer_create((uint8_t*)ctx, sizeof(*ctx),
175                            hwdevice_ctx_free, NULL,
176                            AV_BUFFER_FLAG_READONLY);
177     if (!buf)
178         goto fail;
179
180     ctx->type     = type;
181     ctx->av_class = &hwdevice_ctx_class;
182
183     ctx->internal->hw_type = hw_type;
184
185     return buf;
186
187 fail:
188     if (ctx->internal)
189         av_freep(&ctx->internal->priv);
190     av_freep(&ctx->internal);
191     av_freep(&ctx->hwctx);
192     av_freep(&ctx);
193     return NULL;
194 }
195
196 int av_hwdevice_ctx_init(AVBufferRef *ref)
197 {
198     AVHWDeviceContext *ctx = (AVHWDeviceContext*)ref->data;
199     int ret;
200
201     if (ctx->internal->hw_type->device_init) {
202         ret = ctx->internal->hw_type->device_init(ctx);
203         if (ret < 0)
204             goto fail;
205     }
206
207     return 0;
208 fail:
209     if (ctx->internal->hw_type->device_uninit)
210         ctx->internal->hw_type->device_uninit(ctx);
211     return ret;
212 }
213
214 static const AVClass hwframe_ctx_class = {
215     .class_name = "AVHWFramesContext",
216     .item_name  = av_default_item_name,
217     .version    = LIBAVUTIL_VERSION_INT,
218 };
219
220 static void hwframe_ctx_free(void *opaque, uint8_t *data)
221 {
222     AVHWFramesContext *ctx = (AVHWFramesContext*)data;
223
224     if (ctx->internal->pool_internal)
225         av_buffer_pool_uninit(&ctx->internal->pool_internal);
226
227     if (ctx->internal->hw_type->frames_uninit)
228         ctx->internal->hw_type->frames_uninit(ctx);
229
230     if (ctx->free)
231         ctx->free(ctx);
232
233     av_buffer_unref(&ctx->internal->source_frames);
234
235     av_buffer_unref(&ctx->device_ref);
236
237     av_freep(&ctx->hwctx);
238     av_freep(&ctx->internal->priv);
239     av_freep(&ctx->internal);
240     av_freep(&ctx);
241 }
242
243 AVBufferRef *av_hwframe_ctx_alloc(AVBufferRef *device_ref_in)
244 {
245     AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)device_ref_in->data;
246     const HWContextType  *hw_type = device_ctx->internal->hw_type;
247     AVHWFramesContext *ctx;
248     AVBufferRef *buf, *device_ref = NULL;
249
250     ctx = av_mallocz(sizeof(*ctx));
251     if (!ctx)
252         return NULL;
253
254     ctx->internal = av_mallocz(sizeof(*ctx->internal));
255     if (!ctx->internal)
256         goto fail;
257
258     if (hw_type->frames_priv_size) {
259         ctx->internal->priv = av_mallocz(hw_type->frames_priv_size);
260         if (!ctx->internal->priv)
261             goto fail;
262     }
263
264     if (hw_type->frames_hwctx_size) {
265         ctx->hwctx = av_mallocz(hw_type->frames_hwctx_size);
266         if (!ctx->hwctx)
267             goto fail;
268     }
269
270     device_ref = av_buffer_ref(device_ref_in);
271     if (!device_ref)
272         goto fail;
273
274     buf = av_buffer_create((uint8_t*)ctx, sizeof(*ctx),
275                            hwframe_ctx_free, NULL,
276                            AV_BUFFER_FLAG_READONLY);
277     if (!buf)
278         goto fail;
279
280     ctx->av_class   = &hwframe_ctx_class;
281     ctx->device_ref = device_ref;
282     ctx->device_ctx = device_ctx;
283     ctx->format     = AV_PIX_FMT_NONE;
284     ctx->sw_format  = AV_PIX_FMT_NONE;
285
286     ctx->internal->hw_type = hw_type;
287
288     return buf;
289
290 fail:
291     if (device_ref)
292         av_buffer_unref(&device_ref);
293     if (ctx->internal)
294         av_freep(&ctx->internal->priv);
295     av_freep(&ctx->internal);
296     av_freep(&ctx->hwctx);
297     av_freep(&ctx);
298     return NULL;
299 }
300
301 static int hwframe_pool_prealloc(AVBufferRef *ref)
302 {
303     AVHWFramesContext *ctx = (AVHWFramesContext*)ref->data;
304     AVFrame **frames;
305     int i, ret = 0;
306
307     frames = av_mallocz_array(ctx->initial_pool_size, sizeof(*frames));
308     if (!frames)
309         return AVERROR(ENOMEM);
310
311     for (i = 0; i < ctx->initial_pool_size; i++) {
312         frames[i] = av_frame_alloc();
313         if (!frames[i])
314             goto fail;
315
316         ret = av_hwframe_get_buffer(ref, frames[i], 0);
317         if (ret < 0)
318             goto fail;
319     }
320
321 fail:
322     for (i = 0; i < ctx->initial_pool_size; i++)
323         av_frame_free(&frames[i]);
324     av_freep(&frames);
325
326     return ret;
327 }
328
329 int av_hwframe_ctx_init(AVBufferRef *ref)
330 {
331     AVHWFramesContext *ctx = (AVHWFramesContext*)ref->data;
332     const enum AVPixelFormat *pix_fmt;
333     int ret;
334
335     if (ctx->internal->source_frames) {
336         /* A derived frame context is already initialised. */
337         return 0;
338     }
339
340     /* validate the pixel format */
341     for (pix_fmt = ctx->internal->hw_type->pix_fmts; *pix_fmt != AV_PIX_FMT_NONE; pix_fmt++) {
342         if (*pix_fmt == ctx->format)
343             break;
344     }
345     if (*pix_fmt == AV_PIX_FMT_NONE) {
346         av_log(ctx, AV_LOG_ERROR,
347                "The hardware pixel format '%s' is not supported by the device type '%s'\n",
348                av_get_pix_fmt_name(ctx->format), ctx->internal->hw_type->name);
349         return AVERROR(ENOSYS);
350     }
351
352     /* validate the dimensions */
353     ret = av_image_check_size(ctx->width, ctx->height, 0, ctx);
354     if (ret < 0)
355         return ret;
356
357     /* format-specific init */
358     if (ctx->internal->hw_type->frames_init) {
359         ret = ctx->internal->hw_type->frames_init(ctx);
360         if (ret < 0)
361             goto fail;
362     }
363
364     if (ctx->internal->pool_internal && !ctx->pool)
365         ctx->pool = ctx->internal->pool_internal;
366
367     /* preallocate the frames in the pool, if requested */
368     if (ctx->initial_pool_size > 0) {
369         ret = hwframe_pool_prealloc(ref);
370         if (ret < 0)
371             goto fail;
372     }
373
374     return 0;
375 fail:
376     if (ctx->internal->hw_type->frames_uninit)
377         ctx->internal->hw_type->frames_uninit(ctx);
378     return ret;
379 }
380
381 int av_hwframe_transfer_get_formats(AVBufferRef *hwframe_ref,
382                                     enum AVHWFrameTransferDirection dir,
383                                     enum AVPixelFormat **formats, int flags)
384 {
385     AVHWFramesContext *ctx = (AVHWFramesContext*)hwframe_ref->data;
386
387     if (!ctx->internal->hw_type->transfer_get_formats)
388         return AVERROR(ENOSYS);
389
390     return ctx->internal->hw_type->transfer_get_formats(ctx, dir, formats);
391 }
392
393 static int transfer_data_alloc(AVFrame *dst, const AVFrame *src, int flags)
394 {
395     AVHWFramesContext *ctx = (AVHWFramesContext*)src->hw_frames_ctx->data;
396     AVFrame *frame_tmp;
397     int ret = 0;
398
399     frame_tmp = av_frame_alloc();
400     if (!frame_tmp)
401         return AVERROR(ENOMEM);
402
403     /* if the format is set, use that
404      * otherwise pick the first supported one */
405     if (dst->format >= 0) {
406         frame_tmp->format = dst->format;
407     } else {
408         enum AVPixelFormat *formats;
409
410         ret = av_hwframe_transfer_get_formats(src->hw_frames_ctx,
411                                               AV_HWFRAME_TRANSFER_DIRECTION_FROM,
412                                               &formats, 0);
413         if (ret < 0)
414             goto fail;
415         frame_tmp->format = formats[0];
416         av_freep(&formats);
417     }
418     frame_tmp->width  = ctx->width;
419     frame_tmp->height = ctx->height;
420
421     ret = av_frame_get_buffer(frame_tmp, 32);
422     if (ret < 0)
423         goto fail;
424
425     ret = av_hwframe_transfer_data(frame_tmp, src, flags);
426     if (ret < 0)
427         goto fail;
428
429     frame_tmp->width  = src->width;
430     frame_tmp->height = src->height;
431
432     av_frame_move_ref(dst, frame_tmp);
433
434 fail:
435     av_frame_free(&frame_tmp);
436     return ret;
437 }
438
439 int av_hwframe_transfer_data(AVFrame *dst, const AVFrame *src, int flags)
440 {
441     AVHWFramesContext *ctx;
442     int ret;
443
444     if (!dst->buf[0])
445         return transfer_data_alloc(dst, src, flags);
446
447     /*
448      * Hardware -> Hardware Transfer.
449      * Unlike Software -> Hardware or Hardware -> Software, the transfer
450      * function could be provided by either the src or dst, depending on
451      * the specific combination of hardware.
452      */
453     if (src->hw_frames_ctx && dst->hw_frames_ctx) {
454         AVHWFramesContext *src_ctx =
455             (AVHWFramesContext*)src->hw_frames_ctx->data;
456         AVHWFramesContext *dst_ctx =
457             (AVHWFramesContext*)dst->hw_frames_ctx->data;
458
459         if (src_ctx->internal->source_frames) {
460             av_log(src_ctx, AV_LOG_ERROR,
461                    "A device with a derived frame context cannot be used as "
462                    "the source of a HW -> HW transfer.");
463             return AVERROR(ENOSYS);
464         }
465
466         if (dst_ctx->internal->source_frames) {
467             av_log(src_ctx, AV_LOG_ERROR,
468                    "A device with a derived frame context cannot be used as "
469                    "the destination of a HW -> HW transfer.");
470             return AVERROR(ENOSYS);
471         }
472
473         ret = src_ctx->internal->hw_type->transfer_data_from(src_ctx, dst, src);
474         if (ret == AVERROR(ENOSYS))
475             ret = dst_ctx->internal->hw_type->transfer_data_to(dst_ctx, dst, src);
476         if (ret < 0)
477             return ret;
478     } else {
479         if (src->hw_frames_ctx) {
480             ctx = (AVHWFramesContext*)src->hw_frames_ctx->data;
481
482             ret = ctx->internal->hw_type->transfer_data_from(ctx, dst, src);
483             if (ret < 0)
484                 return ret;
485         } else if (dst->hw_frames_ctx) {
486             ctx = (AVHWFramesContext*)dst->hw_frames_ctx->data;
487
488             ret = ctx->internal->hw_type->transfer_data_to(ctx, dst, src);
489             if (ret < 0)
490                 return ret;
491         } else {
492             return AVERROR(ENOSYS);
493         }
494     }
495     return 0;
496 }
497
498 int av_hwframe_get_buffer(AVBufferRef *hwframe_ref, AVFrame *frame, int flags)
499 {
500     AVHWFramesContext *ctx = (AVHWFramesContext*)hwframe_ref->data;
501     int ret;
502
503     if (ctx->internal->source_frames) {
504         // This is a derived frame context, so we allocate in the source
505         // and map the frame immediately.
506         AVFrame *src_frame;
507
508         frame->format = ctx->format;
509         frame->hw_frames_ctx = av_buffer_ref(hwframe_ref);
510         if (!frame->hw_frames_ctx)
511             return AVERROR(ENOMEM);
512
513         src_frame = av_frame_alloc();
514         if (!src_frame)
515             return AVERROR(ENOMEM);
516
517         ret = av_hwframe_get_buffer(ctx->internal->source_frames,
518                                     src_frame, 0);
519         if (ret < 0) {
520             av_frame_free(&src_frame);
521             return ret;
522         }
523
524         ret = av_hwframe_map(frame, src_frame,
525                              ctx->internal->source_allocation_map_flags);
526         if (ret) {
527             av_log(ctx, AV_LOG_ERROR, "Failed to map frame into derived "
528                    "frame context: %d.\n", ret);
529             av_frame_free(&src_frame);
530             return ret;
531         }
532
533         // Free the source frame immediately - the mapped frame still
534         // contains a reference to it.
535         av_frame_free(&src_frame);
536
537         return 0;
538     }
539
540     if (!ctx->internal->hw_type->frames_get_buffer)
541         return AVERROR(ENOSYS);
542
543     if (!ctx->pool)
544         return AVERROR(EINVAL);
545
546     frame->hw_frames_ctx = av_buffer_ref(hwframe_ref);
547     if (!frame->hw_frames_ctx)
548         return AVERROR(ENOMEM);
549
550     ret = ctx->internal->hw_type->frames_get_buffer(ctx, frame);
551     if (ret < 0) {
552         av_buffer_unref(&frame->hw_frames_ctx);
553         return ret;
554     }
555
556     return 0;
557 }
558
559 void *av_hwdevice_hwconfig_alloc(AVBufferRef *ref)
560 {
561     AVHWDeviceContext *ctx = (AVHWDeviceContext*)ref->data;
562     const HWContextType  *hw_type = ctx->internal->hw_type;
563
564     if (hw_type->device_hwconfig_size == 0)
565         return NULL;
566
567     return av_mallocz(hw_type->device_hwconfig_size);
568 }
569
570 AVHWFramesConstraints *av_hwdevice_get_hwframe_constraints(AVBufferRef *ref,
571                                                            const void *hwconfig)
572 {
573     AVHWDeviceContext *ctx = (AVHWDeviceContext*)ref->data;
574     const HWContextType  *hw_type = ctx->internal->hw_type;
575     AVHWFramesConstraints *constraints;
576
577     if (!hw_type->frames_get_constraints)
578         return NULL;
579
580     constraints = av_mallocz(sizeof(*constraints));
581     if (!constraints)
582         return NULL;
583
584     constraints->min_width = constraints->min_height = 0;
585     constraints->max_width = constraints->max_height = INT_MAX;
586
587     if (hw_type->frames_get_constraints(ctx, hwconfig, constraints) >= 0) {
588         return constraints;
589     } else {
590         av_hwframe_constraints_free(&constraints);
591         return NULL;
592     }
593 }
594
595 void av_hwframe_constraints_free(AVHWFramesConstraints **constraints)
596 {
597     if (*constraints) {
598         av_freep(&(*constraints)->valid_hw_formats);
599         av_freep(&(*constraints)->valid_sw_formats);
600     }
601     av_freep(constraints);
602 }
603
604 int av_hwdevice_ctx_create(AVBufferRef **pdevice_ref, enum AVHWDeviceType type,
605                            const char *device, AVDictionary *opts, int flags)
606 {
607     AVBufferRef *device_ref = NULL;
608     AVHWDeviceContext *device_ctx;
609     int ret = 0;
610
611     device_ref = av_hwdevice_ctx_alloc(type);
612     if (!device_ref) {
613         ret = AVERROR(ENOMEM);
614         goto fail;
615     }
616     device_ctx = (AVHWDeviceContext*)device_ref->data;
617
618     if (!device_ctx->internal->hw_type->device_create) {
619         ret = AVERROR(ENOSYS);
620         goto fail;
621     }
622
623     ret = device_ctx->internal->hw_type->device_create(device_ctx, device,
624                                                        opts, flags);
625     if (ret < 0)
626         goto fail;
627
628     ret = av_hwdevice_ctx_init(device_ref);
629     if (ret < 0)
630         goto fail;
631
632     *pdevice_ref = device_ref;
633     return 0;
634 fail:
635     av_buffer_unref(&device_ref);
636     *pdevice_ref = NULL;
637     return ret;
638 }
639
640 int av_hwdevice_ctx_create_derived(AVBufferRef **dst_ref_ptr,
641                                    enum AVHWDeviceType type,
642                                    AVBufferRef *src_ref, int flags)
643 {
644     AVBufferRef *dst_ref = NULL, *tmp_ref;
645     AVHWDeviceContext *dst_ctx, *tmp_ctx;
646     int ret = 0;
647
648     tmp_ref = src_ref;
649     while (tmp_ref) {
650         tmp_ctx = (AVHWDeviceContext*)tmp_ref->data;
651         if (tmp_ctx->type == type) {
652             dst_ref = av_buffer_ref(tmp_ref);
653             if (!dst_ref) {
654                 ret = AVERROR(ENOMEM);
655                 goto fail;
656             }
657             goto done;
658         }
659         tmp_ref = tmp_ctx->internal->source_device;
660     }
661
662     dst_ref = av_hwdevice_ctx_alloc(type);
663     if (!dst_ref) {
664         ret = AVERROR(ENOMEM);
665         goto fail;
666     }
667     dst_ctx = (AVHWDeviceContext*)dst_ref->data;
668
669     tmp_ref = src_ref;
670     while (tmp_ref) {
671         tmp_ctx = (AVHWDeviceContext*)tmp_ref->data;
672         if (dst_ctx->internal->hw_type->device_derive) {
673             ret = dst_ctx->internal->hw_type->device_derive(dst_ctx,
674                                                             tmp_ctx,
675                                                             flags);
676             if (ret == 0) {
677                 dst_ctx->internal->source_device = av_buffer_ref(src_ref);
678                 if (!dst_ctx->internal->source_device) {
679                     ret = AVERROR(ENOMEM);
680                     goto fail;
681                 }
682                 ret = av_hwdevice_ctx_init(dst_ref);
683                 if (ret < 0)
684                     goto fail;
685                 goto done;
686             }
687             if (ret != AVERROR(ENOSYS))
688                 goto fail;
689         }
690         tmp_ref = tmp_ctx->internal->source_device;
691     }
692
693     ret = AVERROR(ENOSYS);
694     goto fail;
695
696 done:
697     *dst_ref_ptr = dst_ref;
698     return 0;
699
700 fail:
701     av_buffer_unref(&dst_ref);
702     *dst_ref_ptr = NULL;
703     return ret;
704 }
705
706 static void ff_hwframe_unmap(void *opaque, uint8_t *data)
707 {
708     HWMapDescriptor *hwmap = (HWMapDescriptor*)data;
709     AVHWFramesContext *ctx = opaque;
710
711     if (hwmap->unmap)
712         hwmap->unmap(ctx, hwmap);
713
714     av_frame_free(&hwmap->source);
715
716     av_buffer_unref(&hwmap->hw_frames_ctx);
717
718     av_free(hwmap);
719 }
720
721 int ff_hwframe_map_create(AVBufferRef *hwframe_ref,
722                           AVFrame *dst, const AVFrame *src,
723                           void (*unmap)(AVHWFramesContext *ctx,
724                                         HWMapDescriptor *hwmap),
725                           void *priv)
726 {
727     AVHWFramesContext *ctx = (AVHWFramesContext*)hwframe_ref->data;
728     HWMapDescriptor *hwmap;
729     int ret;
730
731     hwmap = av_mallocz(sizeof(*hwmap));
732     if (!hwmap) {
733         ret = AVERROR(ENOMEM);
734         goto fail;
735     }
736
737     hwmap->source = av_frame_alloc();
738     if (!hwmap->source) {
739         ret = AVERROR(ENOMEM);
740         goto fail;
741     }
742     ret = av_frame_ref(hwmap->source, src);
743     if (ret < 0)
744         goto fail;
745
746     hwmap->hw_frames_ctx = av_buffer_ref(hwframe_ref);
747     if (!hwmap->hw_frames_ctx) {
748         ret = AVERROR(ENOMEM);
749         goto fail;
750     }
751
752     hwmap->unmap = unmap;
753     hwmap->priv  = priv;
754
755     dst->buf[0] = av_buffer_create((uint8_t*)hwmap, sizeof(*hwmap),
756                                    &ff_hwframe_unmap, ctx, 0);
757     if (!dst->buf[0]) {
758         ret = AVERROR(ENOMEM);
759         goto fail;
760     }
761
762     return 0;
763
764 fail:
765     if (hwmap) {
766         av_buffer_unref(&hwmap->hw_frames_ctx);
767         av_frame_free(&hwmap->source);
768     }
769     av_free(hwmap);
770     return ret;
771 }
772
773 int av_hwframe_map(AVFrame *dst, const AVFrame *src, int flags)
774 {
775     AVHWFramesContext *src_frames, *dst_frames;
776     HWMapDescriptor *hwmap;
777     int ret;
778
779     if (src->hw_frames_ctx && dst->hw_frames_ctx) {
780         src_frames = (AVHWFramesContext*)src->hw_frames_ctx->data;
781         dst_frames = (AVHWFramesContext*)dst->hw_frames_ctx->data;
782
783         if ((src_frames == dst_frames &&
784              src->format == dst_frames->sw_format &&
785              dst->format == dst_frames->format) ||
786             (src_frames->internal->source_frames &&
787              src_frames->internal->source_frames->data ==
788              (uint8_t*)dst_frames)) {
789             // This is an unmap operation.  We don't need to directly
790             // do anything here other than fill in the original frame,
791             // because the real unmap will be invoked when the last
792             // reference to the mapped frame disappears.
793             if (!src->buf[0]) {
794                 av_log(src_frames, AV_LOG_ERROR, "Invalid mapping "
795                        "found when attempting unmap.\n");
796                 return AVERROR(EINVAL);
797             }
798             hwmap = (HWMapDescriptor*)src->buf[0]->data;
799             av_frame_unref(dst);
800             return av_frame_ref(dst, hwmap->source);
801         }
802     }
803
804     if (src->hw_frames_ctx) {
805         src_frames = (AVHWFramesContext*)src->hw_frames_ctx->data;
806
807         if (src_frames->format == src->format &&
808             src_frames->internal->hw_type->map_from) {
809             ret = src_frames->internal->hw_type->map_from(src_frames,
810                                                           dst, src, flags);
811             if (ret != AVERROR(ENOSYS))
812                 return ret;
813         }
814     }
815
816     if (dst->hw_frames_ctx) {
817         dst_frames = (AVHWFramesContext*)dst->hw_frames_ctx->data;
818
819         if (dst_frames->format == dst->format &&
820             dst_frames->internal->hw_type->map_to) {
821             ret = dst_frames->internal->hw_type->map_to(dst_frames,
822                                                         dst, src, flags);
823             if (ret != AVERROR(ENOSYS))
824                 return ret;
825         }
826     }
827
828     return AVERROR(ENOSYS);
829 }
830
831 int av_hwframe_ctx_create_derived(AVBufferRef **derived_frame_ctx,
832                                   enum AVPixelFormat format,
833                                   AVBufferRef *derived_device_ctx,
834                                   AVBufferRef *source_frame_ctx,
835                                   int flags)
836 {
837     AVBufferRef   *dst_ref = NULL;
838     AVHWFramesContext *dst = NULL;
839     AVHWFramesContext *src = (AVHWFramesContext*)source_frame_ctx->data;
840     int ret;
841
842     if (src->internal->source_frames) {
843         AVHWFramesContext *src_src =
844             (AVHWFramesContext*)src->internal->source_frames->data;
845         AVHWDeviceContext *dst_dev =
846             (AVHWDeviceContext*)derived_device_ctx->data;
847
848         if (src_src->device_ctx == dst_dev) {
849             // This is actually an unmapping, so we just return a
850             // reference to the source frame context.
851             *derived_frame_ctx =
852                 av_buffer_ref(src->internal->source_frames);
853             if (!*derived_frame_ctx) {
854                 ret = AVERROR(ENOMEM);
855                 goto fail;
856             }
857             return 0;
858         }
859     }
860
861     dst_ref = av_hwframe_ctx_alloc(derived_device_ctx);
862     if (!dst_ref) {
863         ret = AVERROR(ENOMEM);
864         goto fail;
865     }
866
867     dst = (AVHWFramesContext*)dst_ref->data;
868
869     dst->format    = format;
870     dst->sw_format = src->sw_format;
871     dst->width     = src->width;
872     dst->height    = src->height;
873
874     dst->internal->source_frames = av_buffer_ref(source_frame_ctx);
875     if (!dst->internal->source_frames) {
876         ret = AVERROR(ENOMEM);
877         goto fail;
878     }
879
880     dst->internal->source_allocation_map_flags =
881         flags & (AV_HWFRAME_MAP_READ      |
882                  AV_HWFRAME_MAP_WRITE     |
883                  AV_HWFRAME_MAP_OVERWRITE |
884                  AV_HWFRAME_MAP_DIRECT);
885
886     ret = AVERROR(ENOSYS);
887     if (src->internal->hw_type->frames_derive_from)
888         ret = src->internal->hw_type->frames_derive_from(dst, src, flags);
889     if (ret == AVERROR(ENOSYS) &&
890         dst->internal->hw_type->frames_derive_to)
891         ret = dst->internal->hw_type->frames_derive_to(dst, src, flags);
892     if (ret == AVERROR(ENOSYS))
893         ret = 0;
894     if (ret)
895         goto fail;
896
897     *derived_frame_ctx = dst_ref;
898     return 0;
899
900 fail:
901     if (dst)
902         av_buffer_unref(&dst->internal->source_frames);
903     av_buffer_unref(&dst_ref);
904     return ret;
905 }
906
907 int ff_hwframe_map_replace(AVFrame *dst, const AVFrame *src)
908 {
909     HWMapDescriptor *hwmap = (HWMapDescriptor*)dst->buf[0]->data;
910     av_frame_unref(hwmap->source);
911     return av_frame_ref(hwmap->source, src);
912 }