]> git.sesse.net Git - ffmpeg/blob - libavcodec/amfenc.c
Merge commit 'c31f6b1d61759436ef50c094e7f4c8005e97614a'
[ffmpeg] / libavcodec / amfenc.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 "libavutil/avassert.h"
22 #include "libavutil/imgutils.h"
23 #include "libavutil/hwcontext.h"
24 #if CONFIG_D3D11VA
25 #include "libavutil/hwcontext_d3d11va.h"
26 #endif
27 #include "libavutil/mem.h"
28 #include "libavutil/pixdesc.h"
29 #include "libavutil/time.h"
30
31 #include "amfenc.h"
32 #include "internal.h"
33
34 #if CONFIG_D3D11VA
35 #include <d3d11.h>
36 #endif
37
38 #ifdef _WIN32
39 #include "compat/w32dlfcn.h"
40 #else
41 #include <dlfcn.h>
42 #endif
43
44 #define FFMPEG_AMF_WRITER_ID L"ffmpeg_amf"
45
46 #define PTS_PROP L"PtsProp"
47
48 const enum AVPixelFormat ff_amf_pix_fmts[] = {
49     AV_PIX_FMT_NV12,
50     AV_PIX_FMT_YUV420P,
51 #if CONFIG_D3D11VA
52     AV_PIX_FMT_D3D11,
53 #endif
54     AV_PIX_FMT_NONE
55 };
56
57 typedef struct FormatMap {
58     enum AVPixelFormat       av_format;
59     enum AMF_SURFACE_FORMAT  amf_format;
60 } FormatMap;
61
62 static const FormatMap format_map[] =
63 {
64     { AV_PIX_FMT_NONE,       AMF_SURFACE_UNKNOWN },
65     { AV_PIX_FMT_NV12,       AMF_SURFACE_NV12 },
66     { AV_PIX_FMT_BGR0,       AMF_SURFACE_BGRA },
67     { AV_PIX_FMT_RGB0,       AMF_SURFACE_RGBA },
68     { AV_PIX_FMT_GRAY8,      AMF_SURFACE_GRAY8 },
69     { AV_PIX_FMT_YUV420P,    AMF_SURFACE_YUV420P },
70     { AV_PIX_FMT_YUYV422,    AMF_SURFACE_YUY2 },
71     { AV_PIX_FMT_D3D11,      AMF_SURFACE_NV12 },
72 };
73
74
75 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
76 {
77     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
78     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
79 }
80
81
82 static enum AMF_SURFACE_FORMAT amf_av_to_amf_format(enum AVPixelFormat fmt)
83 {
84     int i;
85     for (i = 0; i < amf_countof(format_map); i++) {
86         if (format_map[i].av_format == fmt) {
87             return format_map[i].amf_format;
88         }
89     }
90     return AMF_SURFACE_UNKNOWN;
91 }
92
93 static void AMF_CDECL_CALL AMFTraceWriter_Write(AMFTraceWriter *pThis,
94     const wchar_t *scope, const wchar_t *message)
95 {
96     AmfTraceWriter *tracer = (AmfTraceWriter*)pThis;
97     av_log(tracer->avctx, AV_LOG_DEBUG, "%ls: %ls", scope, message); // \n is provided from AMF
98 }
99
100 static void AMF_CDECL_CALL AMFTraceWriter_Flush(AMFTraceWriter *pThis)
101 {
102 }
103
104 static AMFTraceWriterVtbl tracer_vtbl =
105 {
106     .Write = AMFTraceWriter_Write,
107     .Flush = AMFTraceWriter_Flush,
108 };
109
110 static int amf_load_library(AVCodecContext *avctx)
111 {
112     AmfContext             *ctx = avctx->priv_data;
113     AMFInit_Fn              init_fun = NULL;
114     AMFQueryVersion_Fn      version_fun = NULL;
115     AMF_RESULT              res = AMF_OK;
116
117     ctx->eof = 0;
118     ctx->delayed_drain = 0;
119     ctx->hw_frames_ctx = NULL;
120     ctx->hw_device_ctx = NULL;
121     ctx->delayed_surface = NULL;
122     ctx->delayed_frame = av_frame_alloc();
123     if (!ctx->delayed_frame) {
124         return AVERROR(ENOMEM);
125     }
126     // hardcoded to current HW queue size - will realloc in timestamp_queue_enqueue() if too small
127     ctx->timestamp_list = av_fifo_alloc((avctx->max_b_frames + 16) * sizeof(int64_t));
128     if (!ctx->timestamp_list) {
129         return AVERROR(ENOMEM);
130     }
131     ctx->dts_delay = 0;
132
133
134     ctx->library = dlopen(AMF_DLL_NAMEA, RTLD_NOW | RTLD_LOCAL);
135     AMF_RETURN_IF_FALSE(ctx, ctx->library != NULL,
136         AVERROR_UNKNOWN, "DLL %s failed to open\n", AMF_DLL_NAMEA);
137
138     init_fun = (AMFInit_Fn)dlsym(ctx->library, AMF_INIT_FUNCTION_NAME);
139     AMF_RETURN_IF_FALSE(ctx, init_fun != NULL, AVERROR_UNKNOWN, "DLL %s failed to find function %s\n", AMF_DLL_NAMEA, AMF_INIT_FUNCTION_NAME);
140
141     version_fun = (AMFQueryVersion_Fn)dlsym(ctx->library, AMF_QUERY_VERSION_FUNCTION_NAME);
142     AMF_RETURN_IF_FALSE(ctx, version_fun != NULL, AVERROR_UNKNOWN, "DLL %s failed to find function %s\n", AMF_DLL_NAMEA, AMF_QUERY_VERSION_FUNCTION_NAME);
143
144     res = version_fun(&ctx->version);
145     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_QUERY_VERSION_FUNCTION_NAME, res);
146     res = init_fun(AMF_FULL_VERSION, &ctx->factory);
147     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_INIT_FUNCTION_NAME, res);
148     res = ctx->factory->pVtbl->GetTrace(ctx->factory, &ctx->trace);
149     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetTrace() failed with error %d\n", res);
150     res = ctx->factory->pVtbl->GetDebug(ctx->factory, &ctx->debug);
151     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetDebug() failed with error %d\n", res);
152     return 0;
153 }
154
155 static int amf_init_context(AVCodecContext *avctx)
156 {
157     AmfContext         *ctx = avctx->priv_data;
158     AMF_RESULT          res = AMF_OK;
159
160     ctx->hwsurfaces_in_queue = 0;
161     ctx->hwsurfaces_in_queue_max = 16;
162
163     // configure AMF logger
164     // the return of these functions indicates old state and do not affect behaviour
165     ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, ctx->log_to_dbg != 0 );
166     if (ctx->log_to_dbg)
167         ctx->trace->pVtbl->SetWriterLevel(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, AMF_TRACE_TRACE);
168     ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_CONSOLE, 0);
169     ctx->trace->pVtbl->SetGlobalLevel(ctx->trace, AMF_TRACE_TRACE);
170
171     // connect AMF logger to av_log
172     ctx->tracer.vtbl = &tracer_vtbl;
173     ctx->tracer.avctx = avctx;
174     ctx->trace->pVtbl->RegisterWriter(ctx->trace, FFMPEG_AMF_WRITER_ID,(AMFTraceWriter*)&ctx->tracer, 1);
175     ctx->trace->pVtbl->SetWriterLevel(ctx->trace, FFMPEG_AMF_WRITER_ID, AMF_TRACE_TRACE);
176
177     res = ctx->factory->pVtbl->CreateContext(ctx->factory, &ctx->context);
178     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "CreateContext() failed with error %d\n", res);
179     // try to reuse existing DX device
180 #if CONFIG_D3D11VA
181     if (avctx->hw_frames_ctx) {
182         AVHWFramesContext *device_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
183         if (device_ctx->device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
184             if (amf_av_to_amf_format(device_ctx->sw_format) != AMF_SURFACE_UNKNOWN) {
185                 if (device_ctx->device_ctx->hwctx) {
186                     AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->device_ctx->hwctx;
187                     res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
188                     if (res == AMF_OK) {
189                         ctx->hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
190                         if (!ctx->hw_frames_ctx) {
191                             return AVERROR(ENOMEM);
192                         }
193                         if (device_ctx->initial_pool_size > 0)
194                             ctx->hwsurfaces_in_queue_max = device_ctx->initial_pool_size - 1;
195                     } else {
196                         if(res == AMF_NOT_SUPPORTED)
197                             av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
198                         else
199                             av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has non-AMD device, switching to default\n");
200                     }
201                 }
202             } else {
203                 av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has format not uspported by AMF, switching to default\n");
204             }
205         }
206     } else if (avctx->hw_device_ctx) {
207         AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
208         if (device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
209             if (device_ctx->hwctx) {
210                 AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->hwctx;
211                 res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
212                 if (res == AMF_OK) {
213                     ctx->hw_device_ctx = av_buffer_ref(avctx->hw_device_ctx);
214                     if (!ctx->hw_device_ctx) {
215                         return AVERROR(ENOMEM);
216                     }
217                 } else {
218                     if (res == AMF_NOT_SUPPORTED)
219                         av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
220                     else
221                         av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has non-AMD device, switching to default\n");
222                 }
223             }
224         }
225     }
226 #endif
227     if (!ctx->hw_frames_ctx && !ctx->hw_device_ctx) {
228         res = ctx->context->pVtbl->InitDX11(ctx->context, NULL, AMF_DX11_1);
229         if (res != AMF_OK) {
230             res = ctx->context->pVtbl->InitDX9(ctx->context, NULL);
231             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "InitDX9() failed with error %d\n", res);
232         }
233     }
234     return 0;
235 }
236
237 static int amf_init_encoder(AVCodecContext *avctx)
238 {
239     AmfContext          *ctx = avctx->priv_data;
240     const wchar_t       *codec_id = NULL;
241     AMF_RESULT           res = AMF_OK;
242
243     switch (avctx->codec->id) {
244         case AV_CODEC_ID_H264:
245             codec_id = AMFVideoEncoderVCE_AVC;
246             break;
247         case AV_CODEC_ID_HEVC:
248             codec_id = AMFVideoEncoder_HEVC;
249             break;
250         default:
251             break;
252     }
253     AMF_RETURN_IF_FALSE(ctx, codec_id != NULL, AVERROR(EINVAL), "Codec %d is not supported\n", avctx->codec->id);
254
255     ctx->format = amf_av_to_amf_format(avctx->pix_fmt);
256     AMF_RETURN_IF_FALSE(ctx, ctx->format != AMF_SURFACE_UNKNOWN, AVERROR(EINVAL), "Format %d is not supported\n", avctx->pix_fmt);
257
258     res = ctx->factory->pVtbl->CreateComponent(ctx->factory, ctx->context, codec_id, &ctx->encoder);
259     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_ENCODER_NOT_FOUND, "CreateComponent(%ls) failed with error %d\n", codec_id, res);
260
261     return 0;
262 }
263
264 int av_cold ff_amf_encode_close(AVCodecContext *avctx)
265 {
266     AmfContext      *ctx = avctx->priv_data;
267     if (ctx->delayed_surface)
268     {
269         ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
270         ctx->delayed_surface = NULL;
271     }
272
273     if (ctx->encoder) {
274         ctx->encoder->pVtbl->Terminate(ctx->encoder);
275         ctx->encoder->pVtbl->Release(ctx->encoder);
276         ctx->encoder = NULL;
277     }
278
279     if (ctx->context) {
280         ctx->context->pVtbl->Terminate(ctx->context);
281         ctx->context->pVtbl->Release(ctx->context);
282         ctx->context = NULL;
283     }
284     av_buffer_unref(&ctx->hw_device_ctx);
285     av_buffer_unref(&ctx->hw_frames_ctx);
286
287     if (ctx->trace) {
288         ctx->trace->pVtbl->UnregisterWriter(ctx->trace, FFMPEG_AMF_WRITER_ID);
289     }
290     if (ctx->library) {
291         dlclose(ctx->library);
292         ctx->library = NULL;
293     }
294     ctx->trace = NULL;
295     ctx->debug = NULL;
296     ctx->factory = NULL;
297     ctx->version = 0;
298     ctx->delayed_drain = 0;
299     av_frame_free(&ctx->delayed_frame);
300     av_fifo_freep(&ctx->timestamp_list);
301
302     return 0;
303 }
304
305 static int amf_copy_surface(AVCodecContext *avctx, const AVFrame *frame,
306     AMFSurface* surface)
307 {
308     AVFrame        *sw_frame = NULL;
309     AMFPlane       *plane = NULL;
310     uint8_t        *dst_data[4];
311     int             dst_linesize[4];
312     int             ret = 0;
313     int             planes;
314     int             i;
315
316     if (frame->hw_frames_ctx && is_hwaccel_pix_fmt(frame->format)) {
317         if (!(sw_frame = av_frame_alloc())) {
318             av_log(avctx, AV_LOG_ERROR, "Can not alloc frame\n");
319             ret = AVERROR(ENOMEM);
320             goto fail;
321         }
322         if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
323             av_log(avctx, AV_LOG_ERROR, "Error transferring the data to system memory\n");
324             goto fail;
325         }
326         frame = sw_frame;
327     }
328     planes = (int)surface->pVtbl->GetPlanesCount(surface);
329     if (planes > amf_countof(dst_data)) {
330         av_log(avctx, AV_LOG_ERROR, "Invalid number of planes %d in surface\n", planes);
331         ret = AVERROR(EINVAL);
332         goto fail;
333     }
334
335     for (i = 0; i < planes; i++) {
336         plane = surface->pVtbl->GetPlaneAt(surface, i);
337         dst_data[i] = plane->pVtbl->GetNative(plane);
338         dst_linesize[i] = plane->pVtbl->GetHPitch(plane);
339     }
340     av_image_copy(dst_data, dst_linesize,
341         (const uint8_t**)frame->data, frame->linesize, frame->format,
342         avctx->width, avctx->height);
343
344 fail:
345     if (sw_frame) {
346         av_frame_free(&sw_frame);
347     }
348     return ret;
349 }
350
351 static inline int timestamp_queue_enqueue(AVCodecContext *avctx, int64_t timestamp)
352 {
353     AmfContext         *ctx = avctx->priv_data;
354     if (av_fifo_space(ctx->timestamp_list) < sizeof(timestamp)) {
355         if (av_fifo_grow(ctx->timestamp_list, sizeof(timestamp)) < 0) {
356             return AVERROR(ENOMEM);
357         }
358     }
359     av_fifo_generic_write(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
360     return 0;
361 }
362
363 static int amf_copy_buffer(AVCodecContext *avctx, AVPacket *pkt, AMFBuffer *buffer)
364 {
365     AmfContext             *ctx = avctx->priv_data;
366     int                     ret;
367     AMFVariantStruct        var = {0};
368     int64_t                 timestamp = AV_NOPTS_VALUE;
369     int64_t                 size = buffer->pVtbl->GetSize(buffer);
370
371     if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0) {
372         return ret;
373     }
374     memcpy(pkt->data, buffer->pVtbl->GetNative(buffer), size);
375
376     switch (avctx->codec->id) {
377         case AV_CODEC_ID_H264:
378             buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE, &var);
379             if(var.int64Value == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR) {
380                 pkt->flags = AV_PKT_FLAG_KEY;
381             }
382             break;
383         case AV_CODEC_ID_HEVC:
384             buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE, &var);
385             if (var.int64Value == AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR) {
386                 pkt->flags = AV_PKT_FLAG_KEY;
387             }
388             break;
389         default:
390             break;
391     }
392
393     buffer->pVtbl->GetProperty(buffer, PTS_PROP, &var);
394
395     pkt->pts = var.int64Value; // original pts
396
397
398     AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN, "timestamp_list is empty\n");
399
400     av_fifo_generic_read(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
401
402     // calc dts shift if max_b_frames > 0
403     if (avctx->max_b_frames > 0 && ctx->dts_delay == 0) {
404         int64_t timestamp_last = AV_NOPTS_VALUE;
405         AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN,
406             "timestamp_list is empty while max_b_frames = %d\n", avctx->max_b_frames);
407         av_fifo_generic_peek_at(
408             ctx->timestamp_list,
409             &timestamp_last,
410             (av_fifo_size(ctx->timestamp_list) / sizeof(timestamp) - 1) * sizeof(timestamp_last),
411             sizeof(timestamp_last),
412             NULL);
413         if (timestamp < 0 || timestamp_last < AV_NOPTS_VALUE) {
414             return AVERROR(ERANGE);
415         }
416         ctx->dts_delay = timestamp_last - timestamp;
417     }
418     pkt->dts = timestamp - ctx->dts_delay;
419     return 0;
420 }
421
422 // amfenc API implementation
423 int ff_amf_encode_init(AVCodecContext *avctx)
424 {
425     AmfContext     *ctx = avctx->priv_data;
426     int             ret;
427
428     ctx->factory = NULL;
429     ctx->debug = NULL;
430     ctx->trace = NULL;
431     ctx->context = NULL;
432     ctx->encoder = NULL;
433     ctx->library = NULL;
434     ctx->version = 0;
435     ctx->eof = 0;
436     ctx->format = 0;
437     ctx->tracer.vtbl = NULL;
438     ctx->tracer.avctx = NULL;
439
440     if ((ret = amf_load_library(avctx)) == 0) {
441         if ((ret = amf_init_context(avctx)) == 0) {
442             if ((ret = amf_init_encoder(avctx)) == 0) {
443                 return 0;
444             }
445         }
446     }
447     ff_amf_encode_close(avctx);
448     return ret;
449 }
450
451 static AMF_RESULT amf_set_property_buffer(AMFSurface *object, const wchar_t *name, AMFBuffer *val)
452 {
453     AMF_RESULT res;
454     AMFVariantStruct var;
455     res = AMFVariantInit(&var);
456     if (res == AMF_OK) {
457         AMFGuid guid_AMFInterface = IID_AMFInterface();
458         AMFInterface *amf_interface;
459         res = val->pVtbl->QueryInterface(val, &guid_AMFInterface, (void**)&amf_interface);
460
461         if (res == AMF_OK) {
462             res = AMFVariantAssignInterface(&var, amf_interface);
463             amf_interface->pVtbl->Release(amf_interface);
464         }
465         if (res == AMF_OK) {
466             res = object->pVtbl->SetProperty(object, name, var);
467         }
468         AMFVariantClear(&var);
469     }
470     return res;
471 }
472
473 static AMF_RESULT amf_get_property_buffer(AMFData *object, const wchar_t *name, AMFBuffer **val)
474 {
475     AMF_RESULT res;
476     AMFVariantStruct var;
477     res = AMFVariantInit(&var);
478     if (res == AMF_OK) {
479         res = object->pVtbl->GetProperty(object, name, &var);
480         if (res == AMF_OK) {
481             if (var.type == AMF_VARIANT_INTERFACE) {
482                 AMFGuid guid_AMFBuffer = IID_AMFBuffer();
483                 AMFInterface *amf_interface = AMFVariantInterface(&var);
484                 res = amf_interface->pVtbl->QueryInterface(amf_interface, &guid_AMFBuffer, (void**)val);
485             } else {
486                 res = AMF_INVALID_DATA_TYPE;
487             }
488         }
489         AMFVariantClear(&var);
490     }
491     return res;
492 }
493
494 static AMFBuffer *amf_create_buffer_with_frame_ref(const AVFrame *frame, AMFContext *context)
495 {
496     AVFrame *frame_ref;
497     AMFBuffer *frame_ref_storage_buffer = NULL;
498     AMF_RESULT res;
499
500     res = context->pVtbl->AllocBuffer(context, AMF_MEMORY_HOST, sizeof(frame_ref), &frame_ref_storage_buffer);
501     if (res == AMF_OK) {
502         frame_ref = av_frame_clone(frame);
503         if (frame_ref) {
504             memcpy(frame_ref_storage_buffer->pVtbl->GetNative(frame_ref_storage_buffer), &frame_ref, sizeof(frame_ref));
505         } else {
506             frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
507             frame_ref_storage_buffer = NULL;
508         }
509     }
510     return frame_ref_storage_buffer;
511 }
512
513 static void amf_release_buffer_with_frame_ref(AMFBuffer *frame_ref_storage_buffer)
514 {
515     AVFrame *av_frame_ref;
516     memcpy(&av_frame_ref, frame_ref_storage_buffer->pVtbl->GetNative(frame_ref_storage_buffer), sizeof(av_frame_ref));
517     av_frame_free(&av_frame_ref);
518     frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
519 }
520
521 int ff_amf_send_frame(AVCodecContext *avctx, const AVFrame *frame)
522 {
523     AMF_RESULT      res = AMF_OK;
524     AmfContext     *ctx = avctx->priv_data;
525     AMFSurface     *surface = NULL;
526     int             ret;
527
528     if (!ctx->encoder)
529         return AVERROR(EINVAL);
530
531     if (!frame) { // submit drain
532         if (!ctx->eof) { // submit drain one time only
533             if (ctx->delayed_surface != NULL) {
534                 ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
535             } else if(!ctx->delayed_drain) {
536                 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
537                 if (res == AMF_INPUT_FULL) {
538                     ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
539                 } else {
540                     if (res == AMF_OK) {
541                         ctx->eof = 1; // drain started
542                     }
543                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Drain() failed with error %d\n", res);
544                 }
545             }
546         } else{
547             return AVERROR_EOF;
548         }
549     } else { // submit frame
550         if (ctx->delayed_surface != NULL) {
551             return AVERROR(EAGAIN); // should not happen when called from ffmpeg, other clients may resubmit
552         }
553         // prepare surface from frame
554         if (frame->hw_frames_ctx && ( // HW frame detected
555             // check if the same hw_frames_ctx as used in initialization
556             (ctx->hw_frames_ctx && frame->hw_frames_ctx->data == ctx->hw_frames_ctx->data) ||
557             // check if the same hw_device_ctx as used in initialization
558             (ctx->hw_device_ctx && ((AVHWFramesContext*)frame->hw_frames_ctx->data)->device_ctx ==
559             (AVHWDeviceContext*)ctx->hw_device_ctx->data)
560         )) {
561             AMFBuffer *frame_ref_storage_buffer;
562
563 #if CONFIG_D3D11VA
564             static const GUID AMFTextureArrayIndexGUID = { 0x28115527, 0xe7c3, 0x4b66, { 0x99, 0xd3, 0x4f, 0x2a, 0xe6, 0xb4, 0x7f, 0xaf } };
565             ID3D11Texture2D *texture = (ID3D11Texture2D*)frame->data[0]; // actual texture
566             int index = (int)(size_t)frame->data[1]; // index is a slice in texture array is - set to tell AMF which slice to use
567             texture->lpVtbl->SetPrivateData(texture, &AMFTextureArrayIndexGUID, sizeof(index), &index);
568
569             res = ctx->context->pVtbl->CreateSurfaceFromDX11Native(ctx->context, texture, &surface, NULL); // wrap to AMF surface
570             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "CreateSurfaceFromDX11Native() failed  with error %d\n", res);
571
572             // input HW surfaces can be vertically aligned by 16; tell AMF the real size
573             surface->pVtbl->SetCrop(surface, 0, 0, frame->width, frame->height);
574 #endif
575
576             frame_ref_storage_buffer = amf_create_buffer_with_frame_ref(frame, ctx->context);
577             AMF_RETURN_IF_FALSE(ctx, frame_ref_storage_buffer != NULL, AVERROR(ENOMEM), "create_buffer_with_frame_ref() returned NULL\n");
578
579             res = amf_set_property_buffer(surface, L"av_frame_ref", frame_ref_storage_buffer);
580             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SetProperty failed for \"av_frame_ref\" with error %d\n", res);
581             ctx->hwsurfaces_in_queue++;
582             frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
583         } else {
584             res = ctx->context->pVtbl->AllocSurface(ctx->context, AMF_MEMORY_HOST, ctx->format, avctx->width, avctx->height, &surface);
585             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "AllocSurface() failed  with error %d\n", res);
586             amf_copy_surface(avctx, frame, surface);
587         }
588         surface->pVtbl->SetPts(surface, frame->pts);
589         AMF_ASSIGN_PROPERTY_INT64(res, surface, PTS_PROP, frame->pts);
590
591         switch (avctx->codec->id) {
592         case AV_CODEC_ID_H264:
593             AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_INSERT_AUD, !!ctx->aud);
594             break;
595         case AV_CODEC_ID_HEVC:
596             AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_HEVC_INSERT_AUD, !!ctx->aud);
597             break;
598         default:
599             break;
600         }
601
602
603         // submit surface
604         res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)surface);
605         if (res == AMF_INPUT_FULL) { // handle full queue
606             //store surface for later submission
607             ctx->delayed_surface = surface;
608             if (surface->pVtbl->GetMemoryType(surface) == AMF_MEMORY_DX11) {
609                 av_frame_ref(ctx->delayed_frame, frame);
610             }
611         } else {
612             surface->pVtbl->Release(surface);
613             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SubmitInput() failed with error %d\n", res);
614
615             if ((ret = timestamp_queue_enqueue(avctx, frame->pts)) < 0) {
616                 return ret;
617             }
618
619         }
620     }
621     return 0;
622 }
623 int ff_amf_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
624 {
625     int             ret;
626     AMF_RESULT      res;
627     AMF_RESULT      res_query;
628     AmfContext     *ctx = avctx->priv_data;
629     AMFData        *data = NULL;
630     int             block_and_wait;
631
632     if (!ctx->encoder)
633         return AVERROR(EINVAL);
634
635     do {
636         block_and_wait = 0;
637         // poll data
638         res_query = ctx->encoder->pVtbl->QueryOutput(ctx->encoder, &data);
639         if (data) {
640             // copy data to packet
641             AMFBuffer* buffer;
642             AMFGuid guid = IID_AMFBuffer();
643             data->pVtbl->QueryInterface(data, &guid, (void**)&buffer); // query for buffer interface
644             ret = amf_copy_buffer(avctx, avpkt, buffer);
645
646             buffer->pVtbl->Release(buffer);
647
648             if (data->pVtbl->HasProperty(data, L"av_frame_ref")) {
649                 AMFBuffer *frame_ref_storage_buffer;
650                 res = amf_get_property_buffer(data, L"av_frame_ref", &frame_ref_storage_buffer);
651                 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetProperty failed for \"av_frame_ref\" with error %d\n", res);
652                 amf_release_buffer_with_frame_ref(frame_ref_storage_buffer);
653                 ctx->hwsurfaces_in_queue--;
654             }
655
656             data->pVtbl->Release(data);
657
658             AMF_RETURN_IF_FALSE(ctx, ret >= 0, ret, "amf_copy_buffer() failed with error %d\n", ret);
659
660             if (ctx->delayed_surface != NULL) { // try to resubmit frame
661                 res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)ctx->delayed_surface);
662                 if (res != AMF_INPUT_FULL) {
663                     int64_t pts = ctx->delayed_surface->pVtbl->GetPts(ctx->delayed_surface);
664                     ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
665                     ctx->delayed_surface = NULL;
666                     av_frame_unref(ctx->delayed_frame);
667                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated SubmitInput() failed with error %d\n", res);
668
669                     if ((ret = timestamp_queue_enqueue(avctx, pts)) < 0) {
670                         return ret;
671                     }
672                 } else {
673                     av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed frame submission got AMF_INPUT_FULL- should not happen\n");
674                 }
675             } else if (ctx->delayed_drain) { // try to resubmit drain
676                 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
677                 if (res != AMF_INPUT_FULL) {
678                     ctx->delayed_drain = 0;
679                     ctx->eof = 1; // drain started
680                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated Drain() failed with error %d\n", res);
681                 } else {
682                     av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed drain submission got AMF_INPUT_FULL- should not happen\n");
683                 }
684             }
685         } else if (ctx->delayed_surface != NULL || ctx->delayed_drain || (ctx->eof && res_query != AMF_EOF) || (ctx->hwsurfaces_in_queue >= ctx->hwsurfaces_in_queue_max)) {
686             block_and_wait = 1;
687             av_usleep(1000); // wait and poll again
688         }
689     } while (block_and_wait);
690
691     if (res_query == AMF_EOF) {
692         ret = AVERROR_EOF;
693     } else if (data == NULL) {
694         ret = AVERROR(EAGAIN);
695     } else {
696         ret = 0;
697     }
698     return ret;
699 }