]> git.sesse.net Git - ffmpeg/blob - libavcodec/amfenc.c
Drop Windows XP support remnants
[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 LIBAV_AMF_WRITER_ID L"libav_log"
50
51 #define PTS_PROP L"PtsProp"
52
53 const enum AVPixelFormat ff_amf_pix_fmts[] = {
54     AV_PIX_FMT_NV12,
55     AV_PIX_FMT_YUV420P,
56 #if CONFIG_D3D11VA
57     AV_PIX_FMT_D3D11,
58 #endif
59     AV_PIX_FMT_NONE
60 };
61
62 typedef struct FormatMap {
63     enum AVPixelFormat       av_format;
64     enum AMF_SURFACE_FORMAT  amf_format;
65 } FormatMap;
66
67 static const FormatMap format_map[] =
68 {
69     { AV_PIX_FMT_NONE,       AMF_SURFACE_UNKNOWN },
70     { AV_PIX_FMT_NV12,       AMF_SURFACE_NV12 },
71 //    { AV_PIX_FMT_BGR0,       AMF_SURFACE_BGRA },
72 //    { AV_PIX_FMT_RGB0,       AMF_SURFACE_RGBA },
73     { AV_PIX_FMT_GRAY8,      AMF_SURFACE_GRAY8 },
74     { AV_PIX_FMT_YUV420P,    AMF_SURFACE_YUV420P },
75     { AV_PIX_FMT_YUYV422,    AMF_SURFACE_YUY2 },
76     { AV_PIX_FMT_D3D11,      AMF_SURFACE_NV12 },
77 };
78
79
80 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
81 {
82     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
83     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
84 }
85
86
87 static enum AMF_SURFACE_FORMAT amf_av_to_amf_format(enum AVPixelFormat fmt)
88 {
89     int i;
90     for (i = 0; i < amf_countof(format_map); i++) {
91         if (format_map[i].av_format == fmt) {
92             return format_map[i].amf_format;
93         }
94     }
95     return AMF_SURFACE_UNKNOWN;
96 }
97
98 static void AMF_CDECL_CALL AMFTraceWriter_Write(AMFTraceWriter *pThis,
99     const wchar_t *scope, const wchar_t *message)
100 {
101     AmfTraceWriter *tracer = (AmfTraceWriter*)pThis;
102     av_log(tracer->avctx, AV_LOG_DEBUG, "%ls: %ls", scope, message); // \n is provided from AMF
103 }
104
105 static void AMF_CDECL_CALL AMFTraceWriter_Flush(AMFTraceWriter *pThis)
106 {
107 }
108
109 static AMFTraceWriterVtbl tracer_vtbl =
110 {
111     .Write = AMFTraceWriter_Write,
112     .Flush = AMFTraceWriter_Flush,
113 };
114
115 static int amf_load_library(AVCodecContext *avctx)
116 {
117     AmfContext             *ctx = avctx->priv_data;
118     AMFInit_Fn              init_fun = NULL;
119     AMFQueryVersion_Fn      version_fun = NULL;
120     AMF_RESULT              res = AMF_OK;
121
122     ctx->eof = 0;
123     ctx->delayed_drain = 0;
124     ctx->hw_frames_ctx = NULL;
125     ctx->hw_device_ctx = NULL;
126     ctx->delayed_surface = NULL;
127     ctx->delayed_frame = av_frame_alloc();
128     if (!ctx->delayed_frame) {
129         return AVERROR(ENOMEM);
130     }
131     // hardcoded to current HW queue size - will realloc in timestamp_queue_enqueue() if too small
132     ctx->timestamp_list = av_fifo_alloc((avctx->max_b_frames + 16) * sizeof(int64_t));
133     if (!ctx->timestamp_list) {
134         return AVERROR(ENOMEM);
135     }
136     ctx->dts_delay = 0;
137
138
139     ctx->library = dlopen(AMF_DLL_NAMEA, RTLD_NOW | RTLD_LOCAL);
140     AMF_RETURN_IF_FALSE(ctx, ctx->library != NULL,
141         AVERROR_UNKNOWN, "DLL %s failed to open\n", AMF_DLL_NAMEA);
142
143     init_fun = (AMFInit_Fn)dlsym(ctx->library, AMF_INIT_FUNCTION_NAME);
144     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);
145
146     version_fun = (AMFQueryVersion_Fn)dlsym(ctx->library, AMF_QUERY_VERSION_FUNCTION_NAME);
147     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);
148
149     res = version_fun(&ctx->version);
150     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_QUERY_VERSION_FUNCTION_NAME, res);
151     res = init_fun(AMF_FULL_VERSION, &ctx->factory);
152     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_INIT_FUNCTION_NAME, res);
153     res = ctx->factory->pVtbl->GetTrace(ctx->factory, &ctx->trace);
154     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetTrace() failed with error %d\n", res);
155     res = ctx->factory->pVtbl->GetDebug(ctx->factory, &ctx->debug);
156     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetDebug() failed with error %d\n", res);
157     return 0;
158 }
159
160 static int amf_init_context(AVCodecContext *avctx)
161 {
162     AmfContext         *ctx = avctx->priv_data;
163     AMF_RESULT          res = AMF_OK;
164
165     // configure AMF logger
166     // the return of these functions indicates old state and do not affect behaviour
167     ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, ctx->log_to_dbg != 0 );
168     if (ctx->log_to_dbg)
169         ctx->trace->pVtbl->SetWriterLevel(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, AMF_TRACE_TRACE);
170     ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_CONSOLE, 0);
171     ctx->trace->pVtbl->SetGlobalLevel(ctx->trace, AMF_TRACE_TRACE);
172
173     // connect AMF logger to av_log
174     ctx->tracer.vtbl = &tracer_vtbl;
175     ctx->tracer.avctx = avctx;
176     ctx->trace->pVtbl->RegisterWriter(ctx->trace, LIBAV_AMF_WRITER_ID,(AMFTraceWriter *)&ctx->tracer, 1);
177     ctx->trace->pVtbl->SetWriterLevel(ctx->trace, LIBAV_AMF_WRITER_ID, AMF_TRACE_TRACE);
178
179     res = ctx->factory->pVtbl->CreateContext(ctx->factory, &ctx->context);
180     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "CreateContext() failed with error %d\n", res);
181     // try to reuse existing DX device
182 #if CONFIG_D3D11VA
183     if (avctx->hw_frames_ctx) {
184         AVHWFramesContext *device_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
185         if (device_ctx->device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
186             if (amf_av_to_amf_format(device_ctx->sw_format) != AMF_SURFACE_UNKNOWN) {
187                 if (device_ctx->device_ctx->hwctx) {
188                     AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->device_ctx->hwctx;
189                     res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
190                     if (res == AMF_OK) {
191                         ctx->hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
192                         if (!ctx->hw_frames_ctx) {
193                             return AVERROR(ENOMEM);
194                         }
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, LIBAV_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_free(ctx->timestamp_list);
301     ctx->timestamp_list = NULL;
302     ctx->timestamp_last = 0;
303
304     return 0;
305 }
306
307 static int amf_copy_surface(AVCodecContext *avctx, const AVFrame *frame,
308     AMFSurface* surface)
309 {
310     AVFrame        *sw_frame = NULL;
311     AMFPlane       *plane = NULL;
312     uint8_t        *dst_data[4];
313     int             dst_linesize[4];
314     int             ret = 0;
315     int             planes;
316     int             i;
317
318     if (frame->hw_frames_ctx && is_hwaccel_pix_fmt(frame->format)) {
319         if (!(sw_frame = av_frame_alloc())) {
320             av_log(avctx, AV_LOG_ERROR, "Can not alloc frame\n");
321             ret = AVERROR(ENOMEM);
322             goto fail;
323         }
324         if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
325             av_log(avctx, AV_LOG_ERROR, "Error transferring the data to system memory\n");
326             goto fail;
327         }
328         frame = sw_frame;
329     }
330     planes = (int)surface->pVtbl->GetPlanesCount(surface);
331     if (planes > amf_countof(dst_data)) {
332         av_log(avctx, AV_LOG_ERROR, "Invalid number of planes %d in surface\n", planes);
333         ret = AVERROR(EINVAL);
334         goto fail;
335     }
336
337     for (i = 0; i < planes; i++) {
338         plane = surface->pVtbl->GetPlaneAt(surface, i);
339         dst_data[i] = plane->pVtbl->GetNative(plane);
340         dst_linesize[i] = plane->pVtbl->GetHPitch(plane);
341     }
342     av_image_copy(dst_data, dst_linesize,
343         (const uint8_t**)frame->data, frame->linesize, frame->format,
344         avctx->width, avctx->height);
345
346 fail:
347     if (sw_frame) {
348         av_frame_free(&sw_frame);
349     }
350     return ret;
351 }
352
353 static inline int timestamp_queue_enqueue(AVCodecContext *avctx, int64_t timestamp)
354 {
355     AmfContext         *ctx = avctx->priv_data;
356     if (av_fifo_space(ctx->timestamp_list) < sizeof(timestamp)) {
357         int size = av_fifo_size(ctx->timestamp_list);
358         if (INT_MAX / 2 - size < sizeof(timestamp))
359             return AVERROR(EINVAL);
360         av_fifo_realloc2(ctx->timestamp_list, (size + sizeof(timestamp)) * 2);
361     }
362     av_fifo_generic_write(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
363     ctx->timestamp_last = timestamp;
364     return 0;
365 }
366
367 static int amf_copy_buffer(AVCodecContext *avctx, AVPacket *pkt, AMFBuffer *buffer)
368 {
369     AmfContext             *ctx = avctx->priv_data;
370     int                     ret;
371     AMFVariantStruct        var = {0};
372     int64_t                 timestamp = AV_NOPTS_VALUE;
373     int64_t                 size = buffer->pVtbl->GetSize(buffer);
374
375     //if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0) {
376     if  (ret = ff_alloc_packet(pkt, size)) {
377         return ret;
378     }
379     memcpy(pkt->data, buffer->pVtbl->GetNative(buffer), size);
380
381     switch (avctx->codec->id) {
382         case AV_CODEC_ID_H264:
383             buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE, &var);
384             if(var.int64Value == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR) {
385                 pkt->flags = AV_PKT_FLAG_KEY;
386             }
387             break;
388         case AV_CODEC_ID_HEVC:
389             buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE, &var);
390             if (var.int64Value == AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR) {
391                 pkt->flags = AV_PKT_FLAG_KEY;
392             }
393             break;
394         default:
395             break;
396     }
397
398     buffer->pVtbl->GetProperty(buffer, PTS_PROP, &var);
399
400     pkt->pts = var.int64Value; // original pts
401
402
403     AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN, "timestamp_list is empty\n");
404
405     av_fifo_generic_read(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
406
407     // calc dts shift if max_b_frames > 0
408     if (avctx->max_b_frames > 0 && ctx->dts_delay == 0) {
409         AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN,
410             "timestamp_list is empty while max_b_frames = %d\n", avctx->max_b_frames);
411
412         if (timestamp < 0 || ctx->timestamp_last < AV_NOPTS_VALUE) {
413             return AVERROR(ERANGE);
414         }
415         ctx->dts_delay = ctx->timestamp_last - timestamp;
416     }
417     pkt->dts = timestamp - ctx->dts_delay;
418     return 0;
419 }
420
421 // amfenc API implementation
422 int ff_amf_encode_init(AVCodecContext *avctx)
423 {
424     AmfContext     *ctx = avctx->priv_data;
425     int             ret;
426
427     ctx->factory = NULL;
428     ctx->debug = NULL;
429     ctx->trace = NULL;
430     ctx->context = NULL;
431     ctx->encoder = NULL;
432     ctx->library = NULL;
433     ctx->version = 0;
434     ctx->eof = 0;
435     ctx->format = 0;
436     ctx->tracer.vtbl = NULL;
437     ctx->tracer.avctx = NULL;
438
439     if ((ret = amf_load_library(avctx)) == 0) {
440         if ((ret = amf_init_context(avctx)) == 0) {
441             if ((ret = amf_init_encoder(avctx)) == 0) {
442                 return 0;
443             }
444         }
445     }
446     ff_amf_encode_close(avctx);
447     return ret;
448 }
449
450
451 int ff_amf_send_frame(AVCodecContext *avctx, const AVFrame *frame)
452 {
453     AMF_RESULT      res = AMF_OK;
454     AmfContext     *ctx = avctx->priv_data;
455     AMFSurface     *surface = NULL;
456     int             ret;
457
458     if (!ctx->encoder)
459         return AVERROR(EINVAL);
460
461     if (!frame) { // submit drain
462         if (!ctx->eof) { // submit drain one time only
463             if (ctx->delayed_surface != NULL) {
464                 ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
465             } else if(!ctx->delayed_drain) {
466                 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
467                 if (res == AMF_INPUT_FULL) {
468                     ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
469                 } else {
470                     if (res == AMF_OK) {
471                         ctx->eof = 1; // drain started
472                     }
473                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Drain() failed with error %d\n", res);
474                 }
475             }
476         } else{
477             return AVERROR_EOF;
478         }
479     } else { // submit frame
480         if (ctx->delayed_surface != NULL) {
481             return AVERROR(EAGAIN); // should not happen when called from ffmpeg, other clients may resubmit
482         }
483         // prepare surface from frame
484         if (frame->hw_frames_ctx && ( // HW frame detected
485             // check if the same hw_frames_ctx as used in initialization
486             (ctx->hw_frames_ctx && frame->hw_frames_ctx->data == ctx->hw_frames_ctx->data) ||
487             // check if the same hw_device_ctx as used in initialization
488             (ctx->hw_device_ctx && ((AVHWFramesContext*)frame->hw_frames_ctx->data)->device_ctx ==
489             (AVHWDeviceContext*)ctx->hw_device_ctx->data)
490         )) {
491 #if CONFIG_D3D11VA
492             static const GUID AMFTextureArrayIndexGUID = { 0x28115527, 0xe7c3, 0x4b66, { 0x99, 0xd3, 0x4f, 0x2a, 0xe6, 0xb4, 0x7f, 0xaf } };
493             ID3D11Texture2D *texture = (ID3D11Texture2D*)frame->data[0]; // actual texture
494             int index = (int)(size_t)frame->data[1]; // index is a slice in texture array is - set to tell AMF which slice to use
495             texture->lpVtbl->SetPrivateData(texture, &AMFTextureArrayIndexGUID, sizeof(index), &index);
496
497             res = ctx->context->pVtbl->CreateSurfaceFromDX11Native(ctx->context, texture, &surface, NULL); // wrap to AMF surface
498             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "CreateSurfaceFromDX11Native() failed  with error %d\n", res);
499
500             // input HW surfaces can be vertically aligned by 16; tell AMF the real size
501             surface->pVtbl->SetCrop(surface, 0, 0, frame->width, frame->height);
502 #endif
503         } else {
504             res = ctx->context->pVtbl->AllocSurface(ctx->context, AMF_MEMORY_HOST, ctx->format, avctx->width, avctx->height, &surface);
505             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "AllocSurface() failed  with error %d\n", res);
506             amf_copy_surface(avctx, frame, surface);
507         }
508         surface->pVtbl->SetPts(surface, frame->pts);
509         AMF_ASSIGN_PROPERTY_INT64(res, surface, PTS_PROP, frame->pts);
510
511         switch (avctx->codec->id) {
512         case AV_CODEC_ID_H264:
513             AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_INSERT_AUD, !!ctx->aud);
514             break;
515         case AV_CODEC_ID_HEVC:
516             AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_HEVC_INSERT_AUD, !!ctx->aud);
517             break;
518         default:
519             break;
520         }
521
522
523         // submit surface
524         res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)surface);
525         if (res == AMF_INPUT_FULL) { // handle full queue
526             //store surface for later submission
527             ctx->delayed_surface = surface;
528             if (surface->pVtbl->GetMemoryType(surface) == AMF_MEMORY_DX11) {
529                 av_frame_ref(ctx->delayed_frame, frame);
530             }
531         } else {
532             surface->pVtbl->Release(surface);
533             AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SubmitInput() failed with error %d\n", res);
534
535             if ((ret = timestamp_queue_enqueue(avctx, frame->pts)) < 0) {
536                 return ret;
537             }
538
539         }
540     }
541     return 0;
542 }
543 int ff_amf_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
544 {
545     int             ret;
546     AMF_RESULT      res;
547     AMF_RESULT      res_query;
548     AmfContext     *ctx = avctx->priv_data;
549     AMFData        *data = NULL;
550     int             block_and_wait;
551
552     if (!ctx->encoder)
553         return AVERROR(EINVAL);
554
555     do {
556         block_and_wait = 0;
557         // poll data
558         res_query = ctx->encoder->pVtbl->QueryOutput(ctx->encoder, &data);
559         if (data) {
560             // copy data to packet
561             AMFBuffer* buffer;
562             AMFGuid guid = IID_AMFBuffer();
563             data->pVtbl->QueryInterface(data, &guid, (void**)&buffer); // query for buffer interface
564             ret = amf_copy_buffer(avctx, avpkt, buffer);
565
566             buffer->pVtbl->Release(buffer);
567             data->pVtbl->Release(data);
568
569             AMF_RETURN_IF_FALSE(ctx, ret >= 0, ret, "amf_copy_buffer() failed with error %d\n", ret);
570
571             if (ctx->delayed_surface != NULL) { // try to resubmit frame
572                 res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)ctx->delayed_surface);
573                 if (res != AMF_INPUT_FULL) {
574                     int64_t pts = ctx->delayed_surface->pVtbl->GetPts(ctx->delayed_surface);
575                     ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
576                     ctx->delayed_surface = NULL;
577                     av_frame_unref(ctx->delayed_frame);
578                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated SubmitInput() failed with error %d\n", res);
579
580                     if ((ret = timestamp_queue_enqueue(avctx, pts)) < 0) {
581                         return ret;
582                     }
583                 } else {
584                     av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed frame submission got AMF_INPUT_FULL- should not happen\n");
585                 }
586             } else if (ctx->delayed_drain) { // try to resubmit drain
587                 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
588                 if (res != AMF_INPUT_FULL) {
589                     ctx->delayed_drain = 0;
590                     ctx->eof = 1; // drain started
591                     AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated Drain() failed with error %d\n", res);
592                 } else {
593                     av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed drain submission got AMF_INPUT_FULL- should not happen\n");
594                 }
595             }
596         } else if (ctx->delayed_surface != NULL || ctx->delayed_drain || (ctx->eof && res_query != AMF_EOF)) {
597             block_and_wait = 1;
598             av_usleep(1000); // wait and poll again
599         }
600     } while (block_and_wait);
601
602     if (res_query == AMF_EOF) {
603         ret = AVERROR_EOF;
604     } else if (data == NULL) {
605         ret = AVERROR(EAGAIN);
606     } else {
607         ret = 0;
608     }
609     return ret;
610 }