qsv: Update SDK version to v2022.2.4
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / qsv / gstqsvh264enc.cpp
1 /* GStreamer
2  * Copyright (C) 2021 Seungha Yang <seungha@centricular.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "gstqsvh264enc.h"
25 #include <gst/base/gstbytewriter.h>
26 #include <gst/codecparsers/gsth264parser.h>
27 #include <vector>
28 #include <string>
29 #include <set>
30 #include <string.h>
31
32 #ifdef G_OS_WIN32
33 #include <gst/d3d11/gstd3d11.h>
34 #else
35 #include <gst/va/gstva.h>
36 #endif
37
38 GST_DEBUG_CATEGORY_STATIC (gst_qsv_h264_enc_debug);
39 #define GST_CAT_DEFAULT gst_qsv_h264_enc_debug
40
41 typedef enum
42 {
43   GST_QSV_H264_ENC_SEI_INSERT,
44   GST_QSV_H264_ENC_SEI_INSERT_AND_DROP,
45   GST_QSV_H264_ENC_SEI_DISABLED,
46 } GstQsvH264EncSeiInsertMode;
47
48 #define GST_TYPE_QSV_H264_ENC_SEI_INSERT_MODE (gst_qsv_h264_enc_sei_insert_mode_get_type ())
49 static GType
50 gst_qsv_h264_enc_sei_insert_mode_get_type (void)
51 {
52   static GType sei_insert_mode_type = 0;
53   static const GEnumValue insert_modes[] = {
54     {GST_QSV_H264_ENC_SEI_INSERT, "Insert SEI", "insert"},
55     {GST_QSV_H264_ENC_SEI_INSERT_AND_DROP,
56           "Insert SEI and remove corresponding meta from output buffer",
57         "insert-and-drop"},
58     {GST_QSV_H264_ENC_SEI_DISABLED, "Disable SEI insertion", "disabled"},
59     {0, nullptr, nullptr}
60   };
61
62   if (g_once_init_enter (&sei_insert_mode_type)) {
63     GType type =
64         g_enum_register_static ("GstQsvH264EncSeiInsertMode", insert_modes);
65     g_once_init_leave (&sei_insert_mode_type, type);
66   }
67
68   return sei_insert_mode_type;
69 }
70
71 #define GST_TYPE_QSV_H264_ENC_RATE_CONTROL (gst_qsv_h264_enc_rate_control_get_type ())
72 static GType
73 gst_qsv_h264_enc_rate_control_get_type (void)
74 {
75   static GType rate_control_type = 0;
76   static const GEnumValue rate_controls[] = {
77     {MFX_RATECONTROL_CBR, "Constant Bitrate", "cbr"},
78     {MFX_RATECONTROL_VBR, "Variable Bitrate", "vbr"},
79     {MFX_RATECONTROL_CQP, "Constant Quantizer", "cqp"},
80     {MFX_RATECONTROL_AVBR, "Average Variable Bitrate", "avbr"},
81     {MFX_RATECONTROL_LA, "VBR with look ahead (Non HRD compliant)", "la_vbr"},
82     {MFX_RATECONTROL_ICQ, "Intelligent CQP", "icq"},
83     {MFX_RATECONTROL_VCM, "Video Conferencing Mode (Non HRD compliant)", "vcm"},
84     {MFX_RATECONTROL_LA_ICQ, "Intelligent CQP with LA (Non HRD compliant)",
85         "la_icq"},
86     {MFX_RATECONTROL_LA_HRD, "HRD compliant LA", "la_hrd"},
87     {MFX_RATECONTROL_QVBR, "VBR with CQP", "qvbr"},
88     {0, nullptr, nullptr}
89   };
90
91   if (g_once_init_enter (&rate_control_type)) {
92     GType type =
93         g_enum_register_static ("GstQsvH264EncRateControl", rate_controls);
94     g_once_init_leave (&rate_control_type, type);
95   }
96
97   return rate_control_type;
98 }
99
100 #define GST_TYPE_QSV_H264_ENC_RC_LOOKAHEAD_DS (gst_qsv_h264_enc_rc_lookahead_ds_get_type ())
101 static GType
102 gst_qsv_h264_enc_rc_lookahead_ds_get_type (void)
103 {
104   static GType rc_lookahead_ds_type = 0;
105   static const GEnumValue rc_lookahead_ds[] = {
106     {MFX_LOOKAHEAD_DS_UNKNOWN, "Unknown", "unknown"},
107     {MFX_LOOKAHEAD_DS_OFF, "Do not use down sampling", "off"},
108     {MFX_LOOKAHEAD_DS_2x,
109         "Down sample frames two times before estimation", "2x"},
110     {MFX_LOOKAHEAD_DS_4x,
111         "Down sample frames four times before estimation", "4x"},
112     {0, nullptr, nullptr}
113   };
114
115   if (g_once_init_enter (&rc_lookahead_ds_type)) {
116     GType type =
117         g_enum_register_static ("GstQsvH264EncRCLookAheadDS", rc_lookahead_ds);
118     g_once_init_leave (&rc_lookahead_ds_type, type);
119   }
120
121   return rc_lookahead_ds_type;
122 }
123
124 enum
125 {
126   PROP_0,
127   PROP_CABAC,
128   PROP_MIN_QP_I,
129   PROP_MIN_QP_P,
130   PROP_MIN_QP_B,
131   PROP_MAX_QP_I,
132   PROP_MAX_QP_P,
133   PROP_MAX_QP_B,
134   PROP_QP_I,
135   PROP_QP_P,
136   PROP_QP_B,
137   PROP_GOP_SIZE,
138   PROP_IDR_INTERVAL,
139   PROP_B_FRAMES,
140   PROP_REF_FRAMES,
141   PROP_BITRATE,
142   PROP_MAX_BITRATE,
143   PROP_RATE_CONTROL,
144   PROP_RC_LOOKAHEAD,
145   PROP_RC_LOOKAHEAD_DS,
146   PROP_AVBR_ACCURACY,
147   PROP_AVBR_CONVERGENCE,
148   PROP_ICQ_QUALITY,
149   PROP_QVBR_QUALITY,
150   PROP_DISABLE_HRD_CONFORMANCE,
151   PROP_CC_INSERT,
152 };
153
154 #define DEFAULT_CABAC MFX_CODINGOPTION_UNKNOWN
155 #define DEFAULT_QP 0
156 #define DEFAULT_GOP_SIZE 30
157 #define DEFAULT_IDR_INTERVAL 0
158 #define DEFAULT_B_FRAMES 0
159 #define DEFAULT_REF_FRAMES 2
160 #define DEFAULT_BITRATE 2000
161 #define DEFAULT_MAX_BITRATE 0
162 #define DEFAULT_RATE_CONTROL MFX_RATECONTROL_VBR
163 #define DEFAULT_RC_LOOKAHEAD 10
164 #define DEFAULT_RC_LOOKAHEAD_DS MFX_LOOKAHEAD_DS_UNKNOWN
165 #define DEFAULT_AVBR_ACCURACY 0
166 #define DEFAULT_AVBR_CONVERGENCE 0
167 #define DEFAULT_IQC_QUALITY 0
168 #define DEFAULT_QVBR_QUALITY 0
169 #define DEFAULT_DISABLE_HRD_CONFORMANCE FALSE
170 #define DEFAULT_CC_INSERT GST_QSV_H264_ENC_SEI_INSERT
171
172 typedef struct _GstQsvH264EncClassData
173 {
174   GstCaps *sink_caps;
175   GstCaps *src_caps;
176   guint impl_index;
177   gint64 adapter_luid;
178   gchar *display_path;
179   gchar *description;
180 } GstQsvH264EncClassData;
181
182 typedef struct _GstQsvH264Enc
183 {
184   GstQsvEncoder parent;
185
186   mfxExtVideoSignalInfo signal_info;
187   mfxExtCodingOption option;
188   mfxExtCodingOption2 option2;
189   mfxExtCodingOption3 option3;
190
191   gboolean packetized;
192   GstH264NalParser *parser;
193
194   mfxU16 profile;
195
196   GMutex prop_lock;
197   /* protected by prop_lock */
198   gboolean bitrate_updated;
199   gboolean property_updated;
200
201   /* properties */
202   mfxU16 cabac;
203   guint min_qp_i;
204   guint min_qp_p;
205   guint min_qp_b;
206   guint max_qp_i;
207   guint max_qp_p;
208   guint max_qp_b;
209   guint qp_i;
210   guint qp_p;
211   guint qp_b;
212   guint gop_size;
213   guint idr_interval;
214   guint bframes;
215   guint ref_frames;
216   guint bitrate;
217   guint max_bitrate;
218   mfxU16 rate_control;
219   guint rc_lookahead;
220   mfxU16 rc_lookahead_ds;
221   guint avbr_accuracy;
222   guint avbr_convergence;
223   guint icq_quality;
224   guint qvbr_quality;
225   gboolean disable_hrd_conformance;
226   GstQsvH264EncSeiInsertMode cc_insert;
227 } GstQsvH264Enc;
228
229 typedef struct _GstQsvH264EncClass
230 {
231   GstQsvEncoderClass parent_class;
232 } GstQsvH264EncClass;
233
234 static GstElementClass *parent_class = nullptr;
235
236 #define GST_QSV_H264_ENC(object) ((GstQsvH264Enc *) (object))
237 #define GST_QSV_H264_ENC_GET_CLASS(object) \
238     (G_TYPE_INSTANCE_GET_CLASS ((object),G_TYPE_FROM_INSTANCE (object),GstQsvH264EncClass))
239
240 static void gst_qsv_h264_enc_finalize (GObject * object);
241 static void gst_qsv_h264_enc_set_property (GObject * object, guint prop_id,
242     const GValue * value, GParamSpec * pspec);
243 static void gst_qsv_h264_enc_get_property (GObject * object, guint prop_id,
244     GValue * value, GParamSpec * pspec);
245
246 static gboolean gst_qsv_h264_enc_start (GstVideoEncoder * encoder);
247 static gboolean gst_qsv_h264_enc_transform_meta (GstVideoEncoder * encoder,
248     GstVideoCodecFrame * frame, GstMeta * meta);
249 static GstCaps *gst_qsv_h264_enc_getcaps (GstVideoEncoder * encoder,
250     GstCaps * filter);
251
252 static gboolean gst_qsv_h264_enc_set_format (GstQsvEncoder * encoder,
253     GstVideoCodecState * state, mfxVideoParam * param,
254     GPtrArray * extra_params);
255 static gboolean gst_qsv_h264_enc_set_output_state (GstQsvEncoder * encoder,
256     GstVideoCodecState * state, mfxSession session);
257 static gboolean gst_qsv_h264_enc_attach_payload (GstQsvEncoder * encoder,
258     GstVideoCodecFrame * frame, GPtrArray * payload);
259 static GstBuffer *gst_qsv_h264_enc_create_output_buffer (GstQsvEncoder *
260     encoder, mfxBitstream * bitstream);
261 static GstQsvEncoderReconfigure
262 gst_qsv_h264_enc_check_reconfigure (GstQsvEncoder * encoder, mfxSession session,
263     mfxVideoParam * param, GPtrArray * extra_params);
264
265 static void
266 gst_qsv_h264_enc_class_init (GstQsvH264EncClass * klass, gpointer data)
267 {
268   GObjectClass *object_class = G_OBJECT_CLASS (klass);
269   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
270   GstVideoEncoderClass *encoder_class = GST_VIDEO_ENCODER_CLASS (klass);
271   GstQsvEncoderClass *qsvenc_class = GST_QSV_ENCODER_CLASS (klass);
272   GstQsvH264EncClassData *cdata = (GstQsvH264EncClassData *) data;
273
274   qsvenc_class->codec_id = MFX_CODEC_AVC;
275   qsvenc_class->impl_index = cdata->impl_index;
276   qsvenc_class->adapter_luid = cdata->adapter_luid;
277   qsvenc_class->display_path = cdata->display_path;
278
279   object_class->finalize = gst_qsv_h264_enc_finalize;
280   object_class->set_property = gst_qsv_h264_enc_set_property;
281   object_class->get_property = gst_qsv_h264_enc_get_property;
282
283   g_object_class_install_property (object_class, PROP_CABAC,
284       g_param_spec_enum ("cabac", "Cabac", "Enables CABAC entropy coding",
285           GST_TYPE_QSV_CODING_OPTION, DEFAULT_CABAC,
286           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
287   g_object_class_install_property (object_class, PROP_MIN_QP_I,
288       g_param_spec_uint ("min-qp-i", "Min QP I",
289           "Minimum allowed QP value for I-frame types (0: default)",
290           0, 51, DEFAULT_QP, (GParamFlags)
291           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
292   g_object_class_install_property (object_class, PROP_MIN_QP_P,
293       g_param_spec_uint ("min-qp-p", "Min QP P",
294           "Minimum allowed QP value for P-frame types (0: default)",
295           0, 51, DEFAULT_QP, (GParamFlags)
296           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
297   g_object_class_install_property (object_class, PROP_MIN_QP_B,
298       g_param_spec_uint ("min-qp-b", "Min QP B",
299           "Minimum allowed QP value for B-frame types (0: default)",
300           0, 51, DEFAULT_QP, (GParamFlags)
301           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
302   g_object_class_install_property (object_class, PROP_MAX_QP_I,
303       g_param_spec_uint ("max-qp-i", "Max QP I",
304           "Maximum allowed QP value for I-frame types (0: default)",
305           0, 51, DEFAULT_QP, (GParamFlags)
306           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
307   g_object_class_install_property (object_class, PROP_MAX_QP_P,
308       g_param_spec_uint ("max-qp-p", "Max QP P",
309           "Maximum allowed QP value for P-frame types (0: default)",
310           0, 51, DEFAULT_QP, (GParamFlags)
311           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
312   g_object_class_install_property (object_class, PROP_MAX_QP_B,
313       g_param_spec_uint ("max-qp-b", "Max QP B",
314           "Maximum allowed QP value for B-frame types (0: default)",
315           0, 51, DEFAULT_QP, (GParamFlags)
316           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
317   g_object_class_install_property (object_class, PROP_QP_I,
318       g_param_spec_uint ("qp-i", "QP I",
319           "Constant quantizer for I frames (0: default)",
320           0, 51, DEFAULT_QP, (GParamFlags)
321           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
322   g_object_class_install_property (object_class, PROP_QP_P,
323       g_param_spec_uint ("qp-p", "QP P",
324           "Constant quantizer for P frames (0: default)",
325           0, 51, DEFAULT_QP, (GParamFlags)
326           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
327   g_object_class_install_property (object_class, PROP_QP_B,
328       g_param_spec_uint ("qp-b", "QP B",
329           "Constant quantizer for B frames (0: default)",
330           0, 51, DEFAULT_QP, (GParamFlags)
331           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
332   g_object_class_install_property (object_class, PROP_GOP_SIZE,
333       g_param_spec_uint ("gop-size", "GOP Size",
334           "Number of pictures within a GOP (0: unspecified)",
335           0, G_MAXUSHORT, DEFAULT_GOP_SIZE, (GParamFlags)
336           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
337   g_object_class_install_property (object_class, PROP_IDR_INTERVAL,
338       g_param_spec_uint ("idr-interval", "IDR interval",
339           "IDR-frame interval in terms of I-frames. "
340           "0: every I-frame is an IDR frame, "
341           "N: \"N\" I-frames are inserted between IDR-frames",
342           0, G_MAXUSHORT, DEFAULT_IDR_INTERVAL, (GParamFlags)
343           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
344   g_object_class_install_property (object_class, PROP_B_FRAMES,
345       g_param_spec_uint ("b-frames", "B Frames",
346           "Number of B frames between I and P frames",
347           0, G_MAXUSHORT, DEFAULT_B_FRAMES, (GParamFlags)
348           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
349   g_object_class_install_property (object_class, PROP_REF_FRAMES,
350       g_param_spec_uint ("ref-frames", "Reference Frames",
351           "Number of reference frames (0: unspecified)",
352           0, 16, DEFAULT_REF_FRAMES, (GParamFlags)
353           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
354   g_object_class_install_property (object_class, PROP_BITRATE,
355       g_param_spec_uint ("bitrate", "Bitrate",
356           "Target bitrate in kbit/sec, Ignored when selected rate-control mode "
357           "is constant QP variants (i.e., \"cqp\", \"icq\", and \"la_icq\")",
358           0, G_MAXINT, DEFAULT_BITRATE, (GParamFlags)
359           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
360   g_object_class_install_property (object_class, PROP_MAX_BITRATE,
361       g_param_spec_uint ("max-bitrate", "Max Bitrate",
362           "Maximum bitrate in kbit/sec, Ignored when selected rate-control mode "
363           "is constant QP variants (i.e., \"cqp\", \"icq\", and \"la_icq\")",
364           0, G_MAXINT, DEFAULT_MAX_BITRATE, (GParamFlags)
365           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
366   g_object_class_install_property (object_class, PROP_RATE_CONTROL,
367       g_param_spec_enum ("rate-control", "Rate Control",
368           "Rate Control Method", GST_TYPE_QSV_H264_ENC_RATE_CONTROL,
369           DEFAULT_RATE_CONTROL,
370           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
371   g_object_class_install_property (object_class, PROP_RC_LOOKAHEAD,
372       g_param_spec_uint ("rc-lookahead", "Rate Control Look-ahead",
373           "Number of frames to look ahead for Rate Control, used for "
374           "\"la_vbr\", \"la_icq\", and \"la_hrd\" rate-control modes",
375           10, 100, DEFAULT_RC_LOOKAHEAD, (GParamFlags)
376           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
377   g_object_class_install_property (object_class, PROP_RC_LOOKAHEAD_DS,
378       g_param_spec_enum ("rc-lookahead-ds",
379           "Rate Control Look-ahead Downsampling",
380           "Downsampling method in look-ahead rate control",
381           GST_TYPE_QSV_H264_ENC_RC_LOOKAHEAD_DS, DEFAULT_RC_LOOKAHEAD_DS,
382           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
383   g_object_class_install_property (object_class, PROP_AVBR_ACCURACY,
384       g_param_spec_uint ("avbr-accuracy", "AVBR Accuracy",
385           "AVBR Accuracy in the unit of tenth of percent",
386           0, G_MAXUINT16, DEFAULT_AVBR_ACCURACY, (GParamFlags)
387           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
388   g_object_class_install_property (object_class, PROP_AVBR_CONVERGENCE,
389       g_param_spec_uint ("avbr-convergence", "AVBR Convergence",
390           "AVBR Convergence in the unit of 100 frames",
391           0, G_MAXUINT16, DEFAULT_AVBR_ACCURACY, (GParamFlags)
392           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
393   g_object_class_install_property (object_class, PROP_ICQ_QUALITY,
394       g_param_spec_uint ("icq-quality", "ICQ Quality",
395           "Intelligent Constant Quality for \"icq\" rate-control (0: default)",
396           0, 51, DEFAULT_IQC_QUALITY, (GParamFlags)
397           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
398   g_object_class_install_property (object_class, PROP_QVBR_QUALITY,
399       g_param_spec_uint ("qvbr-quality", "QVBR Quality",
400           "Quality level used for \"qvbr\" rate-control mode (0: default)",
401           0, 51, DEFAULT_QVBR_QUALITY, (GParamFlags)
402           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
403   g_object_class_install_property (object_class, PROP_DISABLE_HRD_CONFORMANCE,
404       g_param_spec_boolean ("disable-hrd-conformance",
405           "Disable HRD Conformance", "Allow NAL HRD non-conformant stream",
406           DEFAULT_DISABLE_HRD_CONFORMANCE,
407           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
408   g_object_class_install_property (object_class, PROP_CC_INSERT,
409       g_param_spec_enum ("cc-insert", "Closed Caption Insert",
410           "Closed Caption Insert mode. "
411           "Only CEA-708 RAW format is supported for now",
412           GST_TYPE_QSV_H264_ENC_SEI_INSERT_MODE, DEFAULT_CC_INSERT,
413           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
414
415   parent_class = (GstElementClass *) g_type_class_peek_parent (klass);
416
417 #ifdef G_OS_WIN32
418   std::string long_name = "Intel Quick Sync Video " +
419       std::string (cdata->description) + " H.264 Encoder";
420
421   gst_element_class_set_metadata (element_class, long_name.c_str (),
422       "Codec/Encoder/Video/Hardware",
423       "Intel Quick Sync Video H.264 Encoder",
424       "Seungha Yang <seungha@centricular.com>");
425 #else
426   gst_element_class_set_static_metadata (element_class,
427       "Intel Quick Sync Video H.264 Encoder",
428       "Codec/Encoder/Video/Hardware",
429       "Intel Quick Sync Video H.264 Encoder",
430       "Seungha Yang <seungha@centricular.com>");
431 #endif
432
433   gst_element_class_add_pad_template (element_class,
434       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
435           cdata->sink_caps));
436   gst_element_class_add_pad_template (element_class,
437       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
438           cdata->src_caps));
439
440   encoder_class->start = GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_start);
441   encoder_class->transform_meta =
442       GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_transform_meta);
443   encoder_class->getcaps = GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_getcaps);
444
445   qsvenc_class->set_format = GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_set_format);
446   qsvenc_class->set_output_state =
447       GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_set_output_state);
448   qsvenc_class->attach_payload =
449       GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_attach_payload);
450   qsvenc_class->create_output_buffer =
451       GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_create_output_buffer);
452   qsvenc_class->check_reconfigure =
453       GST_DEBUG_FUNCPTR (gst_qsv_h264_enc_check_reconfigure);
454
455   gst_caps_unref (cdata->sink_caps);
456   gst_caps_unref (cdata->src_caps);
457   g_free (cdata->description);
458   g_free (cdata);
459 }
460
461 static void
462 gst_qsv_h264_enc_init (GstQsvH264Enc * self)
463 {
464   self->cabac = DEFAULT_CABAC;
465   self->min_qp_i = DEFAULT_QP;
466   self->min_qp_p = DEFAULT_QP;
467   self->min_qp_b = DEFAULT_QP;
468   self->max_qp_i = DEFAULT_QP;
469   self->max_qp_p = DEFAULT_QP;
470   self->max_qp_p = DEFAULT_QP;
471   self->qp_i = DEFAULT_QP;
472   self->qp_p = DEFAULT_QP;
473   self->qp_b = DEFAULT_QP;
474   self->gop_size = DEFAULT_GOP_SIZE;
475   self->idr_interval = DEFAULT_IDR_INTERVAL;
476   self->bframes = DEFAULT_B_FRAMES;
477   self->ref_frames = DEFAULT_REF_FRAMES;
478   self->bitrate = DEFAULT_BITRATE;
479   self->max_bitrate = DEFAULT_MAX_BITRATE;
480   self->rate_control = DEFAULT_RATE_CONTROL;
481   self->rc_lookahead = DEFAULT_RC_LOOKAHEAD;
482   self->rc_lookahead_ds = DEFAULT_RC_LOOKAHEAD_DS;
483   self->avbr_accuracy = DEFAULT_AVBR_ACCURACY;
484   self->avbr_convergence = DEFAULT_AVBR_CONVERGENCE;
485   self->icq_quality = DEFAULT_IQC_QUALITY;
486   self->qvbr_quality = DEFAULT_QVBR_QUALITY;
487   self->disable_hrd_conformance = DEFAULT_DISABLE_HRD_CONFORMANCE;
488   self->cc_insert = DEFAULT_CC_INSERT;
489
490   g_mutex_init (&self->prop_lock);
491
492   self->parser = gst_h264_nal_parser_new ();
493 }
494
495 static void
496 gst_qsv_h264_enc_finalize (GObject * object)
497 {
498   GstQsvH264Enc *self = GST_QSV_H264_ENC (object);
499
500   g_mutex_clear (&self->prop_lock);
501   gst_h264_nal_parser_free (self->parser);
502
503   G_OBJECT_CLASS (parent_class)->finalize (object);
504 }
505
506 static void
507 gst_qsv_h264_enc_check_update_uint (GstQsvH264Enc * self, guint * old_val,
508     guint new_val, gboolean is_bitrate_param)
509 {
510   if (*old_val == new_val)
511     return;
512
513   g_mutex_lock (&self->prop_lock);
514   *old_val = new_val;
515   if (is_bitrate_param)
516     self->bitrate_updated = TRUE;
517   else
518     self->property_updated = TRUE;
519   g_mutex_unlock (&self->prop_lock);
520 }
521
522 static void
523 gst_qsv_h264_enc_check_update_enum (GstQsvH264Enc * self, mfxU16 * old_val,
524     gint new_val)
525 {
526   if (*old_val == (mfxU16) new_val)
527     return;
528
529   g_mutex_lock (&self->prop_lock);
530   *old_val = (mfxU16) new_val;
531   self->property_updated = TRUE;
532   g_mutex_unlock (&self->prop_lock);
533 }
534
535 static void
536 gst_qsv_h264_enc_check_update_boolean (GstQsvH264Enc * self, gboolean * old_val,
537     gboolean new_val)
538 {
539   if (*old_val == new_val)
540     return;
541
542   g_mutex_lock (&self->prop_lock);
543   *old_val = new_val;
544   self->property_updated = TRUE;
545   g_mutex_unlock (&self->prop_lock);
546 }
547
548 static void
549 gst_qsv_h264_enc_set_property (GObject * object, guint prop_id,
550     const GValue * value, GParamSpec * pspec)
551 {
552   GstQsvH264Enc *self = GST_QSV_H264_ENC (object);
553
554   switch (prop_id) {
555     case PROP_CABAC:
556       gst_qsv_h264_enc_check_update_enum (self, &self->cabac,
557           g_value_get_enum (value));
558       break;
559       /* MIN/MAX QP change requires new sequence */
560     case PROP_MIN_QP_I:
561       gst_qsv_h264_enc_check_update_uint (self, &self->min_qp_i,
562           g_value_get_uint (value), FALSE);
563       break;
564     case PROP_MIN_QP_P:
565       gst_qsv_h264_enc_check_update_uint (self, &self->min_qp_p,
566           g_value_get_uint (value), FALSE);
567       break;
568     case PROP_MIN_QP_B:
569       gst_qsv_h264_enc_check_update_uint (self, &self->min_qp_b,
570           g_value_get_uint (value), FALSE);
571       break;
572     case PROP_MAX_QP_I:
573       gst_qsv_h264_enc_check_update_uint (self, &self->max_qp_i,
574           g_value_get_uint (value), FALSE);
575       break;
576     case PROP_MAX_QP_P:
577       gst_qsv_h264_enc_check_update_uint (self, &self->max_qp_p,
578           g_value_get_uint (value), FALSE);
579       break;
580     case PROP_MAX_QP_B:
581       gst_qsv_h264_enc_check_update_uint (self, &self->max_qp_b,
582           g_value_get_uint (value), FALSE);
583       break;
584     case PROP_QP_I:
585       gst_qsv_h264_enc_check_update_uint (self, &self->qp_i,
586           g_value_get_uint (value), TRUE);
587       break;
588     case PROP_QP_P:
589       gst_qsv_h264_enc_check_update_uint (self, &self->qp_p,
590           g_value_get_uint (value), TRUE);
591       break;
592     case PROP_QP_B:
593       gst_qsv_h264_enc_check_update_uint (self, &self->qp_b,
594           g_value_get_uint (value), TRUE);
595       break;
596     case PROP_GOP_SIZE:
597       gst_qsv_h264_enc_check_update_uint (self, &self->gop_size,
598           g_value_get_uint (value), FALSE);
599       break;
600     case PROP_IDR_INTERVAL:
601       gst_qsv_h264_enc_check_update_uint (self, &self->idr_interval,
602           g_value_get_uint (value), FALSE);
603       break;
604     case PROP_B_FRAMES:
605       gst_qsv_h264_enc_check_update_uint (self, &self->bframes,
606           g_value_get_uint (value), FALSE);
607       break;
608     case PROP_REF_FRAMES:
609       gst_qsv_h264_enc_check_update_uint (self, &self->ref_frames,
610           g_value_get_uint (value), FALSE);
611       break;
612     case PROP_BITRATE:
613       gst_qsv_h264_enc_check_update_uint (self, &self->bitrate,
614           g_value_get_uint (value), TRUE);
615       break;
616     case PROP_MAX_BITRATE:
617       gst_qsv_h264_enc_check_update_uint (self, &self->max_bitrate,
618           g_value_get_uint (value), TRUE);
619       break;
620     case PROP_RATE_CONTROL:
621       gst_qsv_h264_enc_check_update_enum (self, &self->rate_control,
622           g_value_get_enum (value));
623       break;
624     case PROP_RC_LOOKAHEAD:
625       gst_qsv_h264_enc_check_update_uint (self, &self->rc_lookahead,
626           g_value_get_uint (value), FALSE);
627       break;
628     case PROP_RC_LOOKAHEAD_DS:
629       gst_qsv_h264_enc_check_update_enum (self, &self->rc_lookahead_ds,
630           g_value_get_enum (value));
631       break;
632     case PROP_AVBR_ACCURACY:
633       gst_qsv_h264_enc_check_update_uint (self, &self->avbr_accuracy,
634           g_value_get_uint (value), FALSE);
635       break;
636     case PROP_AVBR_CONVERGENCE:
637       gst_qsv_h264_enc_check_update_uint (self, &self->avbr_convergence,
638           g_value_get_uint (value), FALSE);
639       break;
640     case PROP_ICQ_QUALITY:
641       gst_qsv_h264_enc_check_update_uint (self, &self->icq_quality,
642           g_value_get_uint (value), FALSE);
643       break;
644     case PROP_QVBR_QUALITY:
645       gst_qsv_h264_enc_check_update_uint (self, &self->qvbr_quality,
646           g_value_get_uint (value), FALSE);
647       break;
648     case PROP_DISABLE_HRD_CONFORMANCE:
649       gst_qsv_h264_enc_check_update_boolean (self,
650           &self->disable_hrd_conformance, g_value_get_boolean (value));
651       break;
652     case PROP_CC_INSERT:
653       /* This property is unrelated to encoder-reset */
654       self->cc_insert = (GstQsvH264EncSeiInsertMode) g_value_get_enum (value);
655       break;
656     default:
657       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
658       break;
659   }
660 }
661
662 static void
663 gst_qsv_h264_enc_get_property (GObject * object, guint prop_id, GValue * value,
664     GParamSpec * pspec)
665 {
666   GstQsvH264Enc *self = GST_QSV_H264_ENC (object);
667
668   switch (prop_id) {
669     case PROP_CABAC:
670       g_value_set_enum (value, self->cabac);
671       break;
672     case PROP_MIN_QP_I:
673       g_value_set_uint (value, self->min_qp_i);
674       break;
675     case PROP_MIN_QP_P:
676       g_value_set_uint (value, self->min_qp_p);
677       break;
678     case PROP_MIN_QP_B:
679       g_value_set_uint (value, self->min_qp_b);
680       break;
681     case PROP_MAX_QP_I:
682       g_value_set_uint (value, self->max_qp_i);
683       break;
684     case PROP_MAX_QP_P:
685       g_value_set_uint (value, self->max_qp_p);
686       break;
687     case PROP_MAX_QP_B:
688       g_value_set_uint (value, self->max_qp_b);
689       break;
690     case PROP_QP_I:
691       g_value_set_uint (value, self->qp_i);
692       break;
693     case PROP_QP_P:
694       g_value_set_uint (value, self->qp_p);
695       break;
696     case PROP_QP_B:
697       g_value_set_uint (value, self->qp_b);
698       break;
699     case PROP_GOP_SIZE:
700       g_value_set_uint (value, self->gop_size);
701       break;
702     case PROP_IDR_INTERVAL:
703       g_value_set_uint (value, self->idr_interval);
704       break;
705     case PROP_B_FRAMES:
706       g_value_set_uint (value, self->bframes);
707       break;
708     case PROP_REF_FRAMES:
709       g_value_set_uint (value, self->ref_frames);
710       break;
711     case PROP_BITRATE:
712       g_value_set_uint (value, self->bitrate);
713       break;
714     case PROP_MAX_BITRATE:
715       g_value_set_uint (value, self->max_bitrate);
716       break;
717     case PROP_RATE_CONTROL:
718       g_value_set_enum (value, self->rate_control);
719       break;
720     case PROP_RC_LOOKAHEAD:
721       g_value_set_uint (value, self->rc_lookahead);
722       break;
723     case PROP_RC_LOOKAHEAD_DS:
724       g_value_set_enum (value, self->rc_lookahead_ds);
725       break;
726     case PROP_AVBR_ACCURACY:
727       g_value_set_uint (value, self->avbr_accuracy);
728       break;
729     case PROP_AVBR_CONVERGENCE:
730       g_value_set_uint (value, self->avbr_convergence);
731       break;
732     case PROP_ICQ_QUALITY:
733       g_value_set_uint (value, self->icq_quality);
734       break;
735     case PROP_QVBR_QUALITY:
736       g_value_set_uint (value, self->qvbr_quality);
737       break;
738     case PROP_CC_INSERT:
739       g_value_set_enum (value, self->cc_insert);
740       break;
741     case PROP_DISABLE_HRD_CONFORMANCE:
742       g_value_set_boolean (value, self->disable_hrd_conformance);
743       break;
744     default:
745       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
746       break;
747   }
748 }
749
750 static gboolean
751 gst_qsv_h264_enc_start (GstVideoEncoder * encoder)
752 {
753   /* To avoid negative DTS when B frame is enabled */
754   gst_video_encoder_set_min_pts (encoder, GST_SECOND * 60 * 60 * 1000);
755
756   return TRUE;
757 }
758
759 static gboolean
760 gst_qsv_h264_enc_transform_meta (GstVideoEncoder * encoder,
761     GstVideoCodecFrame * frame, GstMeta * meta)
762 {
763   GstQsvH264Enc *self = GST_QSV_H264_ENC (encoder);
764   GstVideoCaptionMeta *cc_meta;
765
766   /* We need to handle only case CC meta should be dropped */
767   if (self->cc_insert != GST_QSV_H264_ENC_SEI_INSERT_AND_DROP)
768     goto out;
769
770   if (meta->info->api != GST_VIDEO_CAPTION_META_API_TYPE)
771     goto out;
772
773   cc_meta = (GstVideoCaptionMeta *) meta;
774   if (cc_meta->caption_type != GST_VIDEO_CAPTION_TYPE_CEA708_RAW)
775     goto out;
776
777   /* Don't copy this meta into output buffer */
778   return FALSE;
779
780 out:
781   return GST_VIDEO_ENCODER_CLASS (parent_class)->transform_meta (encoder,
782       frame, meta);
783 }
784
785 static GstCaps *
786 gst_qsv_h264_enc_getcaps (GstVideoEncoder * encoder, GstCaps * filter)
787 {
788   GstQsvH264Enc *self = GST_QSV_H264_ENC (encoder);
789   GstCaps *allowed_caps;
790   GstCaps *template_caps;
791   GstCaps *supported_caps;
792   std::set < std::string > downstream_profiles;
793
794   allowed_caps = gst_pad_get_allowed_caps (encoder->srcpad);
795
796   /* Shouldn't be any or empty though, just return template caps in this case */
797   if (!allowed_caps || gst_caps_is_empty (allowed_caps) ||
798       gst_caps_is_any (allowed_caps)) {
799     gst_clear_caps (&allowed_caps);
800
801     return gst_video_encoder_proxy_getcaps (encoder, nullptr, filter);
802   }
803
804   /* Check if downstream specified profile explicitly, then filter out
805    * incompatible interlaced field */
806   for (guint i = 0; i < gst_caps_get_size (allowed_caps); i++) {
807     const GValue *profile_value;
808     const gchar *profile;
809     GstStructure *s;
810
811     s = gst_caps_get_structure (allowed_caps, i);
812     profile_value = gst_structure_get_value (s, "profile");
813     if (!profile_value)
814       continue;
815
816     if (GST_VALUE_HOLDS_LIST (profile_value)) {
817       for (guint j = 0; j < gst_value_list_get_size (profile_value); j++) {
818         const GValue *p = gst_value_list_get_value (profile_value, j);
819
820         if (!G_VALUE_HOLDS_STRING (p))
821           continue;
822
823         profile = g_value_get_string (p);
824         if (profile)
825           downstream_profiles.insert (profile);
826       }
827
828     } else if (G_VALUE_HOLDS_STRING (profile_value)) {
829       profile = g_value_get_string (profile_value);
830       if (profile)
831         downstream_profiles.insert (profile);
832     }
833   }
834
835   GST_DEBUG_OBJECT (self, "Downstream specified %" G_GSIZE_FORMAT " profiles",
836       downstream_profiles.size ());
837
838   /* Caps returned by gst_pad_get_allowed_caps() should hold profile field
839    * already */
840   if (downstream_profiles.size () == 0) {
841     GST_WARNING_OBJECT (self,
842         "Allowed caps holds no profile field %" GST_PTR_FORMAT, allowed_caps);
843
844     gst_clear_caps (&allowed_caps);
845
846     return gst_video_encoder_proxy_getcaps (encoder, nullptr, filter);
847   }
848
849   gst_clear_caps (&allowed_caps);
850
851   /* Profile allows interlaced? */
852   /* *INDENT-OFF* */
853   gboolean can_support_interlaced = FALSE;
854   for (const auto &iter: downstream_profiles) {
855     if (iter == "high" || iter == "main") {
856       can_support_interlaced = TRUE;
857       break;
858     }
859   }
860   /* *INDENT-ON* */
861
862   GST_DEBUG_OBJECT (self, "Downstream %s support interlaced format",
863       can_support_interlaced ? "can" : "cannot");
864
865   if (can_support_interlaced) {
866     /* No special handling is needed */
867     return gst_video_encoder_proxy_getcaps (encoder, nullptr, filter);
868   }
869
870   template_caps = gst_pad_get_pad_template_caps (encoder->sinkpad);
871   template_caps = gst_caps_make_writable (template_caps);
872
873   gst_caps_set_simple (template_caps, "interlace-mode", G_TYPE_STRING,
874       "progressive", nullptr);
875
876   supported_caps = gst_video_encoder_proxy_getcaps (encoder,
877       template_caps, filter);
878   gst_caps_unref (template_caps);
879
880   GST_DEBUG_OBJECT (self, "Returning %" GST_PTR_FORMAT, supported_caps);
881
882   return supported_caps;
883 }
884
885 typedef struct
886 {
887   mfxU16 profile;
888   const gchar *profile_str;
889 } H264Profile;
890
891 static const H264Profile profile_map[] = {
892   {MFX_PROFILE_AVC_HIGH, "high"},
893   {MFX_PROFILE_AVC_MAIN, "main"},
894   {MFX_PROFILE_AVC_CONSTRAINED_BASELINE, "constrained-baseline"},
895   {MFX_PROFILE_AVC_PROGRESSIVE_HIGH, "progressive-high"},
896   {MFX_PROFILE_AVC_CONSTRAINED_HIGH, "constrained-high"},
897   {MFX_PROFILE_AVC_BASELINE, "baseline"}
898 };
899
900 static const gchar *
901 gst_qsv_h264_profile_to_string (mfxU16 profile)
902 {
903   for (guint i = 0; i < G_N_ELEMENTS (profile_map); i++) {
904     if (profile_map[i].profile == profile)
905       return profile_map[i].profile_str;
906   }
907
908   return nullptr;
909 }
910
911 static mfxU16
912 gst_qsv_h264_profile_string_to_value (const gchar * profile_str)
913 {
914   for (guint i = 0; i < G_N_ELEMENTS (profile_map); i++) {
915     if (g_strcmp0 (profile_map[i].profile_str, profile_str) == 0)
916       return profile_map[i].profile;
917   }
918
919   return MFX_PROFILE_UNKNOWN;
920 }
921
922 static void
923 gst_qsv_h264_enc_init_extra_params (GstQsvH264Enc * self)
924 {
925   memset (&self->signal_info, 0, sizeof (mfxExtVideoSignalInfo));
926   memset (&self->option, 0, sizeof (mfxExtCodingOption));
927   memset (&self->option2, 0, sizeof (mfxExtCodingOption2));
928   memset (&self->option3, 0, sizeof (mfxExtCodingOption3));
929
930   self->signal_info.Header.BufferId = MFX_EXTBUFF_VIDEO_SIGNAL_INFO;
931   self->signal_info.Header.BufferSz = sizeof (mfxExtVideoSignalInfo);
932
933   self->option.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
934   self->option.Header.BufferSz = sizeof (mfxExtCodingOption);
935
936   self->option2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
937   self->option2.Header.BufferSz = sizeof (mfxExtCodingOption2);
938
939   self->option3.Header.BufferId = MFX_EXTBUFF_CODING_OPTION3;
940   self->option3.Header.BufferSz = sizeof (mfxExtCodingOption3);
941 }
942
943 static void
944 gst_qsv_h264_enc_set_bitrate (GstQsvH264Enc * self, mfxVideoParam * param)
945 {
946   guint max_val;
947   guint multiplier;
948
949   switch (param->mfx.RateControlMethod) {
950     case MFX_RATECONTROL_CBR:
951       multiplier = (self->bitrate + 0x10000) / 0x10000;
952       param->mfx.TargetKbps = param->mfx.MaxKbps = self->bitrate / multiplier;
953       param->mfx.BRCParamMultiplier = (mfxU16) multiplier;
954       break;
955     case MFX_RATECONTROL_VBR:
956     case MFX_RATECONTROL_VCM:
957     case MFX_RATECONTROL_QVBR:
958       max_val = MAX (self->bitrate, self->max_bitrate);
959       multiplier = (max_val + 0x10000) / 0x10000;
960       param->mfx.TargetKbps = self->bitrate / multiplier;
961       param->mfx.MaxKbps = self->max_bitrate / multiplier;
962       param->mfx.BRCParamMultiplier = (mfxU16) multiplier;
963       break;
964     case MFX_RATECONTROL_CQP:
965       param->mfx.QPI = self->qp_i;
966       param->mfx.QPP = self->qp_p;
967       param->mfx.QPB = self->qp_b;
968       break;
969     case MFX_RATECONTROL_AVBR:
970       multiplier = (self->bitrate + 0x10000) / 0x10000;
971       param->mfx.TargetKbps = self->bitrate / multiplier;
972       param->mfx.Accuracy = self->avbr_accuracy;
973       param->mfx.Convergence = self->avbr_convergence;
974       param->mfx.BRCParamMultiplier = (mfxU16) multiplier;
975       break;
976     case MFX_RATECONTROL_LA:
977       multiplier = (self->bitrate + 0x10000) / 0x10000;
978       param->mfx.TargetKbps = self->bitrate / multiplier;
979       param->mfx.BRCParamMultiplier = (mfxU16) multiplier;
980       break;
981     case MFX_RATECONTROL_LA_HRD:
982       max_val = MAX (self->bitrate, self->max_bitrate);
983       multiplier = (max_val + 0x10000) / 0x10000;
984       param->mfx.TargetKbps = self->bitrate / multiplier;
985       param->mfx.MaxKbps = self->max_bitrate / multiplier;
986       param->mfx.BRCParamMultiplier = (mfxU16) multiplier;
987       break;
988     case MFX_RATECONTROL_ICQ:
989     case MFX_RATECONTROL_LA_ICQ:
990       param->mfx.ICQQuality = self->icq_quality;
991       break;
992     default:
993       GST_WARNING_OBJECT (self,
994           "Unhandled rate-control method %d", self->rate_control);
995       break;
996   }
997 }
998
999 static gboolean
1000 gst_qsv_h264_enc_set_format (GstQsvEncoder * encoder,
1001     GstVideoCodecState * state, mfxVideoParam * param, GPtrArray * extra_params)
1002 {
1003   GstQsvH264Enc *self = GST_QSV_H264_ENC (encoder);
1004   GstCaps *allowed_caps, *fixated_caps;
1005   std::set < std::string > downstream_profiles;
1006   std::set < std::string > tmp;
1007   guint bframes = self->bframes;
1008   mfxU16 cabac = self->cabac;
1009   std::string profile_str;
1010   mfxU16 mfx_profile = MFX_PROFILE_UNKNOWN;
1011   GstVideoInfo *info = &state->info;
1012   mfxExtVideoSignalInfo *signal_info = nullptr;
1013   mfxExtCodingOption *option;
1014   mfxExtCodingOption2 *option2;
1015   mfxExtCodingOption3 *option3;
1016   GstStructure *s;
1017   const gchar *stream_format;
1018   mfxFrameInfo *frame_info;
1019
1020   frame_info = &param->mfx.FrameInfo;
1021
1022   /* QSV specific alignment requirement:
1023    * width/height should be multiple of 16, and for interlaced encoding,
1024    * height should be multiple of 32 */
1025   frame_info->Width = GST_ROUND_UP_16 (info->width);
1026   if (GST_VIDEO_INFO_IS_INTERLACED (info)) {
1027     frame_info->Height = GST_ROUND_UP_32 (info->height);
1028     switch (GST_VIDEO_INFO_FIELD_ORDER (info)) {
1029       case GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST:
1030         frame_info->PicStruct = MFX_PICSTRUCT_FIELD_TFF;
1031         break;
1032       case GST_VIDEO_FIELD_ORDER_BOTTOM_FIELD_FIRST:
1033         frame_info->PicStruct = MFX_PICSTRUCT_FIELD_BFF;
1034         break;
1035       default:
1036         frame_info->PicStruct = MFX_PICSTRUCT_UNKNOWN;
1037         break;
1038     }
1039   } else {
1040     frame_info->Height = GST_ROUND_UP_16 (info->height);
1041     frame_info->PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
1042   }
1043
1044   /* QSV wouldn't be happy with this size, increase */
1045   if (frame_info->Width == 16)
1046     frame_info->Width = 32;
1047
1048   if (frame_info->Height == 16)
1049     frame_info->Height = 32;
1050
1051   frame_info->CropW = info->width;
1052   frame_info->CropH = info->height;
1053   if (GST_VIDEO_INFO_FPS_N (info) > 0 && GST_VIDEO_INFO_FPS_D (info) > 0) {
1054     frame_info->FrameRateExtN = GST_VIDEO_INFO_FPS_N (info);
1055     frame_info->FrameRateExtD = GST_VIDEO_INFO_FPS_D (info);
1056   } else {
1057     /* HACK: Same as x264enc */
1058     frame_info->FrameRateExtN = 25;
1059     frame_info->FrameRateExtD = 1;
1060   }
1061
1062   frame_info->AspectRatioW = GST_VIDEO_INFO_PAR_N (info);
1063   frame_info->AspectRatioH = GST_VIDEO_INFO_PAR_D (info);
1064
1065   /* TODO: update for non 4:2:0 formats. Currently NV12 only */
1066   frame_info->ChromaFormat = MFX_CHROMAFORMAT_YUV420;
1067   switch (GST_VIDEO_INFO_FORMAT (info)) {
1068     case GST_VIDEO_FORMAT_NV12:
1069       frame_info->FourCC = MFX_FOURCC_NV12;
1070       frame_info->BitDepthLuma = 8;
1071       frame_info->BitDepthChroma = 8;
1072       break;
1073     default:
1074       GST_ERROR_OBJECT (self, "Unexpected format %s",
1075           gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (info)));
1076       return FALSE;
1077   }
1078
1079   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
1080   if (!allowed_caps) {
1081     GST_WARNING_OBJECT (self, "Failed to get allowed caps");
1082     return FALSE;
1083   }
1084
1085   gst_qsv_h264_enc_init_extra_params (self);
1086   option = &self->option;
1087   option2 = &self->option2;
1088   option3 = &self->option3;
1089
1090   self->packetized = FALSE;
1091
1092   fixated_caps = gst_caps_fixate (gst_caps_copy (allowed_caps));
1093   s = gst_caps_get_structure (fixated_caps, 0);
1094   stream_format = gst_structure_get_string (s, "stream-format");
1095   if (g_strcmp0 (stream_format, "avc") == 0)
1096     self->packetized = TRUE;
1097   gst_caps_unref (fixated_caps);
1098
1099   for (guint i = 0; i < gst_caps_get_size (allowed_caps); i++) {
1100     const GValue *profile_value;
1101     const gchar *profile;
1102
1103     s = gst_caps_get_structure (allowed_caps, i);
1104     profile_value = gst_structure_get_value (s, "profile");
1105     if (!profile_value)
1106       continue;
1107
1108     if (GST_VALUE_HOLDS_LIST (profile_value)) {
1109       for (guint j = 0; j < gst_value_list_get_size (profile_value); j++) {
1110         const GValue *p = gst_value_list_get_value (profile_value, j);
1111
1112         if (!G_VALUE_HOLDS_STRING (p))
1113           continue;
1114
1115         profile = g_value_get_string (p);
1116         if (profile)
1117           downstream_profiles.insert (profile);
1118       }
1119
1120     } else if (G_VALUE_HOLDS_STRING (profile_value)) {
1121       profile = g_value_get_string (profile_value);
1122       if (profile)
1123         downstream_profiles.insert (profile);
1124     }
1125   }
1126
1127   GST_DEBUG_OBJECT (self, "Downstream supports %" G_GSIZE_FORMAT " profiles",
1128       downstream_profiles.size ());
1129
1130   /* Prune incompatible profiles */
1131   if ((param->mfx.FrameInfo.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) == 0) {
1132     /* Interlaced, only main and high profiles are allowed */
1133     downstream_profiles.erase (gst_qsv_h264_profile_to_string
1134         (MFX_PROFILE_AVC_CONSTRAINED_BASELINE));
1135     downstream_profiles.erase (gst_qsv_h264_profile_to_string
1136         (MFX_PROFILE_AVC_PROGRESSIVE_HIGH));
1137     downstream_profiles.erase (gst_qsv_h264_profile_to_string
1138         (MFX_PROFILE_AVC_CONSTRAINED_HIGH));
1139     downstream_profiles.erase (gst_qsv_h264_profile_to_string
1140         (MFX_PROFILE_AVC_BASELINE));
1141   }
1142
1143   if (downstream_profiles.empty ()) {
1144     GST_WARNING_OBJECT (self, "No compatible profile was detected");
1145     gst_clear_caps (&allowed_caps);
1146     return FALSE;
1147   }
1148
1149   if (bframes > 0) {
1150     /* baseline and constrained-high doesn't support bframe */
1151     tmp = downstream_profiles;
1152     tmp.erase (gst_qsv_h264_profile_to_string
1153         (MFX_PROFILE_AVC_CONSTRAINED_BASELINE));
1154     tmp.erase (gst_qsv_h264_profile_to_string
1155         (MFX_PROFILE_AVC_CONSTRAINED_HIGH));
1156     tmp.erase (gst_qsv_h264_profile_to_string (MFX_PROFILE_AVC_BASELINE));
1157
1158     if (tmp.empty ()) {
1159       GST_WARNING_OBJECT (self, "None of downstream profile supports bframes");
1160       bframes = 0;
1161       tmp = downstream_profiles;
1162     }
1163
1164     downstream_profiles = tmp;
1165   }
1166
1167   if (cabac == MFX_CODINGOPTION_ON) {
1168     /* baseline doesn't support cabac */
1169     tmp = downstream_profiles;
1170     tmp.erase (gst_qsv_h264_profile_to_string
1171         (MFX_PROFILE_AVC_CONSTRAINED_BASELINE));
1172     tmp.erase (gst_qsv_h264_profile_to_string (MFX_PROFILE_AVC_BASELINE));
1173
1174     if (tmp.empty ()) {
1175       GST_WARNING_OBJECT (self, "None of downstream profile supports cabac");
1176       cabac = MFX_CODINGOPTION_OFF;
1177       tmp = downstream_profiles;
1178     }
1179     downstream_profiles = tmp;
1180   }
1181
1182   /* we have our preference order */
1183   /* *INDENT-OFF* */
1184   for (guint i = 0; i < G_N_ELEMENTS (profile_map); i++) {
1185     auto it = downstream_profiles.find (profile_map[i].profile_str);
1186     if (it != downstream_profiles.end ()) {
1187       profile_str = *it;
1188       break;
1189     }
1190   }
1191   /* *INDENT-ON* */
1192
1193   if (profile_str.empty ()) {
1194     GST_WARNING_OBJECT (self, "Failed to determine profile");
1195     return FALSE;
1196   }
1197
1198   GST_DEBUG_OBJECT (self, "Selected profile %s", profile_str.c_str ());
1199   mfx_profile = gst_qsv_h264_profile_string_to_value (profile_str.c_str ());
1200
1201   gst_clear_caps (&allowed_caps);
1202
1203   if (cabac == MFX_CODINGOPTION_UNKNOWN) {
1204     switch (mfx_profile) {
1205       case MFX_PROFILE_AVC_CONSTRAINED_BASELINE:
1206       case MFX_PROFILE_AVC_BASELINE:
1207         cabac = MFX_CODINGOPTION_OFF;
1208         break;
1209       default:
1210         cabac = MFX_CODINGOPTION_ON;
1211         break;
1212     }
1213   }
1214
1215   g_mutex_lock (&self->prop_lock);
1216   param->mfx.CodecId = MFX_CODEC_AVC;
1217   param->mfx.CodecProfile = mfx_profile;
1218   param->mfx.GopRefDist = bframes + 1;
1219   param->mfx.GopPicSize = self->gop_size;
1220   param->mfx.IdrInterval = self->idr_interval;
1221   param->mfx.RateControlMethod = self->rate_control;
1222   param->mfx.NumRefFrame = self->ref_frames;
1223
1224   gst_qsv_h264_enc_set_bitrate (self, param);
1225
1226   /* Write signal info only when upstream caps contains valid colorimetry,
1227    * because derived default colorimetry in gst_video_info_from_caps() tends to
1228    * very wrong in various cases, and it's even worse than "unknown" */
1229   if (state->caps) {
1230     GstStructure *s = gst_caps_get_structure (state->caps, 0);
1231     GstVideoColorimetry cinfo;
1232     const gchar *str;
1233
1234     str = gst_structure_get_string (s, "colorimetry");
1235     if (str && gst_video_colorimetry_from_string (&cinfo, str)) {
1236       signal_info = &self->signal_info;
1237
1238       /* 0: Component, 1: PAL, 2: NTSC, 3: SECAM, 4: MAC, 5: Unspecified */
1239       signal_info->VideoFormat = 5;
1240       if (cinfo.range == GST_VIDEO_COLOR_RANGE_0_255)
1241         signal_info->VideoFullRange = 1;
1242       else
1243         signal_info->VideoFullRange = 0;
1244       signal_info->ColourDescriptionPresent = 1;
1245       signal_info->ColourPrimaries =
1246           gst_video_color_primaries_to_iso (cinfo.primaries);
1247       signal_info->TransferCharacteristics =
1248           gst_video_transfer_function_to_iso (cinfo.transfer);
1249       signal_info->MatrixCoefficients =
1250           gst_video_color_matrix_to_iso (cinfo.matrix);
1251     }
1252   }
1253
1254   if (cabac == MFX_CODINGOPTION_OFF)
1255     option->CAVLC = MFX_CODINGOPTION_ON;
1256   else
1257     option->CAVLC = MFX_CODINGOPTION_OFF;
1258
1259   /* TODO: property ? */
1260   option->AUDelimiter = MFX_CODINGOPTION_ON;
1261
1262   if (self->disable_hrd_conformance) {
1263     option->NalHrdConformance = MFX_CODINGOPTION_OFF;
1264     option->VuiVclHrdParameters = MFX_CODINGOPTION_OFF;
1265   }
1266
1267   /* Enables PicTiming SEI by default */
1268   option->PicTimingSEI = MFX_CODINGOPTION_ON;
1269
1270   /* VUI is useful in various cases, so we don't want to disable it */
1271   option2->DisableVUI = MFX_CODINGOPTION_OFF;
1272
1273   /* Do not repeat PPS */
1274   option2->RepeatPPS = MFX_CODINGOPTION_OFF;
1275
1276   if (param->mfx.RateControlMethod == MFX_RATECONTROL_LA ||
1277       param->mfx.RateControlMethod == MFX_RATECONTROL_LA_HRD ||
1278       param->mfx.RateControlMethod == MFX_RATECONTROL_LA_ICQ) {
1279     option2->LookAheadDS = self->rc_lookahead_ds;
1280     option2->LookAheadDepth = self->rc_lookahead;
1281   }
1282
1283   option2->MinQPI = self->min_qp_i;
1284   option2->MinQPP = self->min_qp_p;
1285   option2->MinQPB = self->min_qp_b;
1286   option2->MaxQPI = self->max_qp_i;
1287   option2->MaxQPP = self->max_qp_p;
1288   option2->MaxQPB = self->max_qp_b;
1289
1290   /* QSV wants MFX_B_REF_PYRAMID when more than 1 b-frame is enabled */
1291   if (param->mfx.GopRefDist > 2)
1292     option2->BRefType = MFX_B_REF_PYRAMID;
1293
1294   /* Upstream specified framerate, we will believe it's fixed framerate */
1295   if (GST_VIDEO_INFO_FPS_N (info) > 0 && GST_VIDEO_INFO_FPS_D (info) > 0) {
1296     option2->FixedFrameRate = MFX_CODINGOPTION_ON;
1297     option3->TimingInfoPresent = MFX_CODINGOPTION_ON;
1298   }
1299
1300   if (param->mfx.RateControlMethod == MFX_RATECONTROL_QVBR)
1301     option3->QVBRQuality = self->qvbr_quality;
1302
1303   if (signal_info)
1304     g_ptr_array_add (extra_params, signal_info);
1305   g_ptr_array_add (extra_params, option);
1306   g_ptr_array_add (extra_params, option2);
1307   g_ptr_array_add (extra_params, option3);
1308
1309   param->ExtParam = (mfxExtBuffer **) extra_params->pdata;
1310   param->NumExtParam = extra_params->len;
1311
1312   self->bitrate_updated = FALSE;
1313   self->property_updated = FALSE;
1314
1315   g_mutex_unlock (&self->prop_lock);
1316
1317   return TRUE;
1318 }
1319
1320 static gboolean
1321 gst_qsv_h264_enc_set_output_state (GstQsvEncoder * encoder,
1322     GstVideoCodecState * state, mfxSession session)
1323 {
1324   GstQsvH264Enc *self = GST_QSV_H264_ENC (encoder);
1325   GstCaps *caps;
1326   GstTagList *tags;
1327   GstVideoCodecState *out_state;
1328   guint bitrate, max_bitrate;
1329   guint multiplier = 1;
1330   mfxVideoParam param;
1331   const gchar *profile_str;
1332   mfxStatus status;
1333   mfxExtCodingOptionSPSPPS sps_pps;
1334   mfxExtBuffer *ext_buffers[1];
1335   mfxU8 sps[1024];
1336   mfxU8 pps[1024];
1337   GstBuffer *codec_data = nullptr;
1338
1339   memset (&param, 0, sizeof (mfxVideoParam));
1340   memset (&sps_pps, 0, sizeof (mfxExtCodingOptionSPSPPS));
1341   if (self->packetized) {
1342     sps_pps.Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS;
1343     sps_pps.Header.BufferSz = sizeof (mfxExtCodingOptionSPSPPS);
1344
1345     sps_pps.SPSBuffer = sps;
1346     sps_pps.SPSBufSize = sizeof (sps);
1347
1348     sps_pps.PPSBuffer = pps;
1349     sps_pps.PPSBufSize = sizeof (pps);
1350
1351     ext_buffers[0] = (mfxExtBuffer *) & sps_pps;
1352
1353     param.NumExtParam = 1;
1354     param.ExtParam = ext_buffers;
1355   }
1356
1357   status = MFXVideoENCODE_GetVideoParam (session, &param);
1358   if (status < MFX_ERR_NONE) {
1359     GST_ERROR_OBJECT (self, "Failed to get video param %d (%s)",
1360         QSV_STATUS_ARGS (status));
1361     return FALSE;
1362   } else if (status != MFX_ERR_NONE) {
1363     GST_WARNING_OBJECT (self, "GetVideoParam returned warning %d (%s)",
1364         QSV_STATUS_ARGS (status));
1365   }
1366
1367   if (self->packetized) {
1368     GstH264ParserResult rst;
1369     GstH264NalUnit sps_nalu, pps_nalu;
1370     GstMapInfo info;
1371     guint8 *data;
1372     guint8 profile_idc, profile_comp, level_idc;
1373     const guint nal_length_size = 4;
1374     const guint num_sps = 1;
1375     const guint num_pps = 1;
1376
1377     rst = gst_h264_parser_identify_nalu_unchecked (self->parser,
1378         sps, 0, sps_pps.SPSBufSize, &sps_nalu);
1379     if (rst != GST_H264_PARSER_OK) {
1380       GST_ERROR_OBJECT (self, "Failed to identify SPS nal");
1381       return FALSE;
1382     }
1383
1384     if (sps_nalu.size < 4) {
1385       GST_ERROR_OBJECT (self, "Too small sps nal size %d", sps_nalu.size);
1386       return FALSE;
1387     }
1388
1389     data = sps_nalu.data + sps_nalu.offset + sps_nalu.header_bytes;
1390     profile_idc = data[0];
1391     profile_comp = data[1];
1392     level_idc = data[2];
1393
1394     rst = gst_h264_parser_identify_nalu_unchecked (self->parser,
1395         pps, 0, sps_pps.PPSBufSize, &pps_nalu);
1396     if (rst != GST_H264_PARSER_OK) {
1397       GST_ERROR_OBJECT (self, "Failed to identify PPS nal");
1398       return FALSE;
1399     }
1400
1401     /* 5: configuration version, profile, compatibility, level, nal length
1402      * 1: num sps
1403      * 2: sps size bytes
1404      * sizeof (sps)
1405      * 1: num pps
1406      * 2: pps size bytes
1407      * sizeof (pps)
1408      *
1409      * -> 11 + sps_size + pps_size
1410      */
1411     codec_data = gst_buffer_new_and_alloc (11 + sps_nalu.size + pps_nalu.size);
1412
1413     gst_buffer_map (codec_data, &info, GST_MAP_WRITE);
1414
1415     data = (guint8 *) info.data;
1416     data[0] = 1;
1417     data[1] = profile_idc;
1418     data[2] = profile_comp;
1419     data[3] = level_idc;
1420     data[4] = 0xfc | (nal_length_size - 1);
1421     data[5] = 0xe0 | num_sps;
1422     data += 6;
1423     GST_WRITE_UINT16_BE (data, sps_nalu.size);
1424     data += 2;
1425     memcpy (data, sps_nalu.data + sps_nalu.offset, sps_nalu.size);
1426     data += sps_nalu.size;
1427
1428     data[0] = num_pps;
1429     data++;
1430
1431     GST_WRITE_UINT16_BE (data, pps_nalu.size);
1432     data += 2;
1433     memcpy (data, pps_nalu.data + pps_nalu.offset, pps_nalu.size);
1434
1435     gst_buffer_unmap (codec_data, &info);
1436   }
1437
1438   caps = gst_caps_from_string ("video/x-h264, alignment = (string) au");
1439   profile_str = gst_qsv_h264_profile_to_string (param.mfx.CodecProfile);
1440   if (profile_str)
1441     gst_caps_set_simple (caps, "profile", G_TYPE_STRING, profile_str, nullptr);
1442
1443   if (self->packetized) {
1444     gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
1445         "codec_data", GST_TYPE_BUFFER, codec_data, nullptr);
1446     gst_buffer_unref (codec_data);
1447   } else {
1448     gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
1449         nullptr);
1450   }
1451
1452   out_state = gst_video_encoder_set_output_state (GST_VIDEO_ENCODER (encoder),
1453       caps, state);
1454   gst_video_codec_state_unref (out_state);
1455
1456   tags = gst_tag_list_new_empty ();
1457   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_ENCODER, "qsvh264enc",
1458       nullptr);
1459
1460   if (param.mfx.BRCParamMultiplier > 0)
1461     multiplier = param.mfx.BRCParamMultiplier;
1462
1463   switch (param.mfx.RateControlMethod) {
1464     case MFX_RATECONTROL_CQP:
1465     case MFX_RATECONTROL_ICQ:
1466     case MFX_RATECONTROL_LA_ICQ:
1467       /* We don't know target/max bitrate in this case */
1468       break;
1469     default:
1470       max_bitrate = (guint) param.mfx.MaxKbps * multiplier;
1471       bitrate = (guint) param.mfx.TargetKbps * multiplier;
1472       if (bitrate > 0) {
1473         gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
1474             GST_TAG_NOMINAL_BITRATE, bitrate * 1000, nullptr);
1475       }
1476
1477       if (max_bitrate > 0) {
1478         gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
1479             GST_TAG_MAXIMUM_BITRATE, max_bitrate * 1000, nullptr);
1480       }
1481       break;
1482   }
1483
1484   gst_video_encoder_merge_tags (GST_VIDEO_ENCODER (encoder),
1485       tags, GST_TAG_MERGE_REPLACE);
1486   gst_tag_list_unref (tags);
1487
1488   return TRUE;
1489 }
1490
1491 static gboolean
1492 gst_qsv_h264_enc_foreach_caption_meta (GstBuffer * buffer, GstMeta ** meta,
1493     GPtrArray * payload)
1494 {
1495   GstVideoCaptionMeta *cc_meta;
1496   GstByteWriter br;
1497   guint payload_size;
1498   guint extra_size;
1499   mfxPayload *p;
1500
1501   if ((*meta)->info->api != GST_VIDEO_CAPTION_META_API_TYPE)
1502     return TRUE;
1503
1504   cc_meta = (GstVideoCaptionMeta *) (*meta);
1505
1506   if (cc_meta->caption_type != GST_VIDEO_CAPTION_TYPE_CEA708_RAW)
1507     return TRUE;
1508
1509   /* QSV requires full sei_message() structure */
1510   /* 1 byte contry_code + 10 bytes CEA-708 specific data + caption data */
1511   payload_size = 11 + cc_meta->size;
1512   extra_size = payload_size / 255;
1513
1514   /* 1 byte SEI type + 1 byte SEI payload size (+ extra) + payload data */
1515   gst_byte_writer_init_with_size (&br, 2 + extra_size + payload_size, FALSE);
1516
1517   /* SEI type */
1518   gst_byte_writer_put_uint8 (&br, 4);
1519
1520   /* SEI payload size */
1521   while (payload_size >= 0xff) {
1522     gst_byte_writer_put_uint8 (&br, 0xff);
1523     payload_size -= 0xff;
1524   }
1525   gst_byte_writer_put_uint8 (&br, payload_size);
1526
1527   /* 8-bits itu_t_t35_country_code */
1528   gst_byte_writer_put_uint8 (&br, 181);
1529
1530   /* 16-bits itu_t_t35_provider_code */
1531   gst_byte_writer_put_uint8 (&br, 0);
1532   gst_byte_writer_put_uint8 (&br, 49);
1533
1534   /* 32-bits ATSC_user_identifier */
1535   gst_byte_writer_put_uint8 (&br, 'G');
1536   gst_byte_writer_put_uint8 (&br, 'A');
1537   gst_byte_writer_put_uint8 (&br, '9');
1538   gst_byte_writer_put_uint8 (&br, '4');
1539
1540   /* 8-bits ATSC1_data_user_data_type_code */
1541   gst_byte_writer_put_uint8 (&br, 3);
1542
1543   /* 8-bits:
1544    * 1 bit process_em_data_flag (0)
1545    * 1 bit process_cc_data_flag (1)
1546    * 1 bit additional_data_flag (0)
1547    * 5-bits cc_count
1548    */
1549   gst_byte_writer_put_uint8 (&br, ((cc_meta->size / 3) & 0x1f) | 0x40);
1550
1551   /* 8 bits em_data, unused */
1552   gst_byte_writer_put_uint8 (&br, 255);
1553
1554   gst_byte_writer_put_data (&br, cc_meta->data, cc_meta->size);
1555
1556   /* 8 marker bits */
1557   gst_byte_writer_put_uint8 (&br, 255);
1558
1559   p = g_new0 (mfxPayload, 1);
1560   p->BufSize = gst_byte_writer_get_pos (&br);
1561   p->NumBit = p->BufSize * 8;
1562   p->Type = 4;
1563   p->Data = gst_byte_writer_reset_and_get_data (&br);
1564
1565   g_ptr_array_add (payload, p);
1566
1567   return TRUE;
1568 }
1569
1570 static gboolean
1571 gst_qsv_h264_enc_attach_payload (GstQsvEncoder * encoder,
1572     GstVideoCodecFrame * frame, GPtrArray * payload)
1573 {
1574   GstQsvH264Enc *self = GST_QSV_H264_ENC (encoder);
1575
1576   if (self->cc_insert == GST_QSV_H264_ENC_SEI_DISABLED)
1577     return TRUE;
1578
1579   gst_buffer_foreach_meta (frame->input_buffer,
1580       (GstBufferForeachMetaFunc) gst_qsv_h264_enc_foreach_caption_meta,
1581       payload);
1582
1583   return TRUE;
1584 }
1585
1586 static GstBuffer *
1587 gst_qsv_h264_enc_create_output_buffer (GstQsvEncoder * encoder,
1588     mfxBitstream * bitstream)
1589 {
1590   GstQsvH264Enc *self = GST_QSV_H264_ENC (encoder);
1591   GstBuffer *buf;
1592   GstH264ParserResult rst;
1593   GstH264NalUnit nalu;
1594
1595   if (!self->packetized) {
1596     buf = gst_buffer_new_memdup (bitstream->Data + bitstream->DataOffset,
1597         bitstream->DataLength);
1598   } else {
1599     buf = gst_buffer_new ();
1600     rst = gst_h264_parser_identify_nalu (self->parser,
1601         bitstream->Data + bitstream->DataOffset, 0, bitstream->DataLength,
1602         &nalu);
1603     if (rst == GST_H264_PARSER_NO_NAL_END)
1604       rst = GST_H264_PARSER_OK;
1605
1606     while (rst == GST_H264_PARSER_OK) {
1607       GstMemory *mem;
1608       guint8 *data;
1609
1610       data = (guint8 *) g_malloc0 (nalu.size + 4);
1611       GST_WRITE_UINT32_BE (data, nalu.size);
1612       memcpy (data + 4, nalu.data + nalu.offset, nalu.size);
1613
1614       mem = gst_memory_new_wrapped ((GstMemoryFlags) 0, data, nalu.size + 4,
1615           0, nalu.size + 4, data, (GDestroyNotify) g_free);
1616       gst_buffer_append_memory (buf, mem);
1617
1618       rst = gst_h264_parser_identify_nalu (self->parser,
1619           bitstream->Data + bitstream->DataOffset, nalu.offset + nalu.size,
1620           bitstream->DataLength, &nalu);
1621
1622       if (rst == GST_H264_PARSER_NO_NAL_END)
1623         rst = GST_H264_PARSER_OK;
1624     }
1625   }
1626
1627   /* This buffer must be the end of a frame boundary */
1628   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_MARKER);
1629
1630   return buf;
1631 }
1632
1633 static GstQsvEncoderReconfigure
1634 gst_qsv_h264_enc_check_reconfigure (GstQsvEncoder * encoder, mfxSession session,
1635     mfxVideoParam * param, GPtrArray * extra_params)
1636 {
1637   GstQsvH264Enc *self = GST_QSV_H264_ENC (encoder);
1638   GstQsvEncoderReconfigure ret = GST_QSV_ENCODER_RECONFIGURE_NONE;
1639
1640   g_mutex_lock (&self->prop_lock);
1641   if (self->property_updated) {
1642     ret = GST_QSV_ENCODER_RECONFIGURE_FULL;
1643     goto done;
1644   }
1645
1646   if (self->bitrate_updated) {
1647     mfxStatus status;
1648     mfxExtEncoderResetOption reset_opt;
1649     reset_opt.Header.BufferId = MFX_EXTBUFF_ENCODER_RESET_OPTION;
1650     reset_opt.Header.BufferSz = sizeof (mfxExtEncoderResetOption);
1651     reset_opt.StartNewSequence = MFX_CODINGOPTION_UNKNOWN;
1652
1653     gst_qsv_h264_enc_set_bitrate (self, param);
1654
1655     g_ptr_array_add (extra_params, &reset_opt);
1656     param->ExtParam = (mfxExtBuffer **) extra_params->pdata;
1657     param->NumExtParam = extra_params->len;
1658
1659     status = MFXVideoENCODE_Query (session, param, param);
1660     g_ptr_array_remove_index (extra_params, extra_params->len - 1);
1661     param->NumExtParam = extra_params->len;
1662
1663     if (status != MFX_ERR_NONE) {
1664       GST_WARNING_OBJECT (self, "MFXVideoENCODE_Query returned %d (%s)",
1665           QSV_STATUS_ARGS (status));
1666       ret = GST_QSV_ENCODER_RECONFIGURE_FULL;
1667     } else {
1668       if (reset_opt.StartNewSequence == MFX_CODINGOPTION_OFF) {
1669         GST_DEBUG_OBJECT (self, "Can update without new sequence");
1670         ret = GST_QSV_ENCODER_RECONFIGURE_BITRATE;
1671       } else {
1672         GST_DEBUG_OBJECT (self, "Need new sequence");
1673         ret = GST_QSV_ENCODER_RECONFIGURE_FULL;
1674       }
1675     }
1676   }
1677
1678 done:
1679   self->property_updated = FALSE;
1680   self->bitrate_updated = FALSE;
1681   g_mutex_unlock (&self->prop_lock);
1682
1683   return ret;
1684 }
1685
1686 typedef struct
1687 {
1688   guint width;
1689   guint height;
1690 } Resolution;
1691
1692 void
1693 gst_qsv_h264_enc_register (GstPlugin * plugin, guint rank, guint impl_index,
1694     GstObject * device, mfxSession session)
1695 {
1696   mfxStatus status;
1697   mfxVideoParam param;
1698   mfxInfoMFX *mfx;
1699   static const Resolution resolutions_to_check[] = {
1700     {1280, 720}, {1920, 1088}, {2560, 1440}, {3840, 2160}, {4096, 2160},
1701     {7680, 4320}, {8192, 4320}
1702   };
1703   std::vector < mfxU16 > supported_profiles;
1704   Resolution max_resolution;
1705   bool supports_interlaced = false;
1706
1707   GST_DEBUG_CATEGORY_INIT (gst_qsv_h264_enc_debug,
1708       "qsvh264enc", 0, "qsvh264enc");
1709
1710   memset (&param, 0, sizeof (mfxVideoParam));
1711   memset (&max_resolution, 0, sizeof (Resolution));
1712
1713   param.AsyncDepth = 4;
1714   param.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
1715
1716   mfx = &param.mfx;
1717   mfx->CodecId = MFX_CODEC_AVC;
1718
1719   mfx->FrameInfo.Width = GST_ROUND_UP_16 (320);
1720   mfx->FrameInfo.Height = GST_ROUND_UP_16 (240);
1721   mfx->FrameInfo.CropW = 320;
1722   mfx->FrameInfo.CropH = 240;
1723   mfx->FrameInfo.FrameRateExtN = 30;
1724   mfx->FrameInfo.FrameRateExtD = 1;
1725   mfx->FrameInfo.AspectRatioW = 1;
1726   mfx->FrameInfo.AspectRatioH = 1;
1727   mfx->FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
1728   mfx->FrameInfo.FourCC = MFX_FOURCC_NV12;
1729   mfx->FrameInfo.BitDepthLuma = 8;
1730   mfx->FrameInfo.BitDepthChroma = 8;
1731   mfx->FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
1732
1733   /* Check supported profiles */
1734   for (guint i = 0; i < G_N_ELEMENTS (profile_map); i++) {
1735     mfx->CodecProfile = profile_map[i].profile;
1736
1737     if (MFXVideoENCODE_Query (session, &param, &param) != MFX_ERR_NONE)
1738       continue;
1739
1740     supported_profiles.push_back (profile_map[i].profile);
1741   }
1742
1743   if (supported_profiles.empty ()) {
1744     GST_INFO ("Device doesn't support H.264 encoding");
1745     return;
1746   }
1747
1748   mfx->CodecProfile = supported_profiles[0];
1749
1750   /* Check max-resolution */
1751   for (guint i = 0; i < G_N_ELEMENTS (resolutions_to_check); i++) {
1752     mfx->FrameInfo.Width = GST_ROUND_UP_16 (resolutions_to_check[i].width);
1753     mfx->FrameInfo.Height = GST_ROUND_UP_16 (resolutions_to_check[i].height);
1754     mfx->FrameInfo.CropW = resolutions_to_check[i].width;
1755     mfx->FrameInfo.CropH = resolutions_to_check[i].height;
1756
1757     if (MFXVideoENCODE_Query (session, &param, &param) != MFX_ERR_NONE)
1758       break;
1759
1760     max_resolution.width = resolutions_to_check[i].width;
1761     max_resolution.height = resolutions_to_check[i].height;
1762   }
1763
1764   GST_INFO ("Maximum supported resolution: %dx%d",
1765       max_resolution.width, max_resolution.height);
1766
1767   /* TODO: check supported rate-control methods and expose only supported
1768    * methods, since the device might not be able to support some of them */
1769
1770   /* Check interlaced encoding */
1771   /* *INDENT-OFF* */
1772   for (const auto &iter: supported_profiles) {
1773     if (iter == MFX_PROFILE_AVC_MAIN ||
1774         iter == MFX_PROFILE_AVC_HIGH) {
1775       /* Make sure non-lowpower mode, otherwise QSV will not accept
1776        * interlaced format during Query() */
1777       mfx->LowPower = MFX_CODINGOPTION_UNKNOWN;
1778
1779       /* Interlaced encoding is not compatible with MFX_RATECONTROL_VCM,
1780        * make sure profile */
1781       mfx->RateControlMethod = MFX_RATECONTROL_CBR;
1782
1783       /* Too high (MFX_LEVEL_AVC_41) or low (MFX_LEVEL_AVC_21) level will not be
1784        * accepted for interlaced encoding */
1785       mfx->CodecLevel = MFX_LEVEL_UNKNOWN;
1786       mfx->CodecProfile = iter;
1787
1788       mfx->FrameInfo.Width = GST_ROUND_UP_16 (320);
1789       mfx->FrameInfo.Height = GST_ROUND_UP_32 (240);
1790       mfx->FrameInfo.CropW = 320;
1791       mfx->FrameInfo.CropH = 240;
1792       mfx->FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
1793
1794       status = MFXVideoENCODE_Query (session, &param, &param);
1795
1796       if (status == MFX_ERR_NONE) {
1797         GST_INFO ("Interlaced encoding is supported");
1798         supports_interlaced = true;
1799         break;
1800       }
1801     }
1802   }
1803   /* *INDENT-ON* */
1804
1805   /* To cover both landscape and portrait,
1806    * select max value (width in this case) */
1807   guint resolution = MAX (max_resolution.width, max_resolution.height);
1808   std::string sink_caps_str = "video/x-raw, format=(string) NV12";
1809
1810   sink_caps_str += ", width=(int) [ 16, " + std::to_string (resolution) + " ]";
1811   sink_caps_str += ", height=(int) [ 16, " + std::to_string (resolution) + " ]";
1812   if (!supports_interlaced)
1813     sink_caps_str += ", interlace-mode = (string) progressive";
1814
1815   GstCaps *sink_caps = gst_caps_from_string (sink_caps_str.c_str ());
1816
1817   /* TODO: Add support for VA */
1818 #ifdef G_OS_WIN32
1819   GstCaps *d3d11_caps = gst_caps_copy (sink_caps);
1820   GstCapsFeatures *caps_features =
1821       gst_caps_features_new (GST_CAPS_FEATURE_MEMORY_D3D11_MEMORY, nullptr);
1822   gst_caps_set_features_simple (d3d11_caps, caps_features);
1823   gst_caps_append (d3d11_caps, sink_caps);
1824   sink_caps = d3d11_caps;
1825 #else
1826   GstCaps *va_caps = gst_caps_copy (sink_caps);
1827   GstCapsFeatures *caps_features =
1828       gst_caps_features_new (GST_CAPS_FEATURE_MEMORY_VA, nullptr);
1829   gst_caps_set_features_simple (va_caps, caps_features);
1830   gst_caps_append (va_caps, sink_caps);
1831   sink_caps = va_caps;
1832 #endif
1833
1834   std::string src_caps_str = "video/x-h264";
1835   src_caps_str += ", width=(int) [ 16, " + std::to_string (resolution) + " ]";
1836   src_caps_str += ", height=(int) [ 16, " + std::to_string (resolution) + " ]";
1837
1838   src_caps_str += ", stream-format= (string) { avc, byte-stream }";
1839   src_caps_str += ", alignment=(string) au";
1840   /* *INDENT-OFF* */
1841   if (supported_profiles.size () > 1) {
1842     src_caps_str += ", profile=(string) { ";
1843     bool first = true;
1844     for (const auto &iter: supported_profiles) {
1845       if (!first) {
1846         src_caps_str += ", ";
1847       }
1848
1849       src_caps_str += gst_qsv_h264_profile_to_string (iter);
1850       first = false;
1851     }
1852     src_caps_str += " }";
1853   } else {
1854     src_caps_str += ", profile=(string) ";
1855     src_caps_str += gst_qsv_h264_profile_to_string (supported_profiles[0]);
1856   }
1857   /* *INDENT-ON* */
1858
1859   GstCaps *src_caps = gst_caps_from_string (src_caps_str.c_str ());
1860
1861   GST_MINI_OBJECT_FLAG_SET (sink_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1862   GST_MINI_OBJECT_FLAG_SET (src_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1863
1864   GstQsvH264EncClassData *cdata = g_new0 (GstQsvH264EncClassData, 1);
1865   cdata->sink_caps = sink_caps;
1866   cdata->src_caps = src_caps;
1867   cdata->impl_index = impl_index;
1868
1869 #ifdef G_OS_WIN32
1870   g_object_get (device, "adapter-luid", &cdata->adapter_luid,
1871       "description", &cdata->description, nullptr);
1872 #else
1873   g_object_get (device, "path", &cdata->display_path, nullptr);
1874 #endif
1875
1876   GType type;
1877   gchar *type_name;
1878   gchar *feature_name;
1879   GTypeInfo type_info = {
1880     sizeof (GstQsvH264EncClass),
1881     nullptr,
1882     nullptr,
1883     (GClassInitFunc) gst_qsv_h264_enc_class_init,
1884     nullptr,
1885     cdata,
1886     sizeof (GstQsvH264Enc),
1887     0,
1888     (GInstanceInitFunc) gst_qsv_h264_enc_init,
1889   };
1890
1891   type_name = g_strdup ("GstQsvH264Enc");
1892   feature_name = g_strdup ("qsvh264enc");
1893
1894   gint index = 0;
1895   while (g_type_from_name (type_name)) {
1896     index++;
1897     g_free (type_name);
1898     g_free (feature_name);
1899     type_name = g_strdup_printf ("GstQsvH264Device%dEnc", index);
1900     feature_name = g_strdup_printf ("qsvh264device%denc", index);
1901   }
1902
1903   type = g_type_register_static (GST_TYPE_QSV_ENCODER, type_name, &type_info,
1904       (GTypeFlags) 0);
1905
1906   if (rank > 0 && index != 0)
1907     rank--;
1908
1909   if (!gst_element_register (plugin, feature_name, rank, type))
1910     GST_WARNING ("Failed to register plugin '%s'", type_name);
1911
1912   g_free (type_name);
1913   g_free (feature_name);
1914 }