Browse code

Add HW H.264 and HEVC encoding for AMD GPUs based on AMF SDK

Requires AMF headers for at least version 1.4.4.1.

Signed-off-by: Mikhail Mironov <mikhail.mironov@amd.com>
Signed-off-by: Mark Thompson <sw@jkqxz.net>

Mikhail Mironov authored on 2017/11/27 11:36:06
Showing 8 changed files
... ...
@@ -22,6 +22,7 @@ version <next>:
22 22
 - video normalize filter
23 23
 - audio lv2 wrapper filter
24 24
 - VAAPI VP8 decoding
25
+- AMD AMF H.264 and HEVC encoders
25 26
 
26 27
 
27 28
 version 3.4:
... ...
@@ -304,6 +304,7 @@ External library support:
304 304
   --disable-zlib           disable zlib [autodetect]
305 305
 
306 306
   The following libraries provide various hardware acceleration features:
307
+  --disable-amf            disable AMF video encoding code [autodetect]
307 308
   --disable-audiotoolbox   disable Apple AudioToolbox code [autodetect]
308 309
   --disable-cuda           disable dynamically linked Nvidia CUDA code [autodetect]
309 310
   --enable-cuda-sdk        enable CUDA features that require the CUDA SDK [no]
... ...
@@ -1640,6 +1641,7 @@ EXTERNAL_LIBRARY_LIST="
1640 1640
 "
1641 1641
 
1642 1642
 HWACCEL_AUTODETECT_LIBRARY_LIST="
1643
+    amf
1643 1644
     audiotoolbox
1644 1645
     crystalhd
1645 1646
     cuda
... ...
@@ -2783,12 +2785,14 @@ scale_npp_filter_deps="cuda libnpp"
2783 2783
 scale_cuda_filter_deps="cuda_sdk"
2784 2784
 thumbnail_cuda_filter_deps="cuda_sdk"
2785 2785
 
2786
+amf_deps_any="libdl LoadLibrary"
2786 2787
 nvenc_deps="cuda"
2787 2788
 nvenc_deps_any="libdl LoadLibrary"
2788 2789
 nvenc_encoder_deps="nvenc"
2789 2790
 
2790 2791
 h263_v4l2m2m_decoder_deps="v4l2_m2m h263_v4l2_m2m"
2791 2792
 h263_v4l2m2m_encoder_deps="v4l2_m2m h263_v4l2_m2m"
2793
+h264_amf_encoder_deps="amf"
2792 2794
 h264_crystalhd_decoder_select="crystalhd h264_mp4toannexb_bsf h264_parser"
2793 2795
 h264_cuvid_decoder_deps="cuvid"
2794 2796
 h264_cuvid_decoder_select="h264_mp4toannexb_bsf"
... ...
@@ -2805,6 +2809,7 @@ h264_vaapi_encoder_deps="VAEncPictureParameterBufferH264"
2805 2805
 h264_vaapi_encoder_select="cbs_h264 vaapi_encode"
2806 2806
 h264_v4l2m2m_decoder_deps="v4l2_m2m h264_v4l2_m2m"
2807 2807
 h264_v4l2m2m_encoder_deps="v4l2_m2m h264_v4l2_m2m"
2808
+hevc_amf_encoder_deps="amf"
2808 2809
 hevc_cuvid_decoder_deps="cuvid"
2809 2810
 hevc_cuvid_decoder_select="hevc_mp4toannexb_bsf"
2810 2811
 hevc_mediacodec_decoder_deps="mediacodec"
... ...
@@ -6196,6 +6201,11 @@ void f(void) { struct { const GUID guid; } s[] = { { NV_ENC_PRESET_HQ_GUID } };
6196 6196
 int main(void) { return 0; }
6197 6197
 EOF
6198 6198
 
6199
+enabled amf &&
6200
+    check_cpp_condition "AMF/core/Version.h" \
6201
+        "(AMF_VERSION_MAJOR << 48 | AMF_VERSION_MINOR << 32 | AMF_VERSION_RELEASE << 16 | AMF_VERSION_BUILD_NUM) >= 0x0001000400040001" ||
6202
+    disable amf
6203
+
6199 6204
 # Funny iconv installations are not unusual, so check it after all flags have been set
6200 6205
 if enabled libc_iconv; then
6201 6206
     check_func_headers iconv.h iconv
... ...
@@ -55,6 +55,7 @@ OBJS = ac3_parser.o                                                     \
55 55
 OBJS-$(CONFIG_AANDCTTABLES)            += aandcttab.o
56 56
 OBJS-$(CONFIG_AC3DSP)                  += ac3dsp.o ac3.o ac3tab.o
57 57
 OBJS-$(CONFIG_ADTS_HEADER)             += adts_header.o mpeg4audio.o
58
+OBJS-$(CONFIG_AMF)                     += amfenc.o
58 59
 OBJS-$(CONFIG_AUDIO_FRAME_QUEUE)       += audio_frame_queue.o
59 60
 OBJS-$(CONFIG_AUDIODSP)                += audiodsp.o
60 61
 OBJS-$(CONFIG_BLOCKDSP)                += blockdsp.o
... ...
@@ -337,6 +338,7 @@ OBJS-$(CONFIG_H264_DECODER)            += h264dec.o h264_cabac.o h264_cavlc.o \
337 337
                                           h264_mb.o h264_picture.o \
338 338
                                           h264_refs.o h264_sei.o \
339 339
                                           h264_slice.o h264data.o
340
+OBJS-$(CONFIG_H264_AMF_ENCODER)        += amfenc_h264.o
340 341
 OBJS-$(CONFIG_H264_CUVID_DECODER)      += cuviddec.o
341 342
 OBJS-$(CONFIG_H264_MEDIACODEC_DECODER) += mediacodecdec.o
342 343
 OBJS-$(CONFIG_H264_MMAL_DECODER)       += mmaldec.o
... ...
@@ -356,6 +358,7 @@ OBJS-$(CONFIG_HAP_ENCODER)             += hapenc.o hap.o
356 356
 OBJS-$(CONFIG_HEVC_DECODER)            += hevcdec.o hevc_mvs.o \
357 357
                                           hevc_cabac.o hevc_refs.o hevcpred.o    \
358 358
                                           hevcdsp.o hevc_filter.o hevc_data.o
359
+OBJS-$(CONFIG_HEVC_AMF_ENCODER)        += amfenc_hevc.o
359 360
 OBJS-$(CONFIG_HEVC_CUVID_DECODER)      += cuviddec.o
360 361
 OBJS-$(CONFIG_HEVC_MEDIACODEC_DECODER) += mediacodecdec.o
361 362
 OBJS-$(CONFIG_HEVC_NVENC_ENCODER)      += nvenc_hevc.o
... ...
@@ -1065,6 +1068,7 @@ SKIPHEADERS                            += %_tablegen.h                  \
1065 1065
                                           aacenc_quantization_misc.h    \
1066 1066
                                           $(ARCH)/vp56_arith.h          \
1067 1067
 
1068
+SKIPHEADERS-$(CONFIG_AMF)              += amfenc.h
1068 1069
 SKIPHEADERS-$(CONFIG_D3D11VA)          += d3d11va.h dxva2_internal.h
1069 1070
 SKIPHEADERS-$(CONFIG_DXVA2)            += dxva2.h dxva2_internal.h
1070 1071
 SKIPHEADERS-$(CONFIG_JNI)              += ffjni.h
... ...
@@ -576,6 +576,7 @@ static void register_all(void)
576 576
      * above is available */
577 577
     REGISTER_ENCODER(H263_V4L2M2M,      h263_v4l2m2m);
578 578
     REGISTER_ENCDEC (LIBOPENH264,       libopenh264);
579
+    REGISTER_ENCODER(H264_AMF,          h264_amf);
579 580
     REGISTER_DECODER(H264_CUVID,        h264_cuvid);
580 581
     REGISTER_ENCODER(H264_NVENC,        h264_nvenc);
581 582
     REGISTER_ENCODER(H264_OMX,          h264_omx);
... ...
@@ -588,6 +589,7 @@ static void register_all(void)
588 588
     REGISTER_ENCODER(NVENC_H264,        nvenc_h264);
589 589
     REGISTER_ENCODER(NVENC_HEVC,        nvenc_hevc);
590 590
 #endif
591
+    REGISTER_ENCODER(HEVC_AMF,          hevc_amf);
591 592
     REGISTER_DECODER(HEVC_CUVID,        hevc_cuvid);
592 593
     REGISTER_DECODER(HEVC_MEDIACODEC,   hevc_mediacodec);
593 594
     REGISTER_ENCODER(HEVC_NVENC,        hevc_nvenc);
594 595
new file mode 100644
... ...
@@ -0,0 +1,604 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+#include "libavutil/avassert.h"
19
+#include "libavutil/imgutils.h"
20
+#include "libavutil/hwcontext.h"
21
+#if CONFIG_D3D11VA
22
+#include "libavutil/hwcontext_d3d11va.h"
23
+#endif
24
+#include "libavutil/mem.h"
25
+#include "libavutil/pixdesc.h"
26
+#include "libavutil/time.h"
27
+
28
+#include "amfenc.h"
29
+#include "internal.h"
30
+
31
+#if CONFIG_D3D11VA
32
+#include <d3d11.h>
33
+#endif
34
+
35
+#ifdef _WIN32
36
+#include "compat/w32dlfcn.h"
37
+#else
38
+#include <dlfcn.h>
39
+#endif
40
+
41
+#define FFMPEG_AMF_WRITER_ID L"ffmpeg_amf"
42
+
43
+#define PTS_PROP L"PtsProp"
44
+
45
+const enum AVPixelFormat ff_amf_pix_fmts[] = {
46
+    AV_PIX_FMT_NV12,
47
+    AV_PIX_FMT_YUV420P,
48
+#if CONFIG_D3D11VA
49
+    AV_PIX_FMT_D3D11,
50
+#endif
51
+    AV_PIX_FMT_NONE
52
+};
53
+
54
+typedef struct FormatMap {
55
+    enum AVPixelFormat       av_format;
56
+    enum AMF_SURFACE_FORMAT  amf_format;
57
+} FormatMap;
58
+
59
+static const FormatMap format_map[] =
60
+{
61
+    { AV_PIX_FMT_NONE,       AMF_SURFACE_UNKNOWN },
62
+    { AV_PIX_FMT_NV12,       AMF_SURFACE_NV12 },
63
+    { AV_PIX_FMT_BGR0,       AMF_SURFACE_BGRA },
64
+    { AV_PIX_FMT_RGB0,       AMF_SURFACE_RGBA },
65
+    { AV_PIX_FMT_GRAY8,      AMF_SURFACE_GRAY8 },
66
+    { AV_PIX_FMT_YUV420P,    AMF_SURFACE_YUV420P },
67
+    { AV_PIX_FMT_YUYV422,    AMF_SURFACE_YUY2 },
68
+    { AV_PIX_FMT_D3D11,      AMF_SURFACE_NV12 },
69
+};
70
+
71
+
72
+static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
73
+{
74
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
75
+    return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
76
+}
77
+
78
+
79
+static enum AMF_SURFACE_FORMAT amf_av_to_amf_format(enum AVPixelFormat fmt)
80
+{
81
+    int i;
82
+    for (i = 0; i < amf_countof(format_map); i++) {
83
+        if (format_map[i].av_format == fmt) {
84
+            return format_map[i].amf_format;
85
+        }
86
+    }
87
+    return AMF_SURFACE_UNKNOWN;
88
+}
89
+
90
+static void AMF_CDECL_CALL AMFTraceWriter_Write(AMFTraceWriter *pThis,
91
+    const wchar_t *scope, const wchar_t *message)
92
+{
93
+    AmfTraceWriter *tracer = (AmfTraceWriter*)pThis;
94
+    av_log(tracer->avctx, AV_LOG_DEBUG, "%ls: %ls", scope, message); // \n is provided from AMF
95
+}
96
+
97
+static void AMF_CDECL_CALL AMFTraceWriter_Flush(AMFTraceWriter *pThis)
98
+{
99
+}
100
+
101
+static AMFTraceWriterVtbl tracer_vtbl =
102
+{
103
+    .Write = AMFTraceWriter_Write,
104
+    .Flush = AMFTraceWriter_Flush,
105
+};
106
+
107
+static int amf_load_library(AVCodecContext *avctx)
108
+{
109
+    AmfContext             *ctx = avctx->priv_data;
110
+    AMFInit_Fn              init_fun = NULL;
111
+    AMFQueryVersion_Fn      version_fun = NULL;
112
+    AMF_RESULT              res = AMF_OK;
113
+
114
+    ctx->eof = 0;
115
+    ctx->delayed_drain = 0;
116
+    ctx->hw_frames_ctx = NULL;
117
+    ctx->hw_device_ctx = NULL;
118
+    ctx->delayed_surface = NULL;
119
+    ctx->delayed_frame = av_frame_alloc();
120
+    if (!ctx->delayed_frame) {
121
+        return AVERROR(ENOMEM);
122
+    }
123
+    // hardcoded to current HW queue size - will realloc in timestamp_queue_enqueue() if too small
124
+    ctx->timestamp_list = av_fifo_alloc((avctx->max_b_frames + 16) * sizeof(int64_t));
125
+    if (!ctx->timestamp_list) {
126
+        return AVERROR(ENOMEM);
127
+    }
128
+    ctx->dts_delay = 0;
129
+
130
+
131
+    ctx->library = dlopen(AMF_DLL_NAMEA, RTLD_NOW | RTLD_LOCAL);
132
+    AMF_RETURN_IF_FALSE(ctx, ctx->library != NULL,
133
+        AVERROR_UNKNOWN, "DLL %s failed to open\n", AMF_DLL_NAMEA);
134
+
135
+    init_fun = (AMFInit_Fn)dlsym(ctx->library, AMF_INIT_FUNCTION_NAME);
136
+    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);
137
+
138
+    version_fun = (AMFQueryVersion_Fn)dlsym(ctx->library, AMF_QUERY_VERSION_FUNCTION_NAME);
139
+    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);
140
+
141
+    res = version_fun(&ctx->version);
142
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_QUERY_VERSION_FUNCTION_NAME, res);
143
+    res = init_fun(AMF_FULL_VERSION, &ctx->factory);
144
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "%s failed with error %d\n", AMF_INIT_FUNCTION_NAME, res);
145
+    res = ctx->factory->pVtbl->GetTrace(ctx->factory, &ctx->trace);
146
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetTrace() failed with error %d\n", res);
147
+    res = ctx->factory->pVtbl->GetDebug(ctx->factory, &ctx->debug);
148
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "GetDebug() failed with error %d\n", res);
149
+    return 0;
150
+}
151
+
152
+static int amf_init_context(AVCodecContext *avctx)
153
+{
154
+    AmfContext         *ctx = avctx->priv_data;
155
+    AMF_RESULT          res = AMF_OK;
156
+
157
+    // confugure AMF logger
158
+    // the return of these functions indicates old state and do not affect behaviour
159
+    ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, ctx->log_to_dbg != 0 );
160
+    if (ctx->log_to_dbg)
161
+        ctx->trace->pVtbl->SetWriterLevel(ctx->trace, AMF_TRACE_WRITER_DEBUG_OUTPUT, AMF_TRACE_TRACE);
162
+    ctx->trace->pVtbl->EnableWriter(ctx->trace, AMF_TRACE_WRITER_CONSOLE, 0);
163
+    ctx->trace->pVtbl->SetGlobalLevel(ctx->trace, AMF_TRACE_TRACE);
164
+
165
+    // connect AMF logger to av_log
166
+    ctx->tracer.vtbl = &tracer_vtbl;
167
+    ctx->tracer.avctx = avctx;
168
+    ctx->trace->pVtbl->RegisterWriter(ctx->trace, FFMPEG_AMF_WRITER_ID,(AMFTraceWriter*)&ctx->tracer, 1);
169
+    ctx->trace->pVtbl->SetWriterLevel(ctx->trace, FFMPEG_AMF_WRITER_ID, AMF_TRACE_TRACE);
170
+
171
+    res = ctx->factory->pVtbl->CreateContext(ctx->factory, &ctx->context);
172
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "CreateContext() failed with error %d\n", res);
173
+    // try to reuse existing DX device
174
+#if CONFIG_D3D11VA
175
+    if (avctx->hw_frames_ctx) {
176
+        AVHWFramesContext *device_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
177
+        if (device_ctx->device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
178
+            if (amf_av_to_amf_format(device_ctx->sw_format) != AMF_SURFACE_UNKNOWN) {
179
+                if (device_ctx->device_ctx->hwctx) {
180
+                    AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->device_ctx->hwctx;
181
+                    res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
182
+                    if (res == AMF_OK) {
183
+                        ctx->hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
184
+                        if (!ctx->hw_frames_ctx) {
185
+                            return AVERROR(ENOMEM);
186
+                        }
187
+                    } else {
188
+                        if(res == AMF_NOT_SUPPORTED)
189
+                            av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
190
+                        else
191
+                            av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has non-AMD device, switching to default\n");
192
+                    }
193
+                }
194
+            } else {
195
+                av_log(avctx, AV_LOG_INFO, "avctx->hw_frames_ctx has format not uspported by AMF, switching to default\n");
196
+            }
197
+        }
198
+    } else if (avctx->hw_device_ctx) {
199
+        AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)(avctx->hw_device_ctx->data);
200
+        if (device_ctx->type == AV_HWDEVICE_TYPE_D3D11VA) {
201
+            if (device_ctx->hwctx) {
202
+                AVD3D11VADeviceContext *device_d3d11 = (AVD3D11VADeviceContext *)device_ctx->hwctx;
203
+                res = ctx->context->pVtbl->InitDX11(ctx->context, device_d3d11->device, AMF_DX11_1);
204
+                if (res == AMF_OK) {
205
+                    ctx->hw_device_ctx = av_buffer_ref(avctx->hw_device_ctx);
206
+                    if (!ctx->hw_device_ctx) {
207
+                        return AVERROR(ENOMEM);
208
+                    }
209
+                } else {
210
+                    if (res == AMF_NOT_SUPPORTED)
211
+                        av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has D3D11 device which doesn't have D3D11VA interface, switching to default\n");
212
+                    else
213
+                        av_log(avctx, AV_LOG_INFO, "avctx->hw_device_ctx has non-AMD device, switching to default\n");
214
+                }
215
+            }
216
+        }
217
+    }
218
+#endif
219
+    if (!ctx->hw_frames_ctx && !ctx->hw_device_ctx) {
220
+        res = ctx->context->pVtbl->InitDX11(ctx->context, NULL, AMF_DX11_1);
221
+        if (res != AMF_OK) {
222
+            res = ctx->context->pVtbl->InitDX9(ctx->context, NULL);
223
+            AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "InitDX9() failed with error %d\n", res);
224
+        }
225
+    }
226
+    return 0;
227
+}
228
+
229
+static int amf_init_encoder(AVCodecContext *avctx)
230
+{
231
+    AmfContext          *ctx = avctx->priv_data;
232
+    const wchar_t       *codec_id = NULL;
233
+    AMF_RESULT           res = AMF_OK;
234
+
235
+    switch (avctx->codec->id) {
236
+        case AV_CODEC_ID_H264:
237
+            codec_id = AMFVideoEncoderVCE_AVC;
238
+            break;
239
+        case AV_CODEC_ID_HEVC:
240
+            codec_id = AMFVideoEncoder_HEVC;
241
+            break;
242
+        default:
243
+            break;
244
+    }
245
+    AMF_RETURN_IF_FALSE(ctx, codec_id != NULL, AVERROR(EINVAL), "Codec %d is not supported\n", avctx->codec->id);
246
+
247
+    ctx->format = amf_av_to_amf_format(avctx->pix_fmt);
248
+    AMF_RETURN_IF_FALSE(ctx, ctx->format != AMF_SURFACE_UNKNOWN, AVERROR(EINVAL), "Format %d is not supported\n", avctx->pix_fmt);
249
+
250
+    res = ctx->factory->pVtbl->CreateComponent(ctx->factory, ctx->context, codec_id, &ctx->encoder);
251
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_ENCODER_NOT_FOUND, "CreateComponent(%ls) failed with error %d\n", codec_id, res);
252
+
253
+    return 0;
254
+}
255
+
256
+int av_cold ff_amf_encode_close(AVCodecContext *avctx)
257
+{
258
+    AmfContext      *ctx = avctx->priv_data;
259
+    if (ctx->delayed_surface)
260
+    {
261
+        ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
262
+        ctx->delayed_surface = NULL;
263
+    }
264
+
265
+    if (ctx->encoder) {
266
+        ctx->encoder->pVtbl->Terminate(ctx->encoder);
267
+        ctx->encoder->pVtbl->Release(ctx->encoder);
268
+        ctx->encoder = NULL;
269
+    }
270
+
271
+    if (ctx->context) {
272
+        ctx->context->pVtbl->Terminate(ctx->context);
273
+        ctx->context->pVtbl->Release(ctx->context);
274
+        ctx->context = NULL;
275
+    }
276
+    av_buffer_unref(&ctx->hw_device_ctx);
277
+    av_buffer_unref(&ctx->hw_frames_ctx);
278
+
279
+    if (ctx->trace) {
280
+        ctx->trace->pVtbl->UnregisterWriter(ctx->trace, FFMPEG_AMF_WRITER_ID);
281
+    }
282
+    if (ctx->library) {
283
+        dlclose(ctx->library);
284
+        ctx->library = NULL;
285
+    }
286
+    ctx->trace = NULL;
287
+    ctx->debug = NULL;
288
+    ctx->factory = NULL;
289
+    ctx->version = 0;
290
+    ctx->delayed_drain = 0;
291
+    av_frame_free(&ctx->delayed_frame);
292
+    av_fifo_freep(&ctx->timestamp_list);
293
+
294
+    return 0;
295
+}
296
+
297
+static int amf_copy_surface(AVCodecContext *avctx, const AVFrame *frame,
298
+    AMFSurface* surface)
299
+{
300
+    AVFrame        *sw_frame = NULL;
301
+    AMFPlane       *plane = NULL;
302
+    uint8_t        *dst_data[4];
303
+    int             dst_linesize[4];
304
+    int             ret = 0;
305
+    int             planes;
306
+    int             i;
307
+
308
+    if (frame->hw_frames_ctx && is_hwaccel_pix_fmt(frame->format)) {
309
+        if (!(sw_frame = av_frame_alloc())) {
310
+            av_log(avctx, AV_LOG_ERROR, "Can not alloc frame\n");
311
+            ret = AVERROR(ENOMEM);
312
+            goto fail;
313
+        }
314
+        if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
315
+            av_log(avctx, AV_LOG_ERROR, "Error transferring the data to system memory\n");
316
+            goto fail;
317
+        }
318
+        frame = sw_frame;
319
+    }
320
+    planes = (int)surface->pVtbl->GetPlanesCount(surface);
321
+    if (planes > amf_countof(dst_data)) {
322
+        av_log(avctx, AV_LOG_ERROR, "Invalid number of planes %d in surface\n", planes);
323
+        ret = AVERROR(EINVAL);
324
+        goto fail;
325
+    }
326
+
327
+    for (i = 0; i < planes; i++) {
328
+        plane = surface->pVtbl->GetPlaneAt(surface, i);
329
+        dst_data[i] = plane->pVtbl->GetNative(plane);
330
+        dst_linesize[i] = plane->pVtbl->GetHPitch(plane);
331
+    }
332
+    av_image_copy(dst_data, dst_linesize,
333
+        (const uint8_t**)frame->data, frame->linesize, frame->format,
334
+        avctx->width, avctx->height);
335
+
336
+fail:
337
+    if (sw_frame) {
338
+        av_frame_free(&sw_frame);
339
+    }
340
+    return ret;
341
+}
342
+
343
+static inline int timestamp_queue_enqueue(AVCodecContext *avctx, int64_t timestamp)
344
+{
345
+    AmfContext         *ctx = avctx->priv_data;
346
+    if (av_fifo_space(ctx->timestamp_list) < sizeof(timestamp)) {
347
+        if (av_fifo_grow(ctx->timestamp_list, sizeof(timestamp)) < 0) {
348
+            return AVERROR(ENOMEM);
349
+        }
350
+    }
351
+    av_fifo_generic_write(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
352
+    return 0;
353
+}
354
+
355
+static int amf_copy_buffer(AVCodecContext *avctx, AVPacket *pkt, AMFBuffer *buffer)
356
+{
357
+    AmfContext             *ctx = avctx->priv_data;
358
+    int                     ret;
359
+    AMFVariantStruct        var = {0};
360
+    int64_t                 timestamp = AV_NOPTS_VALUE;
361
+    int64_t                 size = buffer->pVtbl->GetSize(buffer);
362
+
363
+    if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0) {
364
+        return ret;
365
+    }
366
+    memcpy(pkt->data, buffer->pVtbl->GetNative(buffer), size);
367
+
368
+    switch (avctx->codec->id) {
369
+        case AV_CODEC_ID_H264:
370
+            buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE, &var);
371
+            if(var.int64Value == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR) {
372
+                pkt->flags = AV_PKT_FLAG_KEY;
373
+            }
374
+            break;
375
+        case AV_CODEC_ID_HEVC:
376
+            buffer->pVtbl->GetProperty(buffer, AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE, &var);
377
+            if (var.int64Value == AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE_IDR) {
378
+                pkt->flags = AV_PKT_FLAG_KEY;
379
+            }
380
+            break;
381
+        default:
382
+            break;
383
+    }
384
+
385
+    buffer->pVtbl->GetProperty(buffer, PTS_PROP, &var);
386
+
387
+    pkt->pts = var.int64Value; // original pts
388
+
389
+
390
+    AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN, "timestamp_list is empty\n");
391
+
392
+    av_fifo_generic_read(ctx->timestamp_list, &timestamp, sizeof(timestamp), NULL);
393
+
394
+    // calc dts shift if max_b_frames > 0
395
+    if (avctx->max_b_frames > 0 && ctx->dts_delay == 0) {
396
+        int64_t timestamp_last = AV_NOPTS_VALUE;
397
+        AMF_RETURN_IF_FALSE(ctx, av_fifo_size(ctx->timestamp_list) > 0, AVERROR_UNKNOWN,
398
+            "timestamp_list is empty while max_b_frames = %d\n", avctx->max_b_frames);
399
+        av_fifo_generic_peek_at(
400
+            ctx->timestamp_list,
401
+            &timestamp_last,
402
+            (av_fifo_size(ctx->timestamp_list) / sizeof(timestamp) - 1) * sizeof(timestamp_last),
403
+            sizeof(timestamp_last),
404
+            NULL);
405
+        if (timestamp < 0 || timestamp_last < AV_NOPTS_VALUE) {
406
+            return AVERROR(ERANGE);
407
+        }
408
+        ctx->dts_delay = timestamp_last - timestamp;
409
+    }
410
+    pkt->dts = timestamp - ctx->dts_delay;
411
+    return 0;
412
+}
413
+
414
+// amfenc API implmentation
415
+int ff_amf_encode_init(AVCodecContext *avctx)
416
+{
417
+    AmfContext     *ctx = avctx->priv_data;
418
+    int             ret;
419
+
420
+    ctx->factory = NULL;
421
+    ctx->debug = NULL;
422
+    ctx->trace = NULL;
423
+    ctx->context = NULL;
424
+    ctx->encoder = NULL;
425
+    ctx->library = NULL;
426
+    ctx->version = 0;
427
+    ctx->eof = 0;
428
+    ctx->format = 0;
429
+    ctx->tracer.vtbl = NULL;
430
+    ctx->tracer.avctx = NULL;
431
+
432
+    if ((ret = amf_load_library(avctx)) == 0) {
433
+        if ((ret = amf_init_context(avctx)) == 0) {
434
+            if ((ret = amf_init_encoder(avctx)) == 0) {
435
+                return 0;
436
+            }
437
+        }
438
+    }
439
+    ff_amf_encode_close(avctx);
440
+    return ret;
441
+}
442
+
443
+
444
+int ff_amf_send_frame(AVCodecContext *avctx, const AVFrame *frame)
445
+{
446
+    AMF_RESULT      res = AMF_OK;
447
+    AmfContext     *ctx = avctx->priv_data;
448
+    AMFSurface     *surface = NULL;
449
+    int             ret;
450
+
451
+    if (!ctx->encoder)
452
+        return AVERROR(EINVAL);
453
+
454
+    if (!frame) { // submit drain
455
+        if (!ctx->eof) { // submit drain one time only
456
+            if (ctx->delayed_surface != NULL) {
457
+                ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
458
+            } else if(!ctx->delayed_drain) {
459
+                res = ctx->encoder->pVtbl->Drain(ctx->encoder);
460
+                if (res == AMF_INPUT_FULL) {
461
+                    ctx->delayed_drain = 1; // input queue is full: resubmit Drain() in ff_amf_receive_packet
462
+                } else {
463
+                    if (res == AMF_OK) {
464
+                        ctx->eof = 1; // drain started
465
+                    }
466
+                    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Drain() failed with error %d\n", res);
467
+                }
468
+            }
469
+        } else{
470
+            return AVERROR_EOF;
471
+        }
472
+    } else { // submit frame
473
+        if (ctx->delayed_surface != NULL) {
474
+            return AVERROR(EAGAIN); // should not happen when called from ffmpeg, other clients may resubmit
475
+        }
476
+        // prepare surface from frame
477
+        if (frame->hw_frames_ctx && ( // HW frame detected
478
+            // check if the same hw_frames_ctx as used in initialization
479
+            (ctx->hw_frames_ctx && frame->hw_frames_ctx->data == ctx->hw_frames_ctx->data) ||
480
+            // check if the same hw_device_ctx as used in initialization
481
+            (ctx->hw_device_ctx && ((AVHWFramesContext*)frame->hw_frames_ctx->data)->device_ctx ==
482
+            (AVHWDeviceContext*)ctx->hw_device_ctx->data)
483
+        )) {
484
+#if CONFIG_D3D11VA
485
+            static const GUID AMFTextureArrayIndexGUID = { 0x28115527, 0xe7c3, 0x4b66, { 0x99, 0xd3, 0x4f, 0x2a, 0xe6, 0xb4, 0x7f, 0xaf } };
486
+            ID3D11Texture2D *texture = (ID3D11Texture2D*)frame->data[0]; // actual texture
487
+            int index = (int)(size_t)frame->data[1]; // index is a slice in texture array is - set to tell AMF which slice to use
488
+            texture->lpVtbl->SetPrivateData(texture, &AMFTextureArrayIndexGUID, sizeof(index), &index);
489
+
490
+            res = ctx->context->pVtbl->CreateSurfaceFromDX11Native(ctx->context, texture, &surface, NULL); // wrap to AMF surface
491
+            AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "CreateSurfaceFromDX11Native() failed  with error %d\n", res);
492
+
493
+            // input HW surfaces can be vertically aligned by 16; tell AMF the real size
494
+            surface->pVtbl->SetCrop(surface, 0, 0, frame->width, frame->height);
495
+#endif
496
+        } else {
497
+            res = ctx->context->pVtbl->AllocSurface(ctx->context, AMF_MEMORY_HOST, ctx->format, avctx->width, avctx->height, &surface);
498
+            AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR(ENOMEM), "AllocSurface() failed  with error %d\n", res);
499
+            amf_copy_surface(avctx, frame, surface);
500
+        }
501
+        surface->pVtbl->SetPts(surface, frame->pts);
502
+        AMF_ASSIGN_PROPERTY_INT64(res, surface, PTS_PROP, frame->pts);
503
+
504
+        switch (avctx->codec->id) {
505
+        case AV_CODEC_ID_H264:
506
+            AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_INSERT_AUD, !!ctx->aud);
507
+            break;
508
+        case AV_CODEC_ID_HEVC:
509
+            AMF_ASSIGN_PROPERTY_INT64(res, surface, AMF_VIDEO_ENCODER_HEVC_INSERT_AUD, !!ctx->aud);
510
+            break;
511
+        default:
512
+            break;
513
+        }
514
+
515
+
516
+        // submit surface
517
+        res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)surface);
518
+        if (res == AMF_INPUT_FULL) { // handle full queue
519
+            //store surface for later submission
520
+            ctx->delayed_surface = surface;
521
+            if (surface->pVtbl->GetMemoryType(surface) == AMF_MEMORY_DX11) {
522
+                av_frame_ref(ctx->delayed_frame, frame);
523
+            }
524
+        } else {
525
+            surface->pVtbl->Release(surface);
526
+            AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "SubmitInput() failed with error %d\n", res);
527
+
528
+            if ((ret = timestamp_queue_enqueue(avctx, frame->pts)) < 0) {
529
+                return ret;
530
+            }
531
+
532
+        }
533
+    }
534
+    return 0;
535
+}
536
+int ff_amf_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
537
+{
538
+    int             ret;
539
+    AMF_RESULT      res;
540
+    AMF_RESULT      res_query;
541
+    AmfContext     *ctx = avctx->priv_data;
542
+    AMFData        *data = NULL;
543
+    int             block_and_wait;
544
+
545
+    if (!ctx->encoder)
546
+        return AVERROR(EINVAL);
547
+
548
+    do {
549
+        block_and_wait = 0;
550
+        // poll data
551
+        res_query = ctx->encoder->pVtbl->QueryOutput(ctx->encoder, &data);
552
+        if (data) {
553
+            // copy data to packet
554
+            AMFBuffer* buffer;
555
+            AMFGuid guid = IID_AMFBuffer();
556
+            data->pVtbl->QueryInterface(data, &guid, (void**)&buffer); // query for buffer interface
557
+            ret = amf_copy_buffer(avctx, avpkt, buffer);
558
+
559
+            buffer->pVtbl->Release(buffer);
560
+            data->pVtbl->Release(data);
561
+
562
+            AMF_RETURN_IF_FALSE(ctx, ret >= 0, ret, "amf_copy_buffer() failed with error %d\n", ret);
563
+
564
+            if (ctx->delayed_surface != NULL) { // try to resubmit frame
565
+                res = ctx->encoder->pVtbl->SubmitInput(ctx->encoder, (AMFData*)ctx->delayed_surface);
566
+                if (res != AMF_INPUT_FULL) {
567
+                    int64_t pts = ctx->delayed_surface->pVtbl->GetPts(ctx->delayed_surface);
568
+                    ctx->delayed_surface->pVtbl->Release(ctx->delayed_surface);
569
+                    ctx->delayed_surface = NULL;
570
+                    av_frame_unref(ctx->delayed_frame);
571
+                    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated SubmitInput() failed with error %d\n", res);
572
+
573
+                    if ((ret = timestamp_queue_enqueue(avctx, pts)) < 0) {
574
+                        return ret;
575
+                    }
576
+                } else {
577
+                    av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed frame submission got AMF_INPUT_FULL- should not happen\n");
578
+                }
579
+            } else if (ctx->delayed_drain) { // try to resubmit drain
580
+                res = ctx->encoder->pVtbl->Drain(ctx->encoder);
581
+                if (res != AMF_INPUT_FULL) {
582
+                    ctx->delayed_drain = 0;
583
+                    ctx->eof = 1; // drain started
584
+                    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_UNKNOWN, "Repeated Drain() failed with error %d\n", res);
585
+                } else {
586
+                    av_log(avctx, AV_LOG_WARNING, "Data acquired but delayed drain submission got AMF_INPUT_FULL- should not happen\n");
587
+                }
588
+            }
589
+        } else if (ctx->delayed_surface != NULL || ctx->delayed_drain || (ctx->eof && res_query != AMF_EOF)) {
590
+            block_and_wait = 1;
591
+            av_usleep(1000); // wait and poll again
592
+        }
593
+    } while (block_and_wait);
594
+
595
+    if (res_query == AMF_EOF) {
596
+        ret = AVERROR_EOF;
597
+    } else if (data == NULL) {
598
+        ret = AVERROR(EAGAIN);
599
+    } else {
600
+        ret = 0;
601
+    }
602
+    return ret;
603
+}
0 604
new file mode 100644
... ...
@@ -0,0 +1,148 @@
0
+/*
1
+* This file is part of FFmpeg.
2
+*
3
+* FFmpeg is free software; you can redistribute it and/or
4
+* modify it under the terms of the GNU Lesser General Public
5
+* License as published by the Free Software Foundation; either
6
+* version 2.1 of the License, or (at your option) any later version.
7
+*
8
+* FFmpeg is distributed in the hope that it will be useful,
9
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+* Lesser General Public License for more details.
12
+*
13
+* You should have received a copy of the GNU Lesser General Public
14
+* License along with FFmpeg; if not, write to the Free Software
15
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+*/
17
+
18
+#ifndef AVCODEC_AMFENC_H
19
+#define AVCODEC_AMFENC_H
20
+
21
+#include <AMF/core/Factory.h>
22
+
23
+#include <AMF/components/VideoEncoderVCE.h>
24
+#include <AMF/components/VideoEncoderHEVC.h>
25
+
26
+#include "libavutil/fifo.h"
27
+
28
+#include "config.h"
29
+#include "avcodec.h"
30
+
31
+
32
+/**
33
+* AMF trace writer callback class
34
+* Used to capture all AMF logging
35
+*/
36
+
37
+typedef struct AmfTraceWriter {
38
+    AMFTraceWriterVtbl *vtbl;
39
+    AVCodecContext     *avctx;
40
+} AmfTraceWriter;
41
+
42
+/**
43
+* AMF encoder context
44
+*/
45
+
46
+typedef struct AmfContext {
47
+    AVClass            *avclass;
48
+    // access to AMF runtime
49
+    amf_handle          library; ///< handle to DLL library
50
+    AMFFactory         *factory; ///< pointer to AMF factory
51
+    AMFDebug           *debug;   ///< pointer to AMF debug interface
52
+    AMFTrace           *trace;   ///< pointer to AMF trace interface
53
+
54
+    amf_uint64          version; ///< version of AMF runtime
55
+    AmfTraceWriter      tracer;  ///< AMF writer registered with AMF
56
+    AMFContext         *context; ///< AMF context
57
+    //encoder
58
+    AMFComponent       *encoder; ///< AMF encoder object
59
+    amf_bool            eof;     ///< flag indicating EOF happened
60
+    AMF_SURFACE_FORMAT  format;  ///< AMF surface format
61
+
62
+    AVBufferRef        *hw_device_ctx; ///< pointer to HW accelerator (decoder)
63
+    AVBufferRef        *hw_frames_ctx; ///< pointer to HW accelerator (frame allocator)
64
+
65
+    // helpers to handle async calls
66
+    int                 delayed_drain;
67
+    AMFSurface         *delayed_surface;
68
+    AVFrame            *delayed_frame;
69
+
70
+    // shift dts back by max_b_frames in timing
71
+    AVFifoBuffer       *timestamp_list;
72
+    int64_t             dts_delay;
73
+
74
+    // common encoder option options
75
+
76
+    int                 log_to_dbg;
77
+
78
+    // Static options, have to be set before Init() call
79
+    int                 usage;
80
+    int                 profile;
81
+    int                 level;
82
+    int                 preanalysis;
83
+    int                 quality;
84
+    int                 b_frame_delta_qp;
85
+    int                 ref_b_frame_delta_qp;
86
+
87
+    // Dynamic options, can be set after Init() call
88
+
89
+    int                 rate_control_mode;
90
+    int                 enforce_hrd;
91
+    int                 filler_data;
92
+    int                 enable_vbaq;
93
+    int                 skip_frame;
94
+    int                 qp_i;
95
+    int                 qp_p;
96
+    int                 qp_b;
97
+    int                 max_au_size;
98
+    int                 header_spacing;
99
+    int                 b_frame_ref;
100
+    int                 intra_refresh_mb;
101
+    int                 coding_mode;
102
+    int                 me_half_pel;
103
+    int                 me_quarter_pel;
104
+    int                 aud;
105
+
106
+    // HEVC - specific options
107
+
108
+    int                 gops_per_idr;
109
+    int                 header_insertion_mode;
110
+    int                 min_qp_i;
111
+    int                 max_qp_i;
112
+    int                 min_qp_p;
113
+    int                 max_qp_p;
114
+    int                 tier;
115
+} AmfContext;
116
+
117
+/**
118
+* Common encoder initization function
119
+*/
120
+int ff_amf_encode_init(AVCodecContext *avctx);
121
+/**
122
+* Common encoder termination function
123
+*/
124
+int ff_amf_encode_close(AVCodecContext *avctx);
125
+
126
+/**
127
+* Ecoding one frame - common function for all AMF encoders
128
+*/
129
+
130
+int ff_amf_send_frame(AVCodecContext *avctx, const AVFrame *frame);
131
+int ff_amf_receive_packet(AVCodecContext *avctx, AVPacket *avpkt);
132
+
133
+/**
134
+* Supported formats
135
+*/
136
+extern const enum AVPixelFormat ff_amf_pix_fmts[];
137
+
138
+/**
139
+* Error handling helper
140
+*/
141
+#define AMF_RETURN_IF_FALSE(avctx, exp, ret_value, /*message,*/ ...) \
142
+    if (!(exp)) { \
143
+        av_log(avctx, AV_LOG_ERROR, __VA_ARGS__); \
144
+        return ret_value; \
145
+    }
146
+
147
+#endif //AVCODEC_AMFENC_H
0 148
new file mode 100644
... ...
@@ -0,0 +1,395 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+
19
+#include "libavutil/internal.h"
20
+#include "libavutil/opt.h"
21
+#include "amfenc.h"
22
+#include "internal.h"
23
+
24
+#define OFFSET(x) offsetof(AmfContext, x)
25
+#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
26
+
27
+static const AVOption options[] = {
28
+    // Static
29
+    /// Usage
30
+    { "usage",          "Encoder Usage",        OFFSET(usage),  AV_OPT_TYPE_INT,   { .i64 = AMF_VIDEO_ENCODER_USAGE_TRANSCONDING      }, AMF_VIDEO_ENCODER_USAGE_TRANSCONDING, AMF_VIDEO_ENCODER_USAGE_WEBCAM, VE, "usage" },
31
+    { "transcoding",    "Generic Transcoding",  0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_USAGE_TRANSCONDING      }, 0, 0, VE, "usage" },
32
+    { "ultralowlatency","",                     0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_USAGE_ULTRA_LOW_LATENCY }, 0, 0, VE, "usage" },
33
+    { "lowlatency",     "",                     0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY       }, 0, 0, VE, "usage" },
34
+    { "webcam",         "Webcam",               0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_USAGE_WEBCAM            }, 0, 0, VE, "usage" },
35
+
36
+    /// Profile,
37
+    { "profile",        "Profile",              OFFSET(profile),AV_OPT_TYPE_INT,   { .i64 = AMF_VIDEO_ENCODER_PROFILE_MAIN                 }, AMF_VIDEO_ENCODER_PROFILE_BASELINE, AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH, VE, "profile" },
38
+    { "main",           "",                     0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_PROFILE_MAIN                 }, 0, 0, VE, "profile" },
39
+    { "high",           "",                     0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_PROFILE_HIGH                 }, 0, 0, VE, "profile" },
40
+    { "constrained_baseline", "",               0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_BASELINE }, 0, 0, VE, "profile" },
41
+    { "constrained_high",     "",               0,              AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH     }, 0, 0, VE, "profile" },
42
+
43
+    /// Profile Level
44
+    { "level",          "Profile Level",        OFFSET(level),  AV_OPT_TYPE_INT,   { .i64 = 0  }, 0, 62, VE, "level" },
45
+    { "auto",           "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 0  }, 0, 0,  VE, "level" },
46
+    { "1.0",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 10 }, 0, 0,  VE, "level" },
47
+    { "1.1",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 11 }, 0, 0,  VE, "level" },
48
+    { "1.2",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 12 }, 0, 0,  VE, "level" },
49
+    { "1.3",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 13 }, 0, 0,  VE, "level" },
50
+    { "2.0",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 20 }, 0, 0,  VE, "level" },
51
+    { "2.1",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 21 }, 0, 0,  VE, "level" },
52
+    { "2.2",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 22 }, 0, 0,  VE, "level" },
53
+    { "3.0",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 30 }, 0, 0,  VE, "level" },
54
+    { "3.1",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 31 }, 0, 0,  VE, "level" },
55
+    { "3.2",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 32 }, 0, 0,  VE, "level" },
56
+    { "4.0",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 40 }, 0, 0,  VE, "level" },
57
+    { "4.1",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 41 }, 0, 0,  VE, "level" },
58
+    { "4.2",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 42 }, 0, 0,  VE, "level" },
59
+    { "5.0",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 50 }, 0, 0,  VE, "level" },
60
+    { "5.1",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 51 }, 0, 0,  VE, "level" },
61
+    { "5.2",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 52 }, 0, 0,  VE, "level" },
62
+    { "6.0",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 60 }, 0, 0,  VE, "level" },
63
+    { "6.1",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 61 }, 0, 0,  VE, "level" },
64
+    { "6.2",            "",                     0,              AV_OPT_TYPE_CONST, { .i64 = 62 }, 0, 0,  VE, "level" },
65
+
66
+
67
+    /// Quality Preset
68
+    { "quality",        "Quality Preference",                   OFFSET(quality),    AV_OPT_TYPE_INT,   { .i64 = AMF_VIDEO_ENCODER_QUALITY_PRESET_SPEED    }, AMF_VIDEO_ENCODER_QUALITY_PRESET_BALANCED, AMF_VIDEO_ENCODER_QUALITY_PRESET_QUALITY, VE, "quality" },
69
+    { "speed",          "Prefer Speed",                         0,                  AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_QUALITY_PRESET_SPEED    },       0, 0, VE, "quality" },
70
+    { "balanced",       "Balanced",                             0,                  AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_QUALITY_PRESET_BALANCED },    0, 0, VE, "quality" },
71
+    { "quality",        "Prefer Quality",                       0,                  AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_QUALITY_PRESET_QUALITY  },     0, 0, VE, "quality" },
72
+
73
+    // Dynamic
74
+    /// Rate Control Method
75
+    { "rc",             "Rate Control Method",                  OFFSET(rate_control_mode), AV_OPT_TYPE_INT,   { .i64 = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_UNKNOWN }, AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_UNKNOWN, AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR, VE, "rc" },
76
+    { "cqp",            "Constant Quantization Parameter",      0,                         AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP             }, 0, 0, VE, "rc" },
77
+    { "cbr",            "Constant Bitrate",                     0,                         AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR                     }, 0, 0, VE, "rc" },
78
+    { "vbr_peak",       "Peak Contrained Variable Bitrate",     0,                         AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR    }, 0, 0, VE, "rc" },
79
+    { "vbr_latency",    "Latency Constrained Variable Bitrate", 0,                         AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR }, 0, 0, VE, "rc" },
80
+
81
+    /// Enforce HRD, Filler Data, VBAQ, Frame Skipping
82
+    { "enforce_hrd",    "Enforce HRD",                          OFFSET(enforce_hrd),        AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
83
+    { "filler_data",    "Filler Data Enable",                   OFFSET(filler_data),        AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
84
+    { "vbaq",           "Enable VBAQ",                          OFFSET(enable_vbaq),        AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
85
+    { "frame_skipping", "Rate Control Based Frame Skip",        OFFSET(skip_frame),         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
86
+
87
+    /// QP Values
88
+    { "qp_i",           "Quantization Parameter for I-Frame",   OFFSET(qp_i),               AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 51, VE },
89
+    { "qp_p",           "Quantization Parameter for P-Frame",   OFFSET(qp_p),               AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 51, VE },
90
+    { "qp_b",           "Quantization Parameter for B-Frame",   OFFSET(qp_b),               AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 51, VE },
91
+
92
+    /// Pre-Pass, Pre-Analysis, Two-Pass
93
+    { "preanalysis",    "Pre-Analysis Mode",                    OFFSET(preanalysis),        AV_OPT_TYPE_BOOL,{ .i64 = 0 }, 0, 1, VE, NULL },
94
+
95
+    /// Maximum Access Unit Size
96
+    { "max_au_size",    "Maximum Access Unit Size for rate control (in bits)",   OFFSET(max_au_size),        AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
97
+
98
+    /// Header Insertion Spacing
99
+    { "header_spacing", "Header Insertion Spacing",             OFFSET(header_spacing),     AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE },
100
+
101
+    /// B-Frames
102
+    // BPicturesPattern=bf
103
+    { "bf_delta_qp",    "B-Picture Delta QP",                   OFFSET(b_frame_delta_qp),   AV_OPT_TYPE_INT,  { .i64 = 4 }, -10, 10, VE },
104
+    { "bf_ref",         "Enable Reference to B-Frames",         OFFSET(b_frame_ref),        AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, VE },
105
+    { "bf_ref_delta_qp","Reference B-Picture Delta QP",         OFFSET(ref_b_frame_delta_qp), AV_OPT_TYPE_INT,  { .i64 = 4 }, -10, 10, VE },
106
+
107
+    /// Intra-Refresh
108
+    { "intra_refresh_mb","Intra Refresh MBs Number Per Slot in Macroblocks",       OFFSET(intra_refresh_mb),    AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
109
+
110
+    /// coder
111
+    { "coder",          "Coding Type",                          OFFSET(coding_mode),   AV_OPT_TYPE_INT,   { .i64 = AMF_VIDEO_ENCODER_UNDEFINED }, AMF_VIDEO_ENCODER_UNDEFINED, AMF_VIDEO_ENCODER_CALV, VE, "coder" },
112
+    { "auto",           "Automatic",                            0,                     AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_UNDEFINED }, 0, 0, VE, "coder" },
113
+    { "cavlc",          "Context Adaptive Variable-Length Coding", 0,                  AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_CALV },      0, 0, VE, "coder" },
114
+    { "cabac",          "Context Adaptive Binary Arithmetic Coding", 0,                AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_CABAC },     0, 0, VE, "coder" },
115
+
116
+    { "me_half_pel",    "Enable ME Half Pixel",                 OFFSET(me_half_pel),   AV_OPT_TYPE_BOOL,  { .i64 = 1 }, 0, 1, VE },
117
+    { "me_quarter_pel", "Enable ME Quarter Pixel",              OFFSET(me_quarter_pel),AV_OPT_TYPE_BOOL,  { .i64 = 1 }, 0, 1, VE },
118
+
119
+    { "aud",            "Inserts AU Delimiter NAL unit",        OFFSET(aud)          ,AV_OPT_TYPE_BOOL,  { .i64 = 0 }, 0, 1, VE },
120
+
121
+    { "log_to_dbg",     "Enable AMF logging to debug output",   OFFSET(log_to_dbg)    , AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
122
+
123
+    { NULL }
124
+};
125
+
126
+static av_cold int amf_encode_init_h264(AVCodecContext *avctx)
127
+{
128
+    int                              ret = 0;
129
+    AMF_RESULT                       res = AMF_OK;
130
+    AmfContext                      *ctx = avctx->priv_data;
131
+    AMFVariantStruct                 var = { 0 };
132
+    amf_int64                        profile = 0;
133
+    amf_int64                        profile_level = 0;
134
+    AMFBuffer                       *buffer;
135
+    AMFGuid                          guid;
136
+    AMFRate                          framerate;
137
+    AMFSize                          framesize = AMFConstructSize(avctx->width, avctx->height);
138
+    int                              deblocking_filter = (avctx->flags & AV_CODEC_FLAG_LOOP_FILTER) ? 1 : 0;
139
+
140
+    if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
141
+        framerate = AMFConstructRate(avctx->framerate.num, avctx->framerate.den);
142
+    } else {
143
+        framerate = AMFConstructRate(avctx->time_base.den, avctx->time_base.num * avctx->ticks_per_frame);
144
+    }
145
+
146
+    if ((ret = ff_amf_encode_init(avctx)) != 0)
147
+        return ret;
148
+
149
+    // Static parameters
150
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_USAGE, ctx->usage);
151
+
152
+    AMF_ASSIGN_PROPERTY_SIZE(res, ctx->encoder, AMF_VIDEO_ENCODER_FRAMESIZE, framesize);
153
+
154
+    AMF_ASSIGN_PROPERTY_RATE(res, ctx->encoder, AMF_VIDEO_ENCODER_FRAMERATE, framerate);
155
+
156
+    switch (avctx->profile) {
157
+    case FF_PROFILE_H264_BASELINE:
158
+        profile = AMF_VIDEO_ENCODER_PROFILE_BASELINE;
159
+        break;
160
+    case FF_PROFILE_H264_MAIN:
161
+        profile = AMF_VIDEO_ENCODER_PROFILE_MAIN;
162
+        break;
163
+    case FF_PROFILE_H264_HIGH:
164
+        profile = AMF_VIDEO_ENCODER_PROFILE_HIGH;
165
+        break;
166
+    case FF_PROFILE_H264_CONSTRAINED_BASELINE:
167
+        profile = AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_BASELINE;
168
+        break;
169
+    case (FF_PROFILE_H264_HIGH | FF_PROFILE_H264_CONSTRAINED):
170
+        profile = AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH;
171
+        break;
172
+    }
173
+    if (profile == 0) {
174
+        profile = ctx->profile;
175
+    }
176
+
177
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_PROFILE, profile);
178
+
179
+    profile_level = avctx->level;
180
+    if (profile_level == FF_LEVEL_UNKNOWN) {
181
+        profile_level = ctx->level;
182
+    }
183
+    if (profile_level != 0) {
184
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_PROFILE_LEVEL, profile_level);
185
+    }
186
+
187
+    // Maximum Reference Frames
188
+    if (avctx->refs != -1) {
189
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_MAX_NUM_REFRAMES, avctx->refs);
190
+    }
191
+    if (avctx->sample_aspect_ratio.den && avctx->sample_aspect_ratio.num) {
192
+        AMFRatio ratio = AMFConstructRatio(avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
193
+        AMF_ASSIGN_PROPERTY_RATIO(res, ctx->encoder, AMF_VIDEO_ENCODER_ASPECT_RATIO, ratio);
194
+    }
195
+
196
+    /// Color Range (Partial/TV/MPEG or Full/PC/JPEG)
197
+    if (avctx->color_range == AVCOL_RANGE_JPEG) {
198
+        AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_FULL_RANGE_COLOR, 1);
199
+    }
200
+
201
+    // autodetect rate control method
202
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_UNKNOWN) {
203
+        if (ctx->qp_i != -1 || ctx->qp_p != -1 || ctx->qp_b != -1) {
204
+            ctx->rate_control_mode = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP;
205
+            av_log(ctx, AV_LOG_DEBUG, "Rate control turned to CQP\n");
206
+        } else if (avctx->rc_max_rate > 0 ) {
207
+            ctx->rate_control_mode = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
208
+            av_log(ctx, AV_LOG_DEBUG, "Rate control turned to Peak VBR\n");
209
+        } else {
210
+            ctx->rate_control_mode = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR;
211
+            av_log(ctx, AV_LOG_DEBUG, "Rate control turned to CBR\n");
212
+        }
213
+    }
214
+
215
+
216
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP) {
217
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_RATE_CONTROL_PREANALYSIS_ENABLE, AMF_VIDEO_ENCODER_PREENCODE_DISABLED);
218
+        if (ctx->preanalysis)
219
+            av_log(ctx, AV_LOG_WARNING, "Pre-Analysis is not supported by cqp Rate Control Method, automatically disabled\n");
220
+    } else {
221
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_RATE_CONTROL_PREANALYSIS_ENABLE, ctx->preanalysis);
222
+    }
223
+
224
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_QUALITY_PRESET, ctx->quality);
225
+
226
+    // Initialize Encoder
227
+    res = ctx->encoder->pVtbl->Init(ctx->encoder, ctx->format, avctx->width, avctx->height);
228
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "encoder->Init() failed with error %d\n", res);
229
+
230
+    // Dynamic parmaters
231
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD, ctx->rate_control_mode);
232
+
233
+    /// VBV Buffer
234
+    if (avctx->rc_buffer_size != 0) {
235
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_VBV_BUFFER_SIZE, avctx->rc_buffer_size);
236
+        if (avctx->rc_initial_buffer_occupancy != 0) {
237
+            int amf_buffer_fullness = avctx->rc_initial_buffer_occupancy * 64 / avctx->rc_buffer_size;
238
+            if (amf_buffer_fullness > 64)
239
+                amf_buffer_fullness = 64;
240
+            AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_INITIAL_VBV_BUFFER_FULLNESS, amf_buffer_fullness);
241
+        }
242
+    }
243
+    /// Maximum Access Unit Size
244
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_MAX_AU_SIZE, ctx->max_au_size);
245
+
246
+    if (ctx->max_au_size)
247
+        ctx->enforce_hrd = 1;
248
+
249
+    // QP Minimum / Maximum
250
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP) {
251
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_MIN_QP, 0);
252
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_MAX_QP, 51);
253
+    } else {
254
+        if (avctx->qmin != -1) {
255
+            int qval = avctx->qmin > 51 ? 51 : avctx->qmin;
256
+            AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_MIN_QP, qval);
257
+        }
258
+        if (avctx->qmax != -1) {
259
+            int qval = avctx->qmax > 51 ? 51 : avctx->qmax;
260
+            AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_MAX_QP, qval);
261
+        }
262
+    }
263
+    // QP Values
264
+    if (ctx->qp_i != -1)
265
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_QP_I, ctx->qp_i);
266
+    if (ctx->qp_p != -1)
267
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_QP_P, ctx->qp_p);
268
+    if (ctx->qp_b != -1)
269
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_QP_B, ctx->qp_b);
270
+
271
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_TARGET_BITRATE, avctx->bit_rate);
272
+
273
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR) {
274
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_PEAK_BITRATE, avctx->bit_rate);
275
+    }
276
+    if (avctx->rc_max_rate) {
277
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_PEAK_BITRATE, avctx->rc_max_rate);
278
+    } else if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR) {
279
+        av_log(ctx, AV_LOG_WARNING, "rate control mode is PEAK_CONSTRAINED_VBR but rc_max_rate is not set\n");
280
+    }
281
+    // Enforce HRD, Filler Data, VBAQ, Frame Skipping, Deblocking Filter
282
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_ENFORCE_HRD, !!ctx->enforce_hrd);
283
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_FILLER_DATA_ENABLE, !!ctx->filler_data);
284
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_RATE_CONTROL_SKIP_FRAME_ENABLE, !!ctx->skip_frame);
285
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP) {
286
+        AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_ENABLE_VBAQ, 0);
287
+        if (ctx->enable_vbaq)
288
+            av_log(ctx, AV_LOG_WARNING, "VBAQ is not supported by cqp Rate Control Method, automatically disabled\n");
289
+    } else {
290
+        AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_ENABLE_VBAQ, !!ctx->enable_vbaq);
291
+    }
292
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_DE_BLOCKING_FILTER, !!deblocking_filter);
293
+
294
+    // B-Frames
295
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_B_PIC_PATTERN, avctx->max_b_frames);
296
+    if (res != AMF_OK) {
297
+        res = ctx->encoder->pVtbl->GetProperty(ctx->encoder, AMF_VIDEO_ENCODER_B_PIC_PATTERN, &var);
298
+        av_log(ctx, AV_LOG_WARNING, "B-frames=%d is not supported by this GPU, switched to %d\n",
299
+            avctx->max_b_frames, (int)var.int64Value);
300
+        avctx->max_b_frames = (int)var.int64Value;
301
+    }
302
+    if (avctx->max_b_frames) {
303
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_B_PIC_DELTA_QP, ctx->b_frame_delta_qp);
304
+        AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_B_REFERENCE_ENABLE, !!ctx->b_frame_ref);
305
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_REF_B_PIC_DELTA_QP, ctx->ref_b_frame_delta_qp);
306
+    }
307
+
308
+    // Keyframe Interval
309
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_IDR_PERIOD, avctx->gop_size);
310
+
311
+    // Header Insertion Spacing
312
+    if (ctx->header_spacing >= 0)
313
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEADER_INSERTION_SPACING, ctx->header_spacing);
314
+
315
+    // Intra-Refresh, Slicing
316
+    if (ctx->intra_refresh_mb > 0)
317
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_INTRA_REFRESH_NUM_MBS_PER_SLOT, ctx->intra_refresh_mb);
318
+    if (avctx->slices > 1)
319
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_SLICES_PER_FRAME, avctx->slices);
320
+
321
+    // Coding
322
+    if (ctx->coding_mode != 0)
323
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_CABAC_ENABLE, ctx->coding_mode);
324
+
325
+    // Motion Estimation
326
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_MOTION_HALF_PIXEL, !!ctx->me_half_pel);
327
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_MOTION_QUARTERPIXEL, !!ctx->me_quarter_pel);
328
+
329
+    // fill extradata
330
+    res = AMFVariantInit(&var);
331
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "AMFVariantInit() failed with error %d\n", res);
332
+
333
+    res = ctx->encoder->pVtbl->GetProperty(ctx->encoder, AMF_VIDEO_ENCODER_EXTRADATA, &var);
334
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "GetProperty(AMF_VIDEO_ENCODER_EXTRADATA) failed with error %d\n", res);
335
+    AMF_RETURN_IF_FALSE(ctx, var.pInterface != NULL, AVERROR_BUG, "GetProperty(AMF_VIDEO_ENCODER_EXTRADATA) returned NULL\n");
336
+
337
+    guid = IID_AMFBuffer();
338
+
339
+    res = var.pInterface->pVtbl->QueryInterface(var.pInterface, &guid, (void**)&buffer); // query for buffer interface
340
+    if (res != AMF_OK) {
341
+        var.pInterface->pVtbl->Release(var.pInterface);
342
+    }
343
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "QueryInterface(IID_AMFBuffer) failed with error %d\n", res);
344
+
345
+    avctx->extradata_size = (int)buffer->pVtbl->GetSize(buffer);
346
+    avctx->extradata = av_mallocz(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
347
+    if (!avctx->extradata) {
348
+        buffer->pVtbl->Release(buffer);
349
+        var.pInterface->pVtbl->Release(var.pInterface);
350
+        return AVERROR(ENOMEM);
351
+    }
352
+    memcpy(avctx->extradata, buffer->pVtbl->GetNative(buffer), avctx->extradata_size);
353
+
354
+    buffer->pVtbl->Release(buffer);
355
+    var.pInterface->pVtbl->Release(var.pInterface);
356
+
357
+    return 0;
358
+}
359
+
360
+static const AVCodecDefault defaults[] = {
361
+    { "refs",       "-1"  },
362
+    { "aspect",     "0"   },
363
+    { "sar",        "0"   },
364
+    { "qmin",       "-1"  },
365
+    { "qmax",       "-1"  },
366
+    { "b",          "2M"  },
367
+    { "g",          "250" },
368
+    { "slices",     "1"   },
369
+    { NULL                },
370
+};
371
+
372
+static const AVClass h264_amf_class = {
373
+    .class_name = "h264_amf",
374
+    .item_name = av_default_item_name,
375
+    .option = options,
376
+    .version = LIBAVUTIL_VERSION_INT,
377
+};
378
+//TODO declare as HW encoder when available
379
+AVCodec ff_h264_amf_encoder = {
380
+    .name           = "h264_amf",
381
+    .long_name      = NULL_IF_CONFIG_SMALL("AMD AMF H.264 Encoder"),
382
+    .type           = AVMEDIA_TYPE_VIDEO,
383
+    .id             = AV_CODEC_ID_H264,
384
+    .init           = amf_encode_init_h264,
385
+    .send_frame     = ff_amf_send_frame,
386
+    .receive_packet = ff_amf_receive_packet,
387
+    .close          = ff_amf_encode_close,
388
+    .priv_data_size = sizeof(AmfContext),
389
+    .priv_class     = &h264_amf_class,
390
+    .defaults       = defaults,
391
+    .capabilities   = AV_CODEC_CAP_DELAY,
392
+    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
393
+    .pix_fmts       = ff_amf_pix_fmts,
394
+};
0 395
new file mode 100644
... ...
@@ -0,0 +1,326 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+#include "libavutil/internal.h"
19
+#include "libavutil/opt.h"
20
+#include "amfenc.h"
21
+#include "internal.h"
22
+
23
+#define OFFSET(x) offsetof(AmfContext, x)
24
+#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
25
+static const AVOption options[] = {
26
+    { "usage",          "Set the encoding usage",             OFFSET(usage),          AV_OPT_TYPE_INT,   { .i64 = AMF_VIDEO_ENCODER_HEVC_USAGE_TRANSCONDING }, AMF_VIDEO_ENCODER_HEVC_USAGE_TRANSCONDING, AMF_VIDEO_ENCODER_HEVC_USAGE_WEBCAM, VE, "usage" },
27
+    { "transcoding",    "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_USAGE_TRANSCONDING },         0, 0, VE, "usage" },
28
+    { "ultralowlatency","", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_USAGE_ULTRA_LOW_LATENCY },    0, 0, VE, "usage" },
29
+    { "lowlatency",     "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_USAGE_LOW_LATENCY },          0, 0, VE, "usage" },
30
+    { "webcam",         "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_USAGE_WEBCAM },               0, 0, VE, "usage" },
31
+
32
+    { "profile",        "Set the profile (default main)",           OFFSET(profile),   AV_OPT_TYPE_INT,{ .i64 = AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN }, AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN, AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN, VE, "profile" },
33
+    { "main",           "", 0,                      AV_OPT_TYPE_CONST,{ .i64 = AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN }, 0, 0, VE, "profile" },
34
+
35
+    { "profile_tier",   "Set the profile tier (default main)",      OFFSET(tier), AV_OPT_TYPE_INT,{ .i64 = AMF_VIDEO_ENCODER_HEVC_TIER_MAIN }, AMF_VIDEO_ENCODER_HEVC_TIER_MAIN, AMF_VIDEO_ENCODER_HEVC_TIER_HIGH, VE, "tier" },
36
+    { "main",           "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_TIER_MAIN }, 0, 0, VE, "tier" },
37
+    { "high",           "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_TIER_HIGH }, 0, 0, VE, "tier" },
38
+
39
+    { "level",          "Set the encoding level (default auto)",    OFFSET(level), AV_OPT_TYPE_INT,{ .i64 = 0 }, 0, AMF_LEVEL_6_2, VE, "level" },
40
+    { "auto",           "", 0, AV_OPT_TYPE_CONST, { .i64 = 0             }, 0, 0, VE, "level" },
41
+    { "1.0",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_1   }, 0, 0, VE, "level" },
42
+    { "2.0",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_2   }, 0, 0, VE, "level" },
43
+    { "2.1",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_2_1 }, 0, 0, VE, "level" },
44
+    { "3.0",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_3   }, 0, 0, VE, "level" },
45
+    { "3.1",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_3_1 }, 0, 0, VE, "level" },
46
+    { "4.0",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_4   }, 0, 0, VE, "level" },
47
+    { "4.1",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_4_1 }, 0, 0, VE, "level" },
48
+    { "5.0",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_5   }, 0, 0, VE, "level" },
49
+    { "5.1",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_5_1 }, 0, 0, VE, "level" },
50
+    { "5.2",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_5_2 }, 0, 0, VE, "level" },
51
+    { "6.0",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_6   }, 0, 0, VE, "level" },
52
+    { "6.1",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_6_1 }, 0, 0, VE, "level" },
53
+    { "6.2",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_LEVEL_6_2 }, 0, 0, VE, "level" },
54
+
55
+    { "quality",        "Set the encoding quality",                 OFFSET(quality),      AV_OPT_TYPE_INT,   { .i64 = AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED }, AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_QUALITY, AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED, VE, "quality" },
56
+    { "balanced",       "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_BALANCED }, 0, 0, VE, "quality" },
57
+    { "speed",          "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED    }, 0, 0, VE, "quality" },
58
+    { "quality",        "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_QUALITY  }, 0, 0, VE, "quality" },
59
+
60
+    { "rc",             "Set the rate control mode",            OFFSET(rate_control_mode), AV_OPT_TYPE_INT, { .i64 = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_UNKNOWN }, AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_UNKNOWN, AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR, VE, "rc" },
61
+    { "cqp",            "Constant Quantization Parameter",      0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP             }, 0, 0, VE, "rc" },
62
+    { "cbr",            "Constant Bitrate",                     0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR                     }, 0, 0, VE, "rc" },
63
+    { "vbr_peak",       "Peak Contrained Variable Bitrate",     0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR    }, 0, 0, VE, "rc" },
64
+    { "vbr_latency",    "Latency Constrained Variable Bitrate", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR }, 0, 0, VE, "rc" },
65
+
66
+    { "header_insertion_mode",        "Set header insertion mode",  OFFSET(header_insertion_mode),      AV_OPT_TYPE_INT,{ .i64 = AMF_VIDEO_ENCODER_HEVC_HEADER_INSERTION_MODE_NONE }, AMF_VIDEO_ENCODER_HEVC_HEADER_INSERTION_MODE_NONE, AMF_VIDEO_ENCODER_HEVC_HEADER_INSERTION_MODE_IDR_ALIGNED, VE, "hdrmode" },
67
+    { "none",           "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_HEADER_INSERTION_MODE_NONE        }, 0, 0, VE, "hdrmode" },
68
+    { "gop",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_HEADER_INSERTION_MODE_GOP_ALIGNED }, 0, 0, VE, "hdrmode" },
69
+    { "idr",            "", 0, AV_OPT_TYPE_CONST, { .i64 = AMF_VIDEO_ENCODER_HEVC_HEADER_INSERTION_MODE_IDR_ALIGNED }, 0, 0, VE, "hdrmode" },
70
+
71
+    { "gops_per_idr",    "GOPs per IDR 0-no IDR will be inserted",  OFFSET(gops_per_idr),  AV_OPT_TYPE_INT,  { .i64 = 60 },  0, INT_MAX, VE },
72
+    { "preanalysis",    "Enable preanalysis",                       OFFSET(preanalysis),   AV_OPT_TYPE_BOOL, { .i64 = 0  },  0, 1, VE},
73
+    { "vbaq",           "Enable VBAQ",                              OFFSET(enable_vbaq),   AV_OPT_TYPE_BOOL, { .i64 = 0  },  0, 1, VE},
74
+    { "enforce_hrd",    "Enforce HRD",                              OFFSET(enforce_hrd),   AV_OPT_TYPE_BOOL, { .i64 = 0  },  0, 1, VE},
75
+    { "filler_data",    "Filler Data Enable",                       OFFSET(filler_data),   AV_OPT_TYPE_BOOL, { .i64 = 0  },  0, 1, VE},
76
+    { "max_au_size",    "Maximum Access Unit Size for rate control (in bits)", OFFSET(max_au_size),   AV_OPT_TYPE_INT,{ .i64 = 0 }, 0, INT_MAX, VE},
77
+    { "min_qp_i",       "min quantization parameter for I-frame",   OFFSET(min_qp_i),      AV_OPT_TYPE_INT, { .i64 = -1  }, -1, 51, VE },
78
+    { "max_qp_i",       "max quantization parameter for I-frame",   OFFSET(max_qp_i),      AV_OPT_TYPE_INT, { .i64 = -1  }, -1, 51, VE },
79
+    { "min_qp_p",       "min quantization parameter for P-frame",   OFFSET(min_qp_p),      AV_OPT_TYPE_INT, { .i64 = -1  }, -1, 51, VE },
80
+    { "max_qp_p",       "max quantization parameter for P-frame",   OFFSET(max_qp_p),      AV_OPT_TYPE_INT, { .i64 = -1  }, -1, 51, VE },
81
+    { "qp_p",           "quantization parameter for P-frame",       OFFSET(qp_p),          AV_OPT_TYPE_INT, { .i64 = -1  }, -1, 51, VE },
82
+    { "qp_i",           "quantization parameter for I-frame",       OFFSET(qp_i),          AV_OPT_TYPE_INT, { .i64 = -1  }, -1, 51, VE },
83
+    { "skip_frame",     "Rate Control Based Frame Skip",            OFFSET(skip_frame),    AV_OPT_TYPE_BOOL,{ .i64 = 0   },  0, 1, VE },
84
+    { "me_half_pel",    "Enable ME Half Pixel",                     OFFSET(me_half_pel),   AV_OPT_TYPE_BOOL,{ .i64 = 1   },  0, 1, VE },
85
+    { "me_quarter_pel", "Enable ME Quarter Pixel ",                 OFFSET(me_quarter_pel),AV_OPT_TYPE_BOOL,{ .i64 = 1   },  0, 1, VE },
86
+
87
+    { "aud",            "Inserts AU Delimiter NAL unit",            OFFSET(aud)           ,AV_OPT_TYPE_BOOL,{ .i64 = 0 }, 0, 1, VE },
88
+
89
+    { "log_to_dbg",     "Enable AMF logging to debug output",   OFFSET(log_to_dbg), AV_OPT_TYPE_BOOL,{ .i64 = 0 }, 0, 1, VE },
90
+    { NULL }
91
+};
92
+
93
+static av_cold int amf_encode_init_hevc(AVCodecContext *avctx)
94
+{
95
+    int                 ret = 0;
96
+    AMF_RESULT          res = AMF_OK;
97
+    AmfContext         *ctx = avctx->priv_data;
98
+    AMFVariantStruct    var = {0};
99
+    amf_int64           profile = 0;
100
+    amf_int64           profile_level = 0;
101
+    AMFBuffer          *buffer;
102
+    AMFGuid             guid;
103
+    AMFRate             framerate;
104
+    AMFSize             framesize = AMFConstructSize(avctx->width, avctx->height);
105
+    int                 deblocking_filter = (avctx->flags & AV_CODEC_FLAG_LOOP_FILTER) ? 1 : 0;
106
+
107
+    if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
108
+        framerate = AMFConstructRate(avctx->framerate.num, avctx->framerate.den);
109
+    } else {
110
+        framerate = AMFConstructRate(avctx->time_base.den, avctx->time_base.num * avctx->ticks_per_frame);
111
+    }
112
+
113
+    if ((ret = ff_amf_encode_init(avctx)) < 0)
114
+        return ret;
115
+
116
+    // init static parameters
117
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_USAGE, ctx->usage);
118
+
119
+    AMF_ASSIGN_PROPERTY_SIZE(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_FRAMESIZE, framesize);
120
+
121
+    AMF_ASSIGN_PROPERTY_RATE(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_FRAMERATE, framerate);
122
+
123
+    switch (avctx->profile) {
124
+    case FF_PROFILE_HEVC_MAIN:
125
+        profile = AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN;
126
+        break;
127
+    default:
128
+        break;
129
+    }
130
+    if (profile == 0) {
131
+        profile = ctx->profile;
132
+    }
133
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_PROFILE, profile);
134
+
135
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_TIER, ctx->tier);
136
+
137
+    profile_level = avctx->level;
138
+    if (profile_level == 0) {
139
+        profile_level = ctx->level;
140
+    }
141
+    if (profile_level != 0) {
142
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_PROFILE_LEVEL, profile_level);
143
+    }
144
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET, ctx->quality);
145
+    // Maximum Reference Frames
146
+    if (avctx->refs != 0) {
147
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MAX_NUM_REFRAMES, avctx->refs);
148
+    }
149
+    // Aspect Ratio
150
+    if (avctx->sample_aspect_ratio.den && avctx->sample_aspect_ratio.num) {
151
+        AMFRatio ratio = AMFConstructRatio(avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
152
+        AMF_ASSIGN_PROPERTY_RATIO(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_ASPECT_RATIO, ratio);
153
+    }
154
+
155
+    // Picture control properties
156
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_NUM_GOPS_PER_IDR, ctx->gops_per_idr);
157
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_GOP_SIZE, avctx->gop_size);
158
+    if (avctx->slices > 1) {
159
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_SLICES_PER_FRAME, avctx->slices);
160
+    }
161
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_DE_BLOCKING_FILTER_DISABLE, deblocking_filter);
162
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_HEADER_INSERTION_MODE, ctx->header_insertion_mode);
163
+
164
+    // Rate control
165
+    // autodetect rate control method
166
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_UNKNOWN) {
167
+        if (ctx->min_qp_i != -1 || ctx->max_qp_i != -1 ||
168
+            ctx->min_qp_p != -1 || ctx->max_qp_p != -1 ||
169
+            ctx->qp_i !=-1 || ctx->qp_p != -1) {
170
+            ctx->rate_control_mode = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP;
171
+            av_log(ctx, AV_LOG_DEBUG, "Rate control turned to CQP\n");
172
+        } else if (avctx->rc_max_rate > 0) {
173
+            ctx->rate_control_mode = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
174
+            av_log(ctx, AV_LOG_DEBUG, "Rate control turned to Peak VBR\n");
175
+        } else {
176
+            ctx->rate_control_mode = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR;
177
+            av_log(ctx, AV_LOG_DEBUG, "Rate control turned to CBR\n");
178
+        }
179
+    }
180
+
181
+
182
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD, ctx->rate_control_mode);
183
+    if (avctx->rc_buffer_size) {
184
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_VBV_BUFFER_SIZE, avctx->rc_buffer_size);
185
+
186
+        if (avctx->rc_initial_buffer_occupancy != 0) {
187
+            int amf_buffer_fullness = avctx->rc_initial_buffer_occupancy * 64 / avctx->rc_buffer_size;
188
+            if (amf_buffer_fullness > 64)
189
+                amf_buffer_fullness = 64;
190
+            AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_INITIAL_VBV_BUFFER_FULLNESS, amf_buffer_fullness);
191
+        }
192
+    }
193
+    // Pre-Pass, Pre-Analysis, Two-Pass
194
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_PREANALYSIS_ENABLE, ctx->preanalysis);
195
+
196
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP) {
197
+        AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_ENABLE_VBAQ, false);
198
+        if (ctx->enable_vbaq)
199
+            av_log(ctx, AV_LOG_WARNING, "VBAQ is not supported by cqp Rate Control Method, automatically disabled\n");
200
+    } else {
201
+        AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_ENABLE_VBAQ, !!ctx->enable_vbaq);
202
+    }
203
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MOTION_HALF_PIXEL, ctx->me_half_pel);
204
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MOTION_QUARTERPIXEL, ctx->me_quarter_pel);
205
+
206
+    // init encoder
207
+    res = ctx->encoder->pVtbl->Init(ctx->encoder, ctx->format, avctx->width, avctx->height);
208
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "encoder->Init() failed with error %d\n", res);
209
+
210
+    // init dynamic rate control params
211
+    if (ctx->max_au_size)
212
+        ctx->enforce_hrd = 1;
213
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_ENFORCE_HRD, ctx->enforce_hrd);
214
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_FILLER_DATA_ENABLE, ctx->filler_data);
215
+
216
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_TARGET_BITRATE, avctx->bit_rate);
217
+
218
+    if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR) {
219
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_PEAK_BITRATE, avctx->bit_rate);
220
+    }
221
+    if (avctx->rc_max_rate) {
222
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_PEAK_BITRATE, avctx->rc_max_rate);
223
+    } else if (ctx->rate_control_mode == AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR) {
224
+        av_log(ctx, AV_LOG_WARNING, "rate control mode is PEAK_CONSTRAINED_VBR but rc_max_rate is not set\n");
225
+    }
226
+
227
+    // init dynamic picture control params
228
+    AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MAX_AU_SIZE, ctx->max_au_size);
229
+
230
+    if (ctx->min_qp_i != -1) {
231
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MIN_QP_I, ctx->min_qp_i);
232
+    } else if (avctx->qmin != -1) {
233
+        int qval = avctx->qmin > 51 ? 51 : avctx->qmin;
234
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MIN_QP_I, qval);
235
+    }
236
+    if (ctx->max_qp_i != -1) {
237
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MAX_QP_I, ctx->max_qp_i);
238
+    } else if (avctx->qmax != -1) {
239
+        int qval = avctx->qmax > 51 ? 51 : avctx->qmax;
240
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MAX_QP_I, qval);
241
+    }
242
+    if (ctx->min_qp_p != -1) {
243
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MIN_QP_P, ctx->min_qp_p);
244
+    } else if (avctx->qmin != -1) {
245
+        int qval = avctx->qmin > 51 ? 51 : avctx->qmin;
246
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MIN_QP_P, qval);
247
+    }
248
+    if (ctx->max_qp_p != -1) {
249
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MAX_QP_P, ctx->max_qp_p);
250
+    } else if (avctx->qmax != -1) {
251
+        int qval = avctx->qmax > 51 ? 51 : avctx->qmax;
252
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_MAX_QP_P, qval);
253
+    }
254
+
255
+    if (ctx->qp_p != -1) {
256
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_QP_I, ctx->qp_p);
257
+    }
258
+    if (ctx->qp_i != -1) {
259
+        AMF_ASSIGN_PROPERTY_INT64(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_QP_P, ctx->qp_i);
260
+    }
261
+    AMF_ASSIGN_PROPERTY_BOOL(res, ctx->encoder, AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_SKIP_FRAME_ENABLE, ctx->skip_frame);
262
+
263
+
264
+    // fill extradata
265
+    res = AMFVariantInit(&var);
266
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "AMFVariantInit() failed with error %d\n", res);
267
+
268
+    res = ctx->encoder->pVtbl->GetProperty(ctx->encoder, AMF_VIDEO_ENCODER_HEVC_EXTRADATA, &var);
269
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "GetProperty(AMF_VIDEO_ENCODER_EXTRADATA) failed with error %d\n", res);
270
+    AMF_RETURN_IF_FALSE(ctx, var.pInterface != NULL, AVERROR_BUG, "GetProperty(AMF_VIDEO_ENCODER_EXTRADATA) returned NULL\n");
271
+
272
+    guid = IID_AMFBuffer();
273
+
274
+    res = var.pInterface->pVtbl->QueryInterface(var.pInterface, &guid, (void**)&buffer); // query for buffer interface
275
+    if (res != AMF_OK) {
276
+        var.pInterface->pVtbl->Release(var.pInterface);
277
+    }
278
+    AMF_RETURN_IF_FALSE(ctx, res == AMF_OK, AVERROR_BUG, "QueryInterface(IID_AMFBuffer) failed with error %d\n", res);
279
+
280
+    avctx->extradata_size = (int)buffer->pVtbl->GetSize(buffer);
281
+    avctx->extradata = av_mallocz(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
282
+    if (!avctx->extradata) {
283
+        buffer->pVtbl->Release(buffer);
284
+        var.pInterface->pVtbl->Release(var.pInterface);
285
+        return AVERROR(ENOMEM);
286
+    }
287
+    memcpy(avctx->extradata, buffer->pVtbl->GetNative(buffer), avctx->extradata_size);
288
+
289
+    buffer->pVtbl->Release(buffer);
290
+    var.pInterface->pVtbl->Release(var.pInterface);
291
+
292
+    return 0;
293
+}
294
+static const AVCodecDefault defaults[] = {
295
+    { "refs",       "-1"  },
296
+    { "aspect",     "0"   },
297
+    { "sar",        "0"   },
298
+    { "b",          "2M"  },
299
+    { "g",          "250" },
300
+    { "slices",     "1"   },
301
+    { NULL                },
302
+};
303
+static const AVClass hevc_amf_class = {
304
+    .class_name = "hevc_amf",
305
+    .item_name = av_default_item_name,
306
+    .option = options,
307
+    .version = LIBAVUTIL_VERSION_INT,
308
+};
309
+//TODO declare as HW encoder when available
310
+AVCodec ff_hevc_amf_encoder = {
311
+    .name           = "hevc_amf",
312
+    .long_name      = NULL_IF_CONFIG_SMALL("AMD AMF HEVC encoder"),
313
+    .type           = AVMEDIA_TYPE_VIDEO,
314
+    .id             = AV_CODEC_ID_HEVC,
315
+    .init           = amf_encode_init_hevc,
316
+    .send_frame     = ff_amf_send_frame,
317
+    .receive_packet = ff_amf_receive_packet,
318
+    .close          = ff_amf_encode_close,
319
+    .priv_data_size = sizeof(AmfContext),
320
+    .priv_class     = &hevc_amf_class,
321
+    .defaults       = defaults,
322
+    .capabilities   = AV_CODEC_CAP_DELAY,
323
+    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
324
+    .pix_fmts       = ff_amf_pix_fmts,
325
+};