amfenc: Retain a reference to D3D frames used as input during the encoding process
[libav.git] / 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 ctx->hwsurfaces_in_queue = 0;
166 ctx->hwsurfaces_in_queue_max = 16;
167
168 // configure AMF logger
169 // the return of these functions indicates old state and do not affect behaviour
170 ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, ctx->log_to_dbg != 0 );
171 if (ctx->log_to_dbg)
172 ctx->trace->pVtbl->SetWriterLevel(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, AMF_TRACE_TRACE);
173 ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_CONSOLE, 0);
174 ctx->trace->pVtbl->SetGlobalLevel(ctx->trace, AMF_TRACE_TRACE);
175
176 // connect AMF logger to av_log
177 ctx->tracer.vtbl = &tracer_vtbl;
178 ctx->tracer.avctx = avctx;
179 ctx->trace->pVtbl->RegisterWriter(ctx->trace, LIBAV_AMF_WRITER_ID,(AMFTraceWriter *)&ctx->tracer, 1);
180 ctx->trace->pVtbl->SetWriterLevel(ctx->trace, LIBAV_AMF_WRITER_ID, AMF_TRACE_TRACE);
181
182 res = ctx->factory->pVtbl->CreateContext(ctx->factory, &ctx->context);
183 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "CreateContext() failed with error %d\n", res);
184 // try to reuse existing DX device
185 #if CONFIG_D3D11VA
186 if (avctx->hw_frames_ctx) {
187 AVHWFramesContext *device_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
188 if (device_ctx->device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
189 if (amf_av_to_amf_format(device_ctx->sw_format) != AMF_SURFACE_UNKNOWN) {
190 if (device_ctx->device_ctx->hwctx) {
191 AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->device_ctx->hwctx;
192 res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
193 if (res == AMF_OK) {
194 ctx->hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
195 if (!ctx->hw_frames_ctx) {
196 return AVERROR(ENOMEM);
197 }
198 if (device_ctx->initial_pool_size > 0)
199 ctx->hwsurfaces_in_queue_max = device_ctx->initial_pool_size - 1;
200 } else {
201 if(res == AMF_NOT_SUPPORTED)
202 av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
203 else
204 av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has non-AMD device, switching to default\n");
205 }
206 }
207 } else {
208 av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has format not uspported by AMF, switching to default\n");
209 }
210 }
211 } else if (avctx->hw_device_ctx) {
212 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
213 if (device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
214 if (device_ctx->hwctx) {
215 AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->hwctx;
216 res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
217 if (res == AMF_OK) {
218 ctx->hw_device_ctx = av_buffer_ref(avctx->hw_device_ctx);
219 if (!ctx->hw_device_ctx) {
220 return AVERROR(ENOMEM);
221 }
222 } else {
223 if (res == AMF_NOT_SUPPORTED)
224 av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
225 else
226 av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has non-AMD device, switching to default\n");
227 }
228 }
229 }
230 }
231 #endif
232 if (!ctx->hw_frames_ctx && !ctx->hw_device_ctx) {
233 res = ctx->context->pVtbl->InitDX11(ctx->context, NULL, AMF_DX11_1);
234 if (res != AMF_OK) {
235 res = ctx->context->pVtbl->InitDX9(ctx->context, NULL);
236 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "InitDX9() failed with error %d\n", res);
237 }
238 }
239 return 0;
240 }
241
242 static int amf_init_encoder(AVCodecContext *avctx)
243 {
244 AmfContext *ctx = avctx->priv_data;
245 const wchar_t *codec_id = NULL;
246 AMF_RESULT res = AMF_OK;
247
248 switch (avctx->codec->id) {
249 case AV_CODEC_ID_H264:
250 codec_id = AMFVideoEncoderVCE_AVC;
251 break;
252 case AV_CODEC_ID_HEVC:
253 codec_id = AMFVideoEncoder_HEVC;
254 break;
255 default:
256 break;
257 }
258 AMF_RETURN_IF_FALSE(ctx, codec_id != NULL, AVERROR(EINVAL), "Codec %d is not supported\n", avctx->codec->id);
259
260 ctx->format = amf_av_to_amf_format(avctx->pix_fmt);
261 AMF_RETURN_IF_FALSE(ctx, ctx->format != AMF_SURFACE_UNKNOWN, AVERROR(EINVAL), "Format %d is not supported\n", avctx->pix_fmt);
262
263 res = ctx->factory->pVtbl->CreateComponent(ctx->factory, ctx->context, codec_id, &ctx->encoder);
264 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_ENCODER_NOT_FOUND, "CreateComponent(%ls) failed with error %d\n", codec_id, res);
265
266 return 0;
267 }
268
269 int av_cold ff_amf_encode_close(AVCodecContext *avctx)
270 {
271 AmfContext *ctx = avctx->priv_data;
272 if (ctx->delayed_surface)
273 {
274 ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
275 ctx->delayed_surface = NULL;
276 }
277
278 if (ctx->encoder) {
279 ctx->encoder->pVtbl->Terminate(ctx->encoder);
280 ctx->encoder->pVtbl->Release(ctx->encoder);
281 ctx->encoder = NULL;
282 }
283
284 if (ctx->context) {
285 ctx->context->pVtbl->Terminate(ctx->context);
286 ctx->context->pVtbl->Release(ctx->context);
287 ctx->context = NULL;
288 }
289 av_buffer_unref(&ctx->hw_device_ctx);
290 av_buffer_unref(&ctx->hw_frames_ctx);
291
292 if (ctx->trace) {
293 ctx->trace->pVtbl->UnregisterWriter(ctx->trace, LIBAV_AMF_WRITER_ID);
294 }
295 if (ctx->library) {
296 dlclose(ctx->library);
297 ctx->library = NULL;
298 }
299 ctx->trace = NULL;
300 ctx->debug = NULL;
301 ctx->factory = NULL;
302 ctx->version = 0;
303 ctx->delayed_drain = 0;
304 av_frame_free(&ctx->delayed_frame);
305 av_fifo_free(ctx->timestamp_list);
306 ctx->timestamp_list = NULL;
307 ctx->timestamp_last = 0;
308
309 return 0;
310 }
311
312 static int amf_copy_surface(AVCodecContext *avctx, const AVFrame *frame,
313 AMFSurface* surface)
314 {
315 AVFrame *sw_frame = NULL;
316 AMFPlane *plane = NULL;
317 uint8_t *dst_data[4];
318 int dst_linesize[4];
319 int ret = 0;
320 int planes;
321 int i;
322
323 if (frame->hw_frames_ctx && is_hwaccel_pix_fmt(frame->format)) {
324 if (!(sw_frame = av_frame_alloc())) {
325 av_log(avctx, AV_LOG_ERROR, "Can not alloc frame\n");
326 ret = AVERROR(ENOMEM);
327 goto fail;
328 }
329 if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
330 av_log(avctx, AV_LOG_ERROR, "Error transferring the data to system memory\n");
331 goto fail;
332 }
333 frame = sw_frame;
334 }
335 planes = (int)surface->pVtbl->GetPlanesCount(surface);
336 if (planes > amf_countof(dst_data)) {
337 av_log(avctx, AV_LOG_ERROR, "Invalid number of planes %d in surface\n", planes);
338 ret = AVERROR(EINVAL);
339 goto fail;
340 }
341
342 for (i = 0; i < planes; i++) {
343 plane = surface->pVtbl->GetPlaneAt(surface, i);
344 dst_data[i] = plane->pVtbl->GetNative(plane);
345 dst_linesize[i] = plane->pVtbl->GetHPitch(plane);
346 }
347 av_image_copy(dst_data, dst_linesize,
348 (const uint8_t**)frame->data, frame->linesize, frame->format,
349 avctx->width, avctx->height);
350
351 fail:
352 if (sw_frame) {
353 av_frame_free(&sw_frame);
354 }
355 return ret;
356 }
357
358 static inline int timestamp_queue_enqueue(AVCodecContext *avctx, int64_t timestamp)
359 {
360 AmfContext *ctx = avctx->priv_data;
361 if (av_fifo_space(ctx->timestamp_list) < sizeof(timestamp)) {
362 int size = av_fifo_size(ctx->timestamp_list);
363 if (INT_MAX / 2 - size < sizeof(timestamp))
364 return AVERROR(EINVAL);
365 av_fifo_realloc2(ctx->timestamp_list, (size + sizeof(timestamp)) * 2);
366 }
367 av_fifo_generic_write(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
368 ctx->timestamp_last = timestamp;
369 return 0;
370 }
371
372 static int amf_copy_buffer(AVCodecContext *avctx, AVPacket *pkt, AMFBuffer *buffer)
373 {
374 AmfContext *ctx = avctx->priv_data;
375 int ret;
376 AMFVariantStruct var = {0};
377 int64_t timestamp = AV_NOPTS_VALUE;
378 int64_t size = buffer->pVtbl->GetSize(buffer);
379
380 //if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0) {
381 if (ret = ff_alloc_packet(pkt, size)) {
382 return ret;
383 }
384 memcpy(pkt->data, buffer->pVtbl->GetNative(buffer), size);
385
386 switch (avctx->codec->id) {
387 case AV_CODEC_ID_H264:
388 buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE, &var);
389 if(var.int64Value == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR) {
390 pkt->flags = AV_PKT_FLAG_KEY;
391 }
392 break;
393 case AV_CODEC_ID_HEVC:
394 buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE, &var);
395 if (var.int64Value == AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR) {
396 pkt->flags = AV_PKT_FLAG_KEY;
397 }
398 break;
399 default:
400 break;
401 }
402
403 buffer->pVtbl->GetProperty(buffer, PTS_PROP, &var);
404
405 pkt->pts = var.int64Value; // original pts
406
407
408 AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN, "timestamp_list is empty\n");
409
410 av_fifo_generic_read(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
411
412 // calc dts shift if max_b_frames > 0
413 if (avctx->max_b_frames > 0 && ctx->dts_delay == 0) {
414 AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN,
415 "timestamp_list is empty while max_b_frames = %d\n", avctx->max_b_frames);
416
417 if (timestamp < 0 || ctx->timestamp_last < AV_NOPTS_VALUE) {
418 return AVERROR(ERANGE);
419 }
420 ctx->dts_delay = ctx->timestamp_last - timestamp;
421 }
422 pkt->dts = timestamp - ctx->dts_delay;
423 return 0;
424 }
425
426 // amfenc API implementation
427 int ff_amf_encode_init(AVCodecContext *avctx)
428 {
429 AmfContext *ctx = avctx->priv_data;
430 int ret;
431
432 ctx->factory = NULL;
433 ctx->debug = NULL;
434 ctx->trace = NULL;
435 ctx->context = NULL;
436 ctx->encoder = NULL;
437 ctx->library = NULL;
438 ctx->version = 0;
439 ctx->eof = 0;
440 ctx->format = 0;
441 ctx->tracer.vtbl = NULL;
442 ctx->tracer.avctx = NULL;
443
444 if ((ret = amf_load_library(avctx)) == 0) {
445 if ((ret = amf_init_context(avctx)) == 0) {
446 if ((ret = amf_init_encoder(avctx)) == 0) {
447 return 0;
448 }
449 }
450 }
451 ff_amf_encode_close(avctx);
452 return ret;
453 }
454
455 static AMF_RESULT amf_set_property_buffer(AMFSurface *object, const wchar_t *name, AMFBuffer *val)
456 {
457 AMF_RESULT res;
458 AMFVariantStruct var;
459 res = AMFVariantInit(&var);
460 if (res == AMF_OK) {
461 AMFGuid guid_AMFInterface = IID_AMFInterface();
462 AMFInterface *amf_interface;
463 res = val->pVtbl->QueryInterface(val, &guid_AMFInterface, (void**)&amf_interface);
464
465 if (res == AMF_OK) {
466 res = AMFVariantAssignInterface(&var, amf_interface);
467 amf_interface->pVtbl->Release(amf_interface);
468 }
469 if (res == AMF_OK) {
470 res = object->pVtbl->SetProperty(object, name, var);
471 }
472 AMFVariantClear(&var);
473 }
474 return res;
475 }
476
477 static AMF_RESULT amf_get_property_buffer(AMFData *object, const wchar_t *name, AMFBuffer **val)
478 {
479 AMF_RESULT res;
480 AMFVariantStruct var;
481 res = AMFVariantInit(&var);
482 if (res == AMF_OK) {
483 res = object->pVtbl->GetProperty(object, name, &var);
484 if (res == AMF_OK) {
485 if (var.type == AMF_VARIANT_INTERFACE) {
486 AMFGuid guid_AMFBuffer = IID_AMFBuffer();
487 AMFInterface *amf_interface = AMFVariantInterface(&var);
488 res = amf_interface->pVtbl->QueryInterface(amf_interface, &guid_AMFBuffer, (void**)val);
489 } else {
490 res = AMF_INVALID_DATA_TYPE;
491 }
492 }
493 AMFVariantClear(&var);
494 }
495 return res;
496 }
497
498 static AMFBuffer *amf_create_buffer_with_frame_ref(const AVFrame *frame, AMFContext *context)
499 {
500 AVFrame *frame_ref;
501 AMFBuffer *frame_ref_storage_buffer = NULL;
502 AMF_RESULT res;
503
504 res = context->pVtbl->AllocBuffer(context, AMF_MEMORY_HOST, sizeof(frame_ref), &frame_ref_storage_buffer);
505 if (res == AMF_OK) {
506 frame_ref = av_frame_clone(frame);
507 if (frame_ref) {
508 memcpy(frame_ref_storage_buffer->pVtbl->GetNative(frame_ref_storage_buffer), &frame_ref, sizeof(frame_ref));
509 } else {
510 frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
511 frame_ref_storage_buffer = NULL;
512 }
513 }
514 return frame_ref_storage_buffer;
515 }
516
517 static void amf_release_buffer_with_frame_ref(AMFBuffer *frame_ref_storage_buffer)
518 {
519 AVFrame *av_frame_ref;
520 memcpy(&av_frame_ref, frame_ref_storage_buffer->pVtbl->GetNative(frame_ref_storage_buffer), sizeof(av_frame_ref));
521 av_frame_free(&av_frame_ref);
522 frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
523 }
524
525 int ff_amf_send_frame(AVCodecContext *avctx, const AVFrame *frame)
526 {
527 AMF_RESULT res = AMF_OK;
528 AmfContext *ctx = avctx->priv_data;
529 AMFSurface *surface = NULL;
530 int ret;
531
532 if (!ctx->encoder)
533 return AVERROR(EINVAL);
534
535 if (!frame) { // submit drain
536 if (!ctx->eof) { // submit drain one time only
537 if (ctx->delayed_surface != NULL) {
538 ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
539 } else if(!ctx->delayed_drain) {
540 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
541 if (res == AMF_INPUT_FULL) {
542 ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
543 } else {
544 if (res == AMF_OK) {
545 ctx->eof = 1; // drain started
546 }
547 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Drain() failed with error %d\n", res);
548 }
549 }
550 } else{
551 return AVERROR_EOF;
552 }
553 } else { // submit frame
554 if (ctx->delayed_surface != NULL) {
555 return AVERROR(EAGAIN); // should not happen when called from ffmpeg, other clients may resubmit
556 }
557 // prepare surface from frame
558 if (frame->hw_frames_ctx && ( // HW frame detected
559 // check if the same hw_frames_ctx as used in initialization
560 (ctx->hw_frames_ctx && frame->hw_frames_ctx->data == ctx->hw_frames_ctx->data) ||
561 // check if the same hw_device_ctx as used in initialization
562 (ctx->hw_device_ctx && ((AVHWFramesContext*)frame->hw_frames_ctx->data)->device_ctx ==
563 (AVHWDeviceContext*)ctx->hw_device_ctx->data)
564 )) {
565 AMFBuffer *frame_ref_storage_buffer;
566
567 #if CONFIG_D3D11VA
568 static const GUID AMFTextureArrayIndexGUID = { 0x28115527, 0xe7c3, 0x4b66, { 0x99, 0xd3, 0x4f, 0x2a, 0xe6, 0xb4, 0x7f, 0xaf } };
569 ID3D11Texture2D *texture = (ID3D11Texture2D*)frame->data[0]; // actual texture
570 int index = (int)(size_t)frame->data[1]; // index is a slice in texture array is - set to tell AMF which slice to use
571 texture->lpVtbl->SetPrivateData(texture, &AMFTextureArrayIndexGUID, sizeof(index), &index);
572
573 res = ctx->context->pVtbl->CreateSurfaceFromDX11Native(ctx->context, texture, &surface, NULL); // wrap to AMF surface
574 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "CreateSurfaceFromDX11Native() failed with error %d\n", res);
575
576 // input HW surfaces can be vertically aligned by 16; tell AMF the real size
577 surface->pVtbl->SetCrop(surface, 0, 0, frame->width, frame->height);
578 #endif
579
580 frame_ref_storage_buffer = amf_create_buffer_with_frame_ref(frame, ctx->context);
581 AMF_RETURN_IF_FALSE(ctx, frame_ref_storage_buffer != NULL, AVERROR(ENOMEM), "create_buffer_with_frame_ref() returned NULL\n");
582
583 res = amf_set_property_buffer(surface, L"av_frame_ref", frame_ref_storage_buffer);
584 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SetProperty failed for \"av_frame_ref\" with error %d\n", res);
585 ctx->hwsurfaces_in_queue++;
586 frame_ref_storage_buffer->pVtbl->Release(frame_ref_storage_buffer);
587 } else {
588 res = ctx->context->pVtbl->AllocSurface(ctx->context, AMF_MEMORY_HOST, ctx->format, avctx->width, avctx->height, &surface);
589 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "AllocSurface() failed with error %d\n", res);
590 amf_copy_surface(avctx, frame, surface);
591 }
592 surface->pVtbl->SetPts(surface, frame->pts);
593 AMF_ASSIGN_PROPERTY_INT64(res, surface, PTS_PROP, frame->pts);
594
595 switch (avctx->codec->id) {
596 case AV_CODEC_ID_H264:
597 AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_INSERT_AUD, !!ctx->aud);
598 break;
599 case AV_CODEC_ID_HEVC:
600 AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_HEVC_INSERT_AUD, !!ctx->aud);
601 break;
602 default:
603 break;
604 }
605
606
607 // submit surface
608 res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)surface);
609 if (res == AMF_INPUT_FULL) { // handle full queue
610 //store surface for later submission
611 ctx->delayed_surface = surface;
612 if (surface->pVtbl->GetMemoryType(surface) == AMF_MEMORY_DX11) {
613 av_frame_ref(ctx->delayed_frame, frame);
614 }
615 } else {
616 surface->pVtbl->Release(surface);
617 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SubmitInput() failed with error %d\n", res);
618
619 if ((ret = timestamp_queue_enqueue(avctx, frame->pts)) < 0) {
620 return ret;
621 }
622
623 }
624 }
625 return 0;
626 }
627 int ff_amf_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
628 {
629 int ret;
630 AMF_RESULT res;
631 AMF_RESULT res_query;
632 AmfContext *ctx = avctx->priv_data;
633 AMFData *data = NULL;
634 int block_and_wait;
635
636 if (!ctx->encoder)
637 return AVERROR(EINVAL);
638
639 do {
640 block_and_wait = 0;
641 // poll data
642 res_query = ctx->encoder->pVtbl->QueryOutput(ctx->encoder, &data);
643 if (data) {
644 // copy data to packet
645 AMFBuffer* buffer;
646 AMFGuid guid = IID_AMFBuffer();
647 data->pVtbl->QueryInterface(data, &guid, (void**)&buffer); // query for buffer interface
648 ret = amf_copy_buffer(avctx, avpkt, buffer);
649
650 buffer->pVtbl->Release(buffer);
651
652 if (data->pVtbl->HasProperty(data, L"av_frame_ref")) {
653 AMFBuffer *frame_ref_storage_buffer;
654 res = amf_get_property_buffer(data, L"av_frame_ref", &frame_ref_storage_buffer);
655 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetProperty failed for \"av_frame_ref\" with error %d\n", res);
656 amf_release_buffer_with_frame_ref(frame_ref_storage_buffer);
657 ctx->hwsurfaces_in_queue--;
658 }
659
660 data->pVtbl->Release(data);
661
662 AMF_RETURN_IF_FALSE(ctx, ret >= 0, ret, "amf_copy_buffer() failed with error %d\n", ret);
663
664 if (ctx->delayed_surface != NULL) { // try to resubmit frame
665 res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)ctx->delayed_surface);
666 if (res != AMF_INPUT_FULL) {
667 int64_t pts = ctx->delayed_surface->pVtbl->GetPts(ctx->delayed_surface);
668 ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
669 ctx->delayed_surface = NULL;
670 av_frame_unref(ctx->delayed_frame);
671 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated SubmitInput() failed with error %d\n", res);
672
673 if ((ret = timestamp_queue_enqueue(avctx, pts)) < 0) {
674 return ret;
675 }
676 } else {
677 av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed frame submission got AMF_INPUT_FULL- should not happen\n");
678 }
679 } else if (ctx->delayed_drain) { // try to resubmit drain
680 res = ctx->encoder->pVtbl->Drain(ctx->encoder);
681 if (res != AMF_INPUT_FULL) {
682 ctx->delayed_drain = 0;
683 ctx->eof = 1; // drain started
684 AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated Drain() failed with error %d\n", res);
685 } else {
686 av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed drain submission got AMF_INPUT_FULL- should not happen\n");
687 }
688 }
689 } else if (ctx->delayed_surface != NULL || ctx->delayed_drain || (ctx->eof && res_query != AMF_EOF) || (ctx->hwsurfaces_in_queue >= ctx->hwsurfaces_in_queue_max)) {
690 block_and_wait = 1;
691 av_usleep(1000); // wait and poll again
692 }
693 } while (block_and_wait);
694
695 if (res_query == AMF_EOF) {
696 ret = AVERROR_EOF;
697 } else if (data == NULL) {
698 ret = AVERROR(EAGAIN);
699 } else {
700 ret = 0;
701 }
702 return ret;
703 }