]> git.sesse.net Git - ffmpeg/blob - libavcodec/amfenc.c
cbs_h264: Add utility functions to insert/delete SEI messages
[ffmpeg] / libavcodec / amfenc.c
1 /*
2  * AMD AMF support
3  * Copyright (C) 2017 Luca Barbato
4  * Copyright (C) 2017 Mikhail Mironov <mikhail.mironov@amd.com>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/imgutils.h"
25 #include "libavutil/hwcontext.h"
26 #include "internal.h"
27 #if CONFIG_D3D11VA
28 #include "libavutil/hwcontext_d3d11va.h"
29 #endif
30 #include "libavutil/mem.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/time.h"
33
34 #include "amfenc.h"
35
36 #if CONFIG_D3D11VA
37 #include <d3d11.h>
38 #endif
39
40 #if HAVE_WINDOWS_H
41 #include <windows.h>
42 #define dlopen(filename, flags) LoadLibrary((filename))
43 #define dlsym(handle, symbol)   GetProcAddress(handle, symbol)
44 #define dlclose(handle)         FreeLibrary(handle)
45 #else
46 #include <dlfcn.h>
47 #endif
48
49 #define PTS_PROP L"PtsProp"
50
51 const enum AVPixelFormat ff_amf_pix_fmts[] = {
52     AV_PIX_FMT_NV12,
53     AV_PIX_FMT_YUV420P,
54 #if CONFIG_D3D11VA
55     AV_PIX_FMT_D3D11,
56 #endif
57     AV_PIX_FMT_NONE
58 };
59
60 typedef struct FormatMap {
61     enum AVPixelFormat       av_format;
62     enum AMF_SURFACE_FORMAT  amf_format;
63 } FormatMap;
64
65 static const FormatMap format_map[] =
66 {
67     { AV_PIX_FMT_NONE,       AMF_SURFACE_UNKNOWN },
68     { AV_PIX_FMT_NV12,       AMF_SURFACE_NV12 },
69 //    { AV_PIX_FMT_BGR0,       AMF_SURFACE_BGRA },
70 //    { AV_PIX_FMT_RGB0,       AMF_SURFACE_RGBA },
71     { AV_PIX_FMT_GRAY8,      AMF_SURFACE_GRAY8 },
72     { AV_PIX_FMT_YUV420P,    AMF_SURFACE_YUV420P },
73     { AV_PIX_FMT_YUYV422,    AMF_SURFACE_YUY2 },
74     { AV_PIX_FMT_D3D11,      AMF_SURFACE_NV12 },
75 };
76
77
78 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
79 {
80     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
81     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
82 }
83
84
85 static enum AMF_SURFACE_FORMAT amf_av_to_amf_format(enum AVPixelFormat fmt)
86 {
87     int i;
88     for (i = 0; i < amf_countof(format_map); i++) {
89         if (format_map[i].av_format == fmt) {
90             return format_map[i].amf_format;
91         }
92     }
93     return AMF_SURFACE_UNKNOWN;
94 }
95
96 static void AMF_CDECL_CALL AMFTraceWriter_Write(AMFTraceWriter *pThis,
97     const wchar_t *scope, const wchar_t *message)
98 {
99     AmfTraceWriter *tracer = (AmfTraceWriter*)pThis;
100     av_log(tracer->avctx, AV_LOG_DEBUG, "%ls: %ls", scope, message); // \n is provided from AMF
101 }
102
103 static void AMF_CDECL_CALL AMFTraceWriter_Flush(AMFTraceWriter *pThis)
104 {
105 }
106
107 static AMFTraceWriterVtbl tracer_vtbl =
108 {
109     .Write = AMFTraceWriter_Write,
110     .Flush = AMFTraceWriter_Flush,
111 };
112
113 static int amf_load_library(AVCodecContext *avctx)
114 {
115     AmfContext             *ctx = avctx->priv_data;
116     AMFInit_Fn              init_fun = NULL;
117     AMFQueryVersion_Fn      version_fun = NULL;
118     AMF_RESULT              res = AMF_OK;
119
120     ctx->eof = 0;
121     ctx->delayed_drain = 0;
122     ctx->hw_frames_ctx = NULL;
123     ctx->hw_device_ctx = NULL;
124     ctx->delayed_surface = NULL;
125     ctx->delayed_frame = av_frame_alloc();
126     if (!ctx->delayed_frame) {
127         return AVERROR(ENOMEM);
128     }
129     // hardcoded to current HW queue size - will realloc in timestamp_queue_enqueue() if too small
130     ctx->timestamp_list = av_fifo_alloc((avctx->max_b_frames + 16) * sizeof(int64_t));
131     if (!ctx->timestamp_list) {
132         return AVERROR(ENOMEM);
133     }
134     ctx->dts_delay = 0;
135
136
137     ctx->library = dlopen(AMF_DLL_NAMEA, RTLD_NOW | RTLD_LOCAL);
138     AMF_RETURN_IF_FALSE(ctx, ctx->library != NULL,
139         AVERROR_UNKNOWN, "DLL %s failed to open\n", AMF_DLL_NAMEA);
140
141     init_fun = (AMFInit_Fn)dlsym(ctx->library, AMF_INIT_FUNCTION_NAME);
142     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);
143
144     version_fun = (AMFQueryVersion_Fn)dlsym(ctx->library, AMF_QUERY_VERSION_FUNCTION_NAME);
145     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);
146
147     res = version_fun(&ctx->version);
148     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_QUERY_VERSION_FUNCTION_NAME, res);
149     res = init_fun(AMF_FULL_VERSION, &ctx->factory);
150     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_INIT_FUNCTION_NAME, res);
151     res = ctx->factory->pVtbl->GetTrace(ctx->factory, &ctx->trace);
152     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetTrace() failed with error %d\n", res);
153     res = ctx->factory->pVtbl->GetDebug(ctx->factory, &ctx->debug);
154     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetDebug() failed with error %d\n", res);
155     return 0;
156 }
157
158 static int amf_init_context(AVCodecContext *avctx)
159 {
160     AmfContext         *ctx = avctx->priv_data;
161     AMF_RESULT          res = AMF_OK;
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, ctx->writer_id, (AMFTraceWriter*)&ctx->tracer, 1);
175     ctx->trace->pVtbl->SetWriterLevel(ctx->trace, ctx->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                     } else {
194                         if(res == AMF_NOT_SUPPORTED)
195                             av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
196                         else
197                             av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has non-AMD device, switching to default\n");
198                     }
199                 }
200             } else {
201                 av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has format not uspported by AMF, switching to default\n");
202             }
203         }
204     } else if (avctx->hw_device_ctx) {
205         AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
206         if (device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
207             if (device_ctx->hwctx) {
208                 AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->hwctx;
209                 res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
210                 if (res == AMF_OK) {
211                     ctx->hw_device_ctx = av_buffer_ref(avctx->hw_device_ctx);
212                     if (!ctx->hw_device_ctx) {
213                         return AVERROR(ENOMEM);
214                     }
215                 } else {
216                     if (res == AMF_NOT_SUPPORTED)
217                         av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
218                     else
219                         av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has non-AMD device, switching to default\n");
220                 }
221             }
222         }
223     }
224 #endif
225     if (!ctx->hw_frames_ctx && !ctx->hw_device_ctx) {
226         res = ctx->context->pVtbl->InitDX11(ctx->context, NULL, AMF_DX11_1);
227         if (res != AMF_OK) {
228             res = ctx->context->pVtbl->InitDX9(ctx->context, NULL);
229             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "InitDX9() failed with error %d\n", res);
230         }
231     }
232     return 0;
233 }
234
235 static int amf_init_encoder(AVCodecContext *avctx)
236 {
237     AmfContext          *ctx = avctx->priv_data;
238     const wchar_t       *codec_id = NULL;
239     AMF_RESULT           res = AMF_OK;
240
241     switch (avctx->codec->id) {
242         case AV_CODEC_ID_H264:
243             codec_id = AMFVideoEncoderVCE_AVC;
244             break;
245         case AV_CODEC_ID_HEVC:
246             codec_id = AMFVideoEncoder_HEVC;
247             break;
248         default:
249             break;
250     }
251     AMF_RETURN_IF_FALSE(ctx, codec_id != NULL, AVERROR(EINVAL), "Codec %d is not supported\n", avctx->codec->id);
252
253     ctx->format = amf_av_to_amf_format(avctx->pix_fmt);
254     AMF_RETURN_IF_FALSE(ctx, ctx->format != AMF_SURFACE_UNKNOWN, AVERROR(EINVAL), "Format %d is not supported\n", avctx->pix_fmt);
255
256     res = ctx->factory->pVtbl->CreateComponent(ctx->factory, ctx->context, codec_id, &ctx->encoder);
257     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_ENCODER_NOT_FOUND, "CreateComponent(%ls) failed with error %d\n", codec_id, res);
258
259     return 0;
260 }
261
262 int av_cold ff_amf_encode_close(AVCodecContext *avctx)
263 {
264     AmfContext      *ctx = avctx->priv_data;
265     if (ctx->delayed_surface)
266     {
267         ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
268         ctx->delayed_surface = NULL;
269     }
270
271     if (ctx->encoder) {
272         ctx->encoder->pVtbl->Terminate(ctx->encoder);
273         ctx->encoder->pVtbl->Release(ctx->encoder);
274         ctx->encoder = NULL;
275     }
276
277     if (ctx->context) {
278         ctx->context->pVtbl->Terminate(ctx->context);
279         ctx->context->pVtbl->Release(ctx->context);
280         ctx->context = NULL;
281     }
282     av_buffer_unref(&ctx->hw_device_ctx);
283     av_buffer_unref(&ctx->hw_frames_ctx);
284
285     if (ctx->trace) {
286         ctx->trace->pVtbl->UnregisterWriter(ctx->trace, ctx->writer_id);
287     }
288     if (ctx->library) {
289         dlclose(ctx->library);
290         ctx->library = NULL;
291     }
292     ctx->trace = NULL;
293     ctx->debug = NULL;
294     ctx->factory = NULL;
295     ctx->version = 0;
296     ctx->delayed_drain = 0;
297     av_frame_free(&ctx->delayed_frame);
298     av_fifo_free(ctx->timestamp_list);
299     ctx->timestamp_list = NULL;
300     ctx->timestamp_last = 0;
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         int size = av_fifo_size(ctx->timestamp_list);
356         if (INT_MAX / 2 - size < sizeof(timestamp))
357             return AVERROR(EINVAL);
358         av_fifo_realloc2(ctx->timestamp_list, (size + sizeof(timestamp)) * 2);
359     }
360     av_fifo_generic_write(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
361     ctx->timestamp_last = timestamp;
362     return 0;
363 }
364
365 static int amf_copy_buffer(AVCodecContext *avctx, AVPacket *pkt, AMFBuffer *buffer)
366 {
367     AmfContext             *ctx = avctx->priv_data;
368     int                     ret;
369     AMFVariantStruct        var = {0};
370     int64_t                 timestamp = AV_NOPTS_VALUE;
371     int64_t                 size = buffer->pVtbl->GetSize(buffer);
372
373     //if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0) {
374     if  (ret = ff_alloc_packet(pkt, size)) {
375         return ret;
376     }
377     memcpy(pkt->data, buffer->pVtbl->GetNative(buffer), size);
378
379     switch (avctx->codec->id) {
380         case AV_CODEC_ID_H264:
381             buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE, &var);
382             if(var.int64Value == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR) {
383                 pkt->flags = AV_PKT_FLAG_KEY;
384             }
385             break;
386         case AV_CODEC_ID_HEVC:
387             buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE, &var);
388             if (var.int64Value == AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR) {
389                 pkt->flags = AV_PKT_FLAG_KEY;
390             }
391             break;
392         default:
393             break;
394     }
395
396     buffer->pVtbl->GetProperty(buffer, PTS_PROP, &var);
397
398     pkt->pts = var.int64Value; // original pts
399
400
401     AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN, "timestamp_list is empty\n");
402
403     av_fifo_generic_read(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
404
405     // calc dts shift if max_b_frames > 0
406     if (avctx->max_b_frames > 0 && ctx->dts_delay == 0) {
407         AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN,
408             "timestamp_list is empty while max_b_frames = %d\n", avctx->max_b_frames);
409
410         if (timestamp < 0 || ctx->timestamp_last < AV_NOPTS_VALUE) {
411             return AVERROR(ERANGE);
412         }
413         ctx->dts_delay = ctx->timestamp_last - timestamp;
414     }
415     pkt->dts = timestamp - ctx->dts_delay;
416     return 0;
417 }
418
419 // amfenc API implementation
420 int ff_amf_encode_init(AVCodecContext *avctx)
421 {
422     AmfContext     *ctx = avctx->priv_data;
423     int             ret;
424
425     ctx->factory = NULL;
426     ctx->debug = NULL;
427     ctx->trace = NULL;
428     ctx->context = NULL;
429     ctx->encoder = NULL;
430     ctx->library = NULL;
431     ctx->version = 0;
432     ctx->eof = 0;
433     ctx->format = 0;
434     ctx->tracer.vtbl = NULL;
435     ctx->tracer.avctx = NULL;
436
437     if ((ret = amf_load_library(avctx)) == 0) {
438         if ((ret = amf_init_context(avctx)) == 0) {
439             if ((ret = amf_init_encoder(avctx)) == 0) {
440                 return 0;
441             }
442         }
443     }
444     ff_amf_encode_close(avctx);
445     return ret;
446 }
447
448
449 int ff_amf_send_frame(AVCodecContext *avctx, const AVFrame *frame)
450 {
451     AMF_RESULT      res = AMF_OK;
452     AmfContext     *ctx = avctx->priv_data;
453     AMFSurface     *surface = NULL;
454     int             ret;
455
456     if (!ctx->encoder)
457         return AVERROR(EINVAL);
458
459     if (!frame) { // submit drain
460         if (!ctx->eof) { // submit drain one time only
461             if (ctx->delayed_surface != NULL) {
462                 ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
463             } else if(!ctx->delayed_drain) {
464                 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
465                 if (res == AMF_INPUT_FULL) {
466                     ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
467                 } else {
468                     if (res == AMF_OK) {
469                         ctx->eof = 1; // drain started
470                     }
471                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Drain() failed with error %d\n", res);
472                 }
473             }
474         } else{
475             return AVERROR_EOF;
476         }
477     } else { // submit frame
478         if (ctx->delayed_surface != NULL) {
479             return AVERROR(EAGAIN); // should not happen when called from ffmpeg, other clients may resubmit
480         }
481         // prepare surface from frame
482         if (frame->hw_frames_ctx && ( // HW frame detected
483             // check if the same hw_frames_ctx as used in initialization
484             (ctx->hw_frames_ctx && frame->hw_frames_ctx->data == ctx->hw_frames_ctx->data) ||
485             // check if the same hw_device_ctx as used in initialization
486             (ctx->hw_device_ctx && ((AVHWFramesContext*)frame->hw_frames_ctx->data)->device_ctx ==
487             (AVHWDeviceContext*)ctx->hw_device_ctx->data)
488         )) {
489 #if CONFIG_D3D11VA
490             static const GUID AMFTextureArrayIndexGUID = { 0x28115527, 0xe7c3, 0x4b66, { 0x99, 0xd3, 0x4f, 0x2a, 0xe6, 0xb4, 0x7f, 0xaf } };
491             ID3D11Texture2D *texture = (ID3D11Texture2D*)frame->data[0]; // actual texture
492             int index = (int)(size_t)frame->data[1]; // index is a slice in texture array is - set to tell AMF which slice to use
493             texture->lpVtbl->SetPrivateData(texture, &AMFTextureArrayIndexGUID, sizeof(index), &index);
494
495             res = ctx->context->pVtbl->CreateSurfaceFromDX11Native(ctx->context, texture, &surface, NULL); // wrap to AMF surface
496             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "CreateSurfaceFromDX11Native() failed  with error %d\n", res);
497
498             // input HW surfaces can be vertically aligned by 16; tell AMF the real size
499             surface->pVtbl->SetCrop(surface, 0, 0, frame->width, frame->height);
500 #endif
501         } else {
502             res = ctx->context->pVtbl->AllocSurface(ctx->context, AMF_MEMORY_HOST, ctx->format, avctx->width, avctx->height, &surface);
503             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "AllocSurface() failed  with error %d\n", res);
504             amf_copy_surface(avctx, frame, surface);
505         }
506         surface->pVtbl->SetPts(surface, frame->pts);
507         AMF_ASSIGN_PROPERTY_INT64(res, surface, PTS_PROP, frame->pts);
508
509         switch (avctx->codec->id) {
510         case AV_CODEC_ID_H264:
511             AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_INSERT_AUD, !!ctx->aud);
512             break;
513         case AV_CODEC_ID_HEVC:
514             AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_HEVC_INSERT_AUD, !!ctx->aud);
515             break;
516         default:
517             break;
518         }
519
520
521         // submit surface
522         res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)surface);
523         if (res == AMF_INPUT_FULL) { // handle full queue
524             //store surface for later submission
525             ctx->delayed_surface = surface;
526             if (surface->pVtbl->GetMemoryType(surface) == AMF_MEMORY_DX11) {
527                 av_frame_ref(ctx->delayed_frame, frame);
528             }
529         } else {
530             surface->pVtbl->Release(surface);
531             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SubmitInput() failed with error %d\n", res);
532
533             if ((ret = timestamp_queue_enqueue(avctx, frame->pts)) < 0) {
534                 return ret;
535             }
536
537         }
538     }
539     return 0;
540 }
541 int ff_amf_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
542 {
543     int             ret;
544     AMF_RESULT      res;
545     AMF_RESULT      res_query;
546     AmfContext     *ctx = avctx->priv_data;
547     AMFData        *data = NULL;
548     int             block_and_wait;
549
550     if (!ctx->encoder)
551         return AVERROR(EINVAL);
552
553     do {
554         block_and_wait = 0;
555         // poll data
556         res_query = ctx->encoder->pVtbl->QueryOutput(ctx->encoder, &data);
557         if (data) {
558             // copy data to packet
559             AMFBuffer* buffer;
560             AMFGuid guid = IID_AMFBuffer();
561             data->pVtbl->QueryInterface(data, &guid, (void**)&buffer); // query for buffer interface
562             ret = amf_copy_buffer(avctx, avpkt, buffer);
563
564             buffer->pVtbl->Release(buffer);
565             data->pVtbl->Release(data);
566
567             AMF_RETURN_IF_FALSE(ctx, ret >= 0, ret, "amf_copy_buffer() failed with error %d\n", ret);
568
569             if (ctx->delayed_surface != NULL) { // try to resubmit frame
570                 res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)ctx->delayed_surface);
571                 if (res != AMF_INPUT_FULL) {
572                     int64_t pts = ctx->delayed_surface->pVtbl->GetPts(ctx->delayed_surface);
573                     ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
574                     ctx->delayed_surface = NULL;
575                     av_frame_unref(ctx->delayed_frame);
576                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated SubmitInput() failed with error %d\n", res);
577
578                     if ((ret = timestamp_queue_enqueue(avctx, pts)) < 0) {
579                         return ret;
580                     }
581                 } else {
582                     av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed frame submission got AMF_INPUT_FULL- should not happen\n");
583                 }
584             } else if (ctx->delayed_drain) { // try to resubmit drain
585                 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
586                 if (res != AMF_INPUT_FULL) {
587                     ctx->delayed_drain = 0;
588                     ctx->eof = 1; // drain started
589                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated Drain() failed with error %d\n", res);
590                 } else {
591                     av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed drain submission got AMF_INPUT_FULL- should not happen\n");
592                 }
593             }
594         } else if (ctx->delayed_surface != NULL || ctx->delayed_drain || (ctx->eof && res_query != AMF_EOF)) {
595             block_and_wait = 1;
596             av_usleep(1000); // wait and poll again
597         }
598     } while (block_and_wait);
599
600     if (res_query == AMF_EOF) {
601         ret = AVERROR_EOF;
602     } else if (data == NULL) {
603         ret = AVERROR(EAGAIN);
604     } else {
605         ret = 0;
606     }
607     return ret;
608 }