va: Fix struct empty initialization syntax
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / va / gstvah264enc.c
1 /* GStreamer
2  *  Copyright (C) 2021 Intel Corporation
3  *     Author: He Junyan <junyan.he@intel.com>
4  *     Author: Víctor Jáquez <vjaquez@igalia.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 /**
23  * SECTION:element-vah264enc
24  * @title: vah264enc
25  * @short_description: A VA-API based H264 video encoder
26  *
27  * vah264enc encodes raw video VA surfaces into H.264 bitstreams using
28  * the installed and chosen [VA-API](https://01.org/linuxmedia/vaapi)
29  * driver.
30  *
31  * The raw video frames in main memory can be imported into VA surfaces.
32  *
33  * ## Example launch line
34  * ```
35  * gst-launch-1.0 videotestsrc num-buffers=60 ! timeoverlay ! vah264enc ! h264parse ! mp4mux ! filesink location=test.mp4
36  * ```
37  *
38  * Since: 1.22
39  *
40  */
41
42  /* @TODO:
43   * 1. Look ahead, which can optimize the slice type and QP.
44   * 2. Field encoding.
45   * 3. The stereo encoding such as the frame-packing or MVC.
46   * 4. Weight prediction of B frame.
47   * 5. latency calculation.
48   */
49
50 #ifdef HAVE_CONFIG_H
51 #include "config.h"
52 #endif
53
54 #include "gstvah264enc.h"
55
56 #include <gst/codecparsers/gsth264bitwriter.h>
57 #include <gst/va/gstva.h>
58 #include <gst/va/gstvavideoformat.h>
59 #include <gst/va/vasurfaceimage.h>
60 #include <gst/video/video.h>
61 #include <va/va_drmcommon.h>
62
63 #include "gstvabaseenc.h"
64 #include "gstvacaps.h"
65 #include "gstvadisplay_priv.h"
66 #include "gstvaencoder.h"
67 #include "gstvaprofile.h"
68 #include "vacompat.h"
69
70 GST_DEBUG_CATEGORY_STATIC (gst_va_h264enc_debug);
71 #define GST_CAT_DEFAULT gst_va_h264enc_debug
72
73 #define GST_VA_H264_ENC(obj)            ((GstVaH264Enc *) obj)
74 #define GST_VA_H264_ENC_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), G_TYPE_FROM_INSTANCE (obj), GstVaH264EncClass))
75 #define GST_VA_H264_ENC_CLASS(klass)    ((GstVaH264EncClass *) klass)
76
77 typedef struct _GstVaH264Enc GstVaH264Enc;
78 typedef struct _GstVaH264EncClass GstVaH264EncClass;
79 typedef struct _GstVaH264EncFrame GstVaH264EncFrame;
80 typedef struct _GstVaH264LevelLimits GstVaH264LevelLimits;
81
82 enum
83 {
84   PROP_KEY_INT_MAX = 1,
85   PROP_BFRAMES,
86   PROP_IFRAMES,
87   PROP_NUM_REF_FRAMES,
88   PROP_B_PYRAMID,
89   PROP_NUM_SLICES,
90   PROP_MIN_QP,
91   PROP_MAX_QP,
92   PROP_QP_I,
93   PROP_QP_P,
94   PROP_QP_B,
95   PROP_DCT8X8,
96   PROP_CABAC,
97   PROP_TRELLIS,
98   PROP_MBBRC,
99   PROP_BITRATE,
100   PROP_TARGET_PERCENTAGE,
101   PROP_TARGET_USAGE,
102   PROP_RATE_CONTROL,
103   PROP_CPB_SIZE,
104   PROP_AUD,
105   PROP_CC,
106   N_PROPERTIES
107 };
108
109 static GParamSpec *properties[N_PROPERTIES];
110
111 static GstElementClass *parent_class = NULL;
112
113 /* Scale factor for bitrate (HRD bit_rate_scale: min = 6) */
114 #define SX_BITRATE 6
115 /* Scale factor for CPB size (HRD cpb_size_scale: min = 4) */
116 #define SX_CPB_SIZE 4
117 /* Maximum sizes for common headers (in bits) */
118 #define MAX_SPS_HDR_SIZE  16473
119 #define MAX_VUI_PARAMS_SIZE  210
120 #define MAX_HRD_PARAMS_SIZE  4103
121 #define MAX_PPS_HDR_SIZE  101
122 #define MAX_SLICE_HDR_SIZE  397 + 2572 + 6670 + 2402
123
124 #define MAX_GOP_SIZE  1024
125
126 /* *INDENT-OFF* */
127 struct _GstVaH264EncClass
128 {
129   GstVaBaseEncClass parent_class;
130
131   GType rate_control_type;
132   char rate_control_type_name[64];
133   GEnumValue rate_control[16];
134 };
135 /* *INDENT-ON* */
136
137 struct _GstVaH264Enc
138 {
139   /*< private > */
140   GstVaBaseEnc parent;
141
142   /* properties */
143   struct
144   {
145     /* kbps */
146     guint bitrate;
147     /* VA_RC_XXX */
148     guint32 rc_ctrl;
149     guint key_int_max;
150     guint32 num_ref_frames;
151     gboolean b_pyramid;
152     guint32 num_bframes;
153     guint32 num_iframes;
154     guint32 min_qp;
155     guint32 max_qp;
156     guint32 qp_i;
157     guint32 qp_p;
158     guint32 qp_b;
159     gboolean use_cabac;
160     gboolean use_dct8x8;
161     gboolean use_trellis;
162     gboolean aud;
163     gboolean cc;
164     guint32 mbbrc;
165     guint32 num_slices;
166     guint32 cpb_size;
167     guint32 target_percentage;
168     guint32 target_usage;
169   } prop;
170
171   /* H264 fields */
172   gint mb_width;
173   gint mb_height;
174   guint8 level_idc;
175   const gchar *level_str;
176   /* Minimum Compression Ratio (A.3.1) */
177   guint min_cr;
178   gboolean use_cabac;
179   gboolean use_dct8x8;
180   gboolean use_trellis;
181   gboolean aud;
182   gboolean cc;
183   guint32 num_slices;
184   guint32 packed_headers;
185
186   struct
187   {
188     /* frames between two IDR [idr, ...., idr) */
189     guint32 idr_period;
190     /* How may IDRs we have encoded */
191     guint32 total_idr_count;
192     /* frames between I/P and P frames [I, B, B, .., B, P) */
193     guint32 ip_period;
194     /* frames between I frames [I, B, B, .., B, P, ..., I), open GOP */
195     guint32 i_period;
196     /* B frames between I/P and P. */
197     guint32 num_bframes;
198     /* Use B pyramid structure in the GOP. */
199     gboolean b_pyramid;
200     /* Level 0 is the simple B not acting as ref. */
201     guint32 highest_pyramid_level;
202     /* If open GOP, I frames within a GOP. */
203     guint32 num_iframes;
204     /* A map of all frames types within a GOP. */
205     struct
206     {
207       guint8 slice_type;
208       gboolean is_ref;
209       guint8 pyramid_level;
210       /* Only for b pyramid */
211       gint left_ref_poc_diff;
212       gint right_ref_poc_diff;
213     } frame_types[MAX_GOP_SIZE];
214     /* current index in the frames types map. */
215     guint cur_frame_index;
216     /* Number of ref frames within current GOP. H264's frame num. */
217     gint cur_frame_num;
218     /* Max frame num within a GOP. */
219     guint32 max_frame_num;
220     guint32 log2_max_frame_num;
221     /* Max poc within a GOP. */
222     guint32 max_pic_order_cnt;
223     guint32 log2_max_pic_order_cnt;
224
225     /* Total ref frames of list0 and list1. */
226     guint32 num_ref_frames;
227     guint32 ref_num_list0;
228     guint32 ref_num_list1;
229
230     guint num_reorder_frames;
231   } gop;
232
233   struct
234   {
235     guint target_usage;
236     guint32 rc_ctrl_mode;
237
238     guint32 min_qp;
239     guint32 max_qp;
240     guint32 qp_i;
241     guint32 qp_p;
242     guint32 qp_b;
243     /* macroblock bitrate control */
244     guint32 mbbrc;
245     guint target_bitrate;
246     guint target_percentage;
247     guint max_bitrate;
248     /* bitrate (bits) */
249     guint max_bitrate_bits;
250     guint target_bitrate_bits;
251     /* length of CPB buffer */
252     guint cpb_size;
253     /* length of CPB buffer (bits) */
254     guint cpb_length_bits;
255   } rc;
256
257   GstH264SPS sequence_hdr;
258 };
259
260 struct _GstVaH264EncFrame
261 {
262   GstVaEncodePicture *picture;
263   GstH264SliceType type;
264   gboolean is_ref;
265   guint pyramid_level;
266   /* Only for b pyramid */
267   gint left_ref_poc_diff;
268   gint right_ref_poc_diff;
269
270   gint poc;
271   gint frame_num;
272   /* The pic_num will be marked as unused_for_reference, which is
273    * replaced by this frame. -1 if we do not need to care about it
274    * explicitly. */
275   gint unused_for_reference_pic_num;
276
277   /* The total frame count we handled. */
278   guint total_frame_count;
279
280   gboolean last_frame;
281 };
282
283 /**
284  * GstVaH264LevelLimits:
285  * @name: the level name
286  * @level_idc: the H.264 level_idc value
287  * @MaxMBPS: the maximum macroblock processing rate (MB/sec)
288  * @MaxFS: the maximum frame size (MBs)
289  * @MaxDpbMbs: the maxium decoded picture buffer size (MBs)
290  * @MaxBR: the maximum video bit rate (kbps)
291  * @MaxCPB: the maximum CPB size (kbits)
292  * @MinCR: the minimum Compression Ratio
293  *
294  * The data structure that describes the limits of an H.264 level.
295  */
296 struct _GstVaH264LevelLimits
297 {
298   const gchar *name;
299   guint8 level_idc;
300   guint32 MaxMBPS;
301   guint32 MaxFS;
302   guint32 MaxDpbMbs;
303   guint32 MaxBR;
304   guint32 MaxCPB;
305   guint32 MinCR;
306 };
307
308 /* Table A-1 - Level limits */
309 /* *INDENT-OFF* */
310 static const GstVaH264LevelLimits _va_h264_level_limits[] = {
311   /* level   idc   MaxMBPS   MaxFS   MaxDpbMbs  MaxBR   MaxCPB  MinCr */
312   {  "1",    10,   1485,     99,     396,       64,     175,    2 },
313   {  "1b",   11,   1485,     99,     396,       128,    350,    2 },
314   {  "1.1",  11,   3000,     396,    900,       192,    500,    2 },
315   {  "1.2",  12,   6000,     396,    2376,      384,    1000,   2 },
316   {  "1.3",  13,   11880,    396,    2376,      768,    2000,   2 },
317   {  "2",    20,   11880,    396,    2376,      2000,   2000,   2 },
318   {  "2.1",  21,   19800,    792,    4752,      4000,   4000,   2 },
319   {  "2.2",  22,   20250,    1620,   8100,      4000,   4000,   2 },
320   {  "3",    30,   40500,    1620,   8100,      10000,  10000,  2 },
321   {  "3.1",  31,   108000,   3600,   18000,     14000,  14000,  4 },
322   {  "3.2",  32,   216000,   5120,   20480,     20000,  20000,  4 },
323   {  "4",    40,   245760,   8192,   32768,     20000,  25000,  4 },
324   {  "4.1",  41,   245760,   8192,   32768,     50000,  62500,  2 },
325   {  "4.2",  42,   522240,   8704,   34816,     50000,  62500,  2 },
326   {  "5",    50,   589824,   22080,  110400,    135000, 135000, 2 },
327   {  "5.1",  51,   983040,   36864,  184320,    240000, 240000, 2 },
328   {  "5.2",  52,   2073600,  36864,  184320,    240000, 240000, 2 },
329   {  "6",    60,   4177920,  139264, 696320,    240000, 240000, 2 },
330   {  "6.1",  61,   8355840,  139264, 696320,    480000, 480000, 2 },
331   {  "6.2",  62,  16711680,  139264, 696320,    800000, 800000, 2 },
332 };
333 /* *INDENT-ON* */
334
335 #ifndef GST_DISABLE_GST_DEBUG
336 static const gchar *
337 _slice_type_name (GstH264SliceType type)
338 {
339   switch (type) {
340     case GST_H264_P_SLICE:
341       return "P";
342     case GST_H264_B_SLICE:
343       return "B";
344     case GST_H264_I_SLICE:
345       return "I";
346     default:
347       g_assert_not_reached ();
348   }
349
350   return NULL;
351 }
352
353 static const gchar *
354 _rate_control_get_name (guint32 rc_mode)
355 {
356   GParamSpecEnum *spec;
357   guint i;
358
359   if (!(properties[PROP_RATE_CONTROL]
360           && G_IS_PARAM_SPEC_ENUM (properties[PROP_RATE_CONTROL])))
361     return NULL;
362
363   spec = G_PARAM_SPEC_ENUM (properties[PROP_RATE_CONTROL]);
364   for (i = 0; i < spec->enum_class->n_values; i++) {
365     if (spec->enum_class->values[i].value == rc_mode)
366       return spec->enum_class->values[i].value_nick;
367   }
368
369   return NULL;
370 }
371 #endif
372
373 static GstVaH264EncFrame *
374 gst_va_enc_frame_new (void)
375 {
376   GstVaH264EncFrame *frame;
377
378   frame = g_slice_new (GstVaH264EncFrame);
379   frame->frame_num = 0;
380   frame->unused_for_reference_pic_num = -1;
381   frame->picture = NULL;
382   frame->total_frame_count = 0;
383   frame->last_frame = FALSE;
384
385   return frame;
386 }
387
388 static void
389 gst_va_enc_frame_free (gpointer pframe)
390 {
391   GstVaH264EncFrame *frame = pframe;
392   g_clear_pointer (&frame->picture, gst_va_encode_picture_free);
393   g_slice_free (GstVaH264EncFrame, frame);
394 }
395
396 static inline GstVaH264EncFrame *
397 _enc_frame (GstVideoCodecFrame * frame)
398 {
399   GstVaH264EncFrame *enc_frame = gst_video_codec_frame_get_user_data (frame);
400   g_assert (enc_frame);
401   return enc_frame;
402 }
403
404 /* Normalizes bitrate (and CPB size) for HRD conformance */
405 static void
406 _calculate_bitrate_hrd (GstVaH264Enc * self)
407 {
408   guint bitrate_bits, cpb_bits_size;
409
410   /* Round down bitrate. This is a hard limit mandated by the user */
411   g_assert (SX_BITRATE >= 6);
412   bitrate_bits = (self->rc.max_bitrate * 1000) & ~((1U << SX_BITRATE) - 1);
413   GST_DEBUG_OBJECT (self, "Max bitrate: %u bits/sec", bitrate_bits);
414   self->rc.max_bitrate_bits = bitrate_bits;
415
416   bitrate_bits = (self->rc.target_bitrate * 1000) & ~((1U << SX_BITRATE) - 1);
417   GST_DEBUG_OBJECT (self, "Target bitrate: %u bits/sec", bitrate_bits);
418   self->rc.target_bitrate_bits = bitrate_bits;
419
420   if (self->rc.cpb_size > 0 && self->rc.cpb_size < (self->rc.max_bitrate / 2)) {
421     GST_INFO_OBJECT (self, "Too small cpb_size: %d", self->rc.cpb_size);
422     self->rc.cpb_size = 0;
423   }
424
425   if (self->rc.cpb_size == 0) {
426     /* We cache 2 second coded data by default. */
427     self->rc.cpb_size = self->rc.max_bitrate * 2;
428     GST_INFO_OBJECT (self, "Adjust cpb_size to: %d", self->rc.cpb_size);
429   }
430
431   /* Round up CPB size. This is an HRD compliance detail */
432   g_assert (SX_CPB_SIZE >= 4);
433   cpb_bits_size = (self->rc.cpb_size * 1000) & ~((1U << SX_CPB_SIZE) - 1);
434
435   GST_DEBUG_OBJECT (self, "HRD CPB size: %u bits", cpb_bits_size);
436   self->rc.cpb_length_bits = cpb_bits_size;
437 }
438
439 #define update_property(type, obj, old_val, new_val, prop_id)           \
440   gst_va_base_enc_update_property_##type (obj, old_val, new_val, properties[prop_id])
441 #define update_property_uint(obj, old_val, new_val, prop_id)    \
442   update_property (uint, obj, old_val, new_val, prop_id)
443 #define update_property_bool(obj, old_val, new_val, prop_id)    \
444   update_property (bool, obj, old_val, new_val, prop_id)
445
446 /* Estimates a good enough bitrate if none was supplied */
447 static gboolean
448 _ensure_rate_control (GstVaH264Enc * self)
449 {
450   /* User can specify the properties of: "bitrate", "target-percentage",
451    * "max-qp", "min-qp", "qpi", "qpp", "qpb", "mbbrc", "cpb-size",
452    * "rate-control" and "target-usage" to control the RC behavior.
453    *
454    * "target-usage" is different from the others, it controls the encoding
455    * speed and quality, while the others control encoding bit rate and
456    * quality. The lower value has better quality(maybe bigger MV search
457    * range) but slower speed, the higher value has faster speed but lower
458    * quality.
459    *
460    * The possible composition to control the bit rate and quality:
461    *
462    * 1. CQP mode: "rate-control=cqp", then "qpi", "qpp" and "qpb"
463    *    specify the QP of I/P/B frames respectively(within the
464    *    "max-qp" and "min-qp" range). The QP will not change during
465    *    the whole stream. Other properties are ignored.
466    *
467    * 2. CBR mode: "rate-control=CBR", then the "bitrate" specify the
468    *    target bit rate and the "cpb-size" specifies the max coded
469    *    picture buffer size to avoid overflow. If the "bitrate" is not
470    *    set, it is calculated by the picture resolution and frame
471    *    rate. If "cpb-size" is not set, it is set to the size of
472    *    caching 2 second coded data. Encoder will try its best to make
473    *    the QP with in the ["max-qp", "min-qp"] range. "mbbrc" can
474    *    enable bit rate control in macro block level. Other paramters
475    *    are ignored.
476    *
477    * 3. VBR mode: "rate-control=VBR", then the "bitrate" specify the
478    *    target bit rate, "target-percentage" is used to calculate the
479    *    max bit rate of VBR mode by ("bitrate" * 100) /
480    *    "target-percentage". It is also used by driver to calculate
481    *    the min bit rate. The "cpb-size" specifies the max coded
482    *    picture buffer size to avoid overflow. If the "bitrate" is not
483    *    set, the target bit rate will be calculated by the picture
484    *    resolution and frame rate. Encoder will try its best to make
485    *    the QP with in the ["max-qp", "min-qp"] range. "mbbrc" can
486    *    enable bit rate control in macro block level. Other paramters
487    *    are ignored.
488    *
489    * 4. VCM mode: "rate-control=VCM", then the "bitrate" specify the
490    *    target bit rate, and encoder will try its best to make the QP
491    *    with in the ["max-qp", "min-qp"] range. Other paramters are
492    *    ignored.
493    */
494
495   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
496   guint bitrate;
497   guint32 rc_ctrl, rc_mode, quality_level;
498
499   quality_level = gst_va_encoder_get_quality_level (base->encoder,
500       base->profile, GST_VA_BASE_ENC_ENTRYPOINT (base));
501   if (self->rc.target_usage > quality_level) {
502     GST_INFO_OBJECT (self, "User setting target-usage: %d is not supported, "
503         "fallback to %d", self->rc.target_usage, quality_level);
504     self->rc.target_usage = quality_level;
505
506     update_property_uint (base, &self->prop.target_usage, self->rc.target_usage,
507         PROP_TARGET_USAGE);
508   }
509
510   GST_OBJECT_LOCK (self);
511   rc_ctrl = self->prop.rc_ctrl;
512   GST_OBJECT_UNLOCK (self);
513
514   if (rc_ctrl != VA_RC_NONE) {
515     rc_mode = gst_va_encoder_get_rate_control_mode (base->encoder,
516         base->profile, GST_VA_BASE_ENC_ENTRYPOINT (base));
517     if (!(rc_mode & rc_ctrl)) {
518       guint32 defval =
519           G_PARAM_SPEC_ENUM (properties[PROP_RATE_CONTROL])->default_value;
520       GST_INFO_OBJECT (self, "The rate control mode %s is not supported, "
521           "fallback to %s mode", _rate_control_get_name (rc_ctrl),
522           _rate_control_get_name (defval));
523       self->rc.rc_ctrl_mode = defval;
524
525       update_property_uint (base, &self->prop.rc_ctrl, self->rc.rc_ctrl_mode,
526           PROP_RATE_CONTROL);
527     }
528   } else {
529     self->rc.rc_ctrl_mode = VA_RC_NONE;
530   }
531
532   if (self->rc.min_qp > self->rc.max_qp) {
533     GST_INFO_OBJECT (self, "The min_qp %d is bigger than the max_qp %d, "
534         "set it to the max_qp", self->rc.min_qp, self->rc.max_qp);
535     self->rc.min_qp = self->rc.max_qp;
536
537     update_property_uint (base, &self->prop.min_qp, self->rc.min_qp,
538         PROP_MIN_QP);
539   }
540
541   /* Make all the qp in the valid range */
542   if (self->rc.qp_i < self->rc.min_qp) {
543     if (self->rc.qp_i != 26)
544       GST_INFO_OBJECT (self, "The qp_i %d is smaller than the min_qp %d, "
545           "set it to the min_qp", self->rc.qp_i, self->rc.min_qp);
546     self->rc.qp_i = self->rc.min_qp;
547   }
548   if (self->rc.qp_i > self->rc.max_qp) {
549     if (self->rc.qp_i != 26)
550       GST_INFO_OBJECT (self, "The qp_i %d is bigger than the max_qp %d, "
551           "set it to the max_qp", self->rc.qp_i, self->rc.max_qp);
552     self->rc.qp_i = self->rc.max_qp;
553   }
554
555   if (self->rc.qp_p < self->rc.min_qp) {
556     if (self->rc.qp_p != 26)
557       GST_INFO_OBJECT (self, "The qp_p %d is smaller than the min_qp %d, "
558           "set it to the min_qp", self->rc.qp_p, self->rc.min_qp);
559     self->rc.qp_p = self->rc.min_qp;
560   }
561   if (self->rc.qp_p > self->rc.max_qp) {
562     if (self->rc.qp_p != 26)
563       GST_INFO_OBJECT (self, "The qp_p %d is bigger than the max_qp %d, "
564           "set it to the max_qp", self->rc.qp_p, self->rc.max_qp);
565     self->rc.qp_p = self->rc.max_qp;
566   }
567
568   if (self->rc.qp_b < self->rc.min_qp) {
569     if (self->rc.qp_b != 26)
570       GST_INFO_OBJECT (self, "The qp_b %d is smaller than the min_qp %d, "
571           "set it to the min_qp", self->rc.qp_b, self->rc.min_qp);
572     self->rc.qp_b = self->rc.min_qp;
573   }
574   if (self->rc.qp_b > self->rc.max_qp) {
575     if (self->rc.qp_b != 26)
576       GST_INFO_OBJECT (self, "The qp_b %d is bigger than the max_qp %d, "
577           "set it to the max_qp", self->rc.qp_b, self->rc.max_qp);
578     self->rc.qp_b = self->rc.max_qp;
579   }
580
581   GST_OBJECT_LOCK (self);
582   bitrate = self->prop.bitrate;
583   GST_OBJECT_UNLOCK (self);
584
585   /* Calculate a bitrate is not set. */
586   if ((self->rc.rc_ctrl_mode == VA_RC_CBR || self->rc.rc_ctrl_mode == VA_RC_VBR
587           || self->rc.rc_ctrl_mode == VA_RC_VCM) && bitrate == 0) {
588     /* Default compression: 48 bits per macroblock in "high-compression" mode */
589     guint bits_per_mb = 48;
590     guint64 factor;
591
592     /* According to the literature and testing, CABAC entropy coding
593      * mode could provide for +10% to +18% improvement in general,
594      * thus estimating +15% here ; and using adaptive 8x8 transforms
595      * in I-frames could bring up to +10% improvement. */
596     if (!self->use_cabac)
597       bits_per_mb += (bits_per_mb * 15) / 100;
598     if (!self->use_dct8x8)
599       bits_per_mb += (bits_per_mb * 10) / 100;
600
601     factor = (guint64) self->mb_width * self->mb_height * bits_per_mb;
602     bitrate = gst_util_uint64_scale (factor,
603         GST_VIDEO_INFO_FPS_N (&base->input_state->info),
604         GST_VIDEO_INFO_FPS_D (&base->input_state->info)) / 1000;
605     GST_INFO_OBJECT (self, "target bitrate computed to %u kbps", bitrate);
606   }
607
608   /* Adjust the setting based on RC mode. */
609   switch (self->rc.rc_ctrl_mode) {
610     case VA_RC_NONE:
611     case VA_RC_CQP:
612       self->rc.max_bitrate = 0;
613       self->rc.target_bitrate = 0;
614       self->rc.target_percentage = 0;
615       self->rc.cpb_size = 0;
616       break;
617     case VA_RC_CBR:
618       self->rc.max_bitrate = bitrate;
619       self->rc.target_bitrate = bitrate;
620       self->rc.target_percentage = 100;
621       self->rc.qp_i = self->rc.qp_p = self->rc.qp_b = 26;
622       break;
623     case VA_RC_VBR:
624       g_assert (self->rc.target_percentage >= 10);
625       self->rc.max_bitrate = (guint) gst_util_uint64_scale_int (bitrate,
626           100, self->rc.target_percentage);
627       self->rc.target_bitrate = bitrate;
628       self->rc.qp_i = self->rc.qp_p = self->rc.qp_b = 26;
629       break;
630     case VA_RC_VCM:
631       self->rc.max_bitrate = bitrate;
632       self->rc.target_bitrate = bitrate;
633       self->rc.target_percentage = 0;
634       self->rc.qp_i = self->rc.qp_p = self->rc.qp_b = 26;
635       self->rc.cpb_size = 0;
636
637       if (self->gop.num_bframes > 0) {
638         GST_INFO_OBJECT (self, "VCM mode just support I/P mode, no B frame");
639         self->gop.num_bframes = 0;
640         self->gop.b_pyramid = FALSE;
641       }
642       break;
643     default:
644       GST_WARNING_OBJECT (self, "Unsupported rate control");
645       return FALSE;
646       break;
647   }
648
649   GST_DEBUG_OBJECT (self, "Max bitrate: %u bits/sec, "
650       "Target bitrate: %u bits/sec", self->rc.max_bitrate,
651       self->rc.target_bitrate);
652
653   if (self->rc.rc_ctrl_mode != VA_RC_NONE && self->rc.rc_ctrl_mode != VA_RC_CQP)
654     _calculate_bitrate_hrd (self);
655
656   /* update & notifications */
657   update_property_uint (base, &self->prop.bitrate, bitrate, PROP_BITRATE);
658   update_property_uint (base, &self->prop.cpb_size, self->rc.cpb_size,
659       PROP_CPB_SIZE);
660   update_property_uint (base, &self->prop.target_percentage,
661       self->rc.target_percentage, PROP_TARGET_PERCENTAGE);
662   update_property_uint (base, &self->prop.qp_i, self->rc.qp_i, PROP_QP_I);
663   update_property_uint (base, &self->prop.qp_p, self->rc.qp_p, PROP_QP_P);
664   update_property_uint (base, &self->prop.qp_b, self->rc.qp_b, PROP_QP_B);
665
666   return TRUE;
667 }
668
669 static guint
670 _get_h264_cpb_nal_factor (VAProfile profile)
671 {
672   guint f;
673
674   /* Table A-2 */
675   switch (profile) {
676     case VAProfileH264High:
677       f = 1500;
678       break;
679     case VAProfileH264ConstrainedBaseline:
680     case VAProfileH264Main:
681       f = 1200;
682       break;
683     case VAProfileH264MultiviewHigh:
684     case VAProfileH264StereoHigh:
685       f = 1500;                 /* H.10.2.1 (r) */
686       break;
687     default:
688       g_assert_not_reached ();
689       f = 1200;
690       break;
691   }
692   return f;
693 }
694
695 /* Derives the level from the currently set limits */
696 static gboolean
697 _calculate_level (GstVaH264Enc * self)
698 {
699   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
700   const guint cpb_factor = _get_h264_cpb_nal_factor (base->profile);
701   guint i, PicSizeMbs, MaxDpbMbs, MaxMBPS;
702
703   PicSizeMbs = self->mb_width * self->mb_height;
704   MaxDpbMbs = PicSizeMbs * (self->gop.num_ref_frames + 1);
705   MaxMBPS = gst_util_uint64_scale_int_ceil (PicSizeMbs,
706       GST_VIDEO_INFO_FPS_N (&base->input_state->info),
707       GST_VIDEO_INFO_FPS_D (&base->input_state->info));
708
709   for (i = 0; i < G_N_ELEMENTS (_va_h264_level_limits); i++) {
710     const GstVaH264LevelLimits *const limits = &_va_h264_level_limits[i];
711     if (PicSizeMbs <= limits->MaxFS && MaxDpbMbs <= limits->MaxDpbMbs
712         && MaxMBPS <= limits->MaxMBPS && (!self->rc.max_bitrate_bits
713             || self->rc.max_bitrate_bits <= (limits->MaxBR * 1000 * cpb_factor))
714         && (!self->rc.cpb_length_bits
715             || self->rc.cpb_length_bits <=
716             (limits->MaxCPB * 1000 * cpb_factor))) {
717
718       self->level_idc = _va_h264_level_limits[i].level_idc;
719       self->level_str = _va_h264_level_limits[i].name;
720       self->min_cr = _va_h264_level_limits[i].MinCR;
721
722       return TRUE;
723     }
724   }
725
726   GST_ERROR_OBJECT (self,
727       "failed to find a suitable level matching codec config");
728   return FALSE;
729 }
730
731 static void
732 _validate_parameters (GstVaH264Enc * self)
733 {
734   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
735   gint32 max_slices;
736
737   /* Ensure the num_slices provided by the user not exceed the limit
738    * of the number of slices permitted by the stream and by the
739    * hardware. */
740   g_assert (self->num_slices >= 1);
741   max_slices = gst_va_encoder_get_max_slice_num (base->encoder,
742       base->profile, GST_VA_BASE_ENC_ENTRYPOINT (base));
743   if (self->num_slices > max_slices)
744     self->num_slices = max_slices;
745   /* The stream size limit. */
746   if (self->num_slices > ((self->mb_width * self->mb_height + 1) / 2))
747     self->num_slices = ((self->mb_width * self->mb_height + 1) / 2);
748
749   update_property_uint (base, &self->prop.num_slices,
750       self->num_slices, PROP_NUM_SLICES);
751
752   /* Ensure trellis. */
753   if (self->use_trellis &&
754       !gst_va_encoder_has_trellis (base->encoder, base->profile,
755           GST_VA_BASE_ENC_ENTRYPOINT (base))) {
756     GST_INFO_OBJECT (self, "The trellis is not supported");
757     self->use_trellis = FALSE;
758   }
759
760   update_property_bool (base, &self->prop.use_trellis, self->use_trellis,
761       PROP_TRELLIS);
762 }
763
764 /* Get log2_max_frame_num_minus4, log2_max_pic_order_cnt_lsb_minus4
765  * value, shall be in the range of 0 to 12, inclusive. */
766 static guint
767 _get_log2_max_num (guint num)
768 {
769   guint ret = 0;
770
771   while (num) {
772     ++ret;
773     num >>= 1;
774   }
775
776   /* shall be in the range of 0+4 to 12+4, inclusive. */
777   if (ret < 4) {
778     ret = 4;
779   } else if (ret > 16) {
780     ret = 16;
781   }
782   return ret;
783 }
784
785 static void
786 _print_gop_structure (GstVaH264Enc * self)
787 {
788 #ifndef GST_DISABLE_GST_DEBUG
789   GString *str;
790   gint i;
791
792   if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) < GST_LEVEL_INFO)
793     return;
794
795   str = g_string_new (NULL);
796
797   g_string_append_printf (str, "[ ");
798
799   for (i = 0; i < self->gop.idr_period; i++) {
800     if (i == 0) {
801       g_string_append_printf (str, "IDR");
802       continue;
803     } else {
804       g_string_append_printf (str, ", ");
805     }
806
807     g_string_append_printf (str, "%s",
808         _slice_type_name (self->gop.frame_types[i].slice_type));
809
810     if (self->gop.b_pyramid
811         && self->gop.frame_types[i].slice_type == GST_H264_B_SLICE) {
812       g_string_append_printf (str, "<L%d (%d, %d)>",
813           self->gop.frame_types[i].pyramid_level,
814           self->gop.frame_types[i].left_ref_poc_diff,
815           self->gop.frame_types[i].right_ref_poc_diff);
816     }
817
818     if (self->gop.frame_types[i].is_ref) {
819       g_string_append_printf (str, "(ref)");
820     }
821
822   }
823
824   g_string_append_printf (str, " ]");
825
826   GST_INFO_OBJECT (self, "GOP size: %d, forward reference %d, backward"
827       " reference %d, GOP structure: %s", self->gop.idr_period,
828       self->gop.ref_num_list0, self->gop.ref_num_list1, str->str);
829
830   g_string_free (str, TRUE);
831 #endif
832 }
833
834 struct PyramidInfo
835 {
836   guint level;
837   gint left_ref_poc_diff;
838   gint right_ref_poc_diff;
839 };
840
841 static void
842 _set_pyramid_info (struct PyramidInfo *info, guint len,
843     guint current_level, guint highest_level)
844 {
845   guint index;
846
847   g_assert (len >= 1);
848
849   if (current_level == highest_level || len == 1) {
850     for (index = 0; index < len; index++) {
851       info[index].level = current_level;
852       info[index].left_ref_poc_diff = (index + 1) * -2;
853       info[index].right_ref_poc_diff = (len - index) * 2;
854     }
855
856     return;
857   }
858
859   index = len / 2;
860   info[index].level = current_level;
861   info[index].left_ref_poc_diff = (index + 1) * -2;
862   info[index].right_ref_poc_diff = (len - index) * 2;
863
864   current_level++;
865
866   if (index > 0)
867     _set_pyramid_info (info, index, current_level, highest_level);
868
869   if (index + 1 < len)
870     _set_pyramid_info (&info[index + 1], len - (index + 1),
871         current_level, highest_level);
872 }
873
874 static void
875 _create_gop_frame_types (GstVaH264Enc * self)
876 {
877   guint i;
878   guint i_frames = self->gop.num_iframes;
879   struct PyramidInfo pyramid_info[31] = { 0, };
880
881   if (self->gop.highest_pyramid_level > 0) {
882     g_assert (self->gop.num_bframes > 0);
883     _set_pyramid_info (pyramid_info, self->gop.num_bframes,
884         0, self->gop.highest_pyramid_level);
885   }
886
887   g_assert (self->gop.idr_period <= MAX_GOP_SIZE);
888   for (i = 0; i < self->gop.idr_period; i++) {
889     if (i == 0) {
890       self->gop.frame_types[i].slice_type = GST_H264_I_SLICE;
891       self->gop.frame_types[i].is_ref = TRUE;
892       continue;
893     }
894
895     /* Intra only stream. */
896     if (self->gop.ip_period == 0) {
897       self->gop.frame_types[i].slice_type = GST_H264_I_SLICE;
898       self->gop.frame_types[i].is_ref = FALSE;
899       continue;
900     }
901
902     if (i % self->gop.ip_period) {
903       guint pyramid_index =
904           i % self->gop.ip_period - 1 /* The first P or IDR */ ;
905
906       self->gop.frame_types[i].slice_type = GST_H264_B_SLICE;
907       self->gop.frame_types[i].pyramid_level =
908           pyramid_info[pyramid_index].level;
909       self->gop.frame_types[i].is_ref =
910           (self->gop.frame_types[i].pyramid_level <
911           self->gop.highest_pyramid_level);
912       self->gop.frame_types[i].left_ref_poc_diff =
913           pyramid_info[pyramid_index].left_ref_poc_diff;
914       self->gop.frame_types[i].right_ref_poc_diff =
915           pyramid_info[pyramid_index].right_ref_poc_diff;
916       continue;
917     }
918
919     if (self->gop.i_period && i % self->gop.i_period == 0 && i_frames > 0) {
920       /* Replace P with I. */
921       self->gop.frame_types[i].slice_type = GST_H264_I_SLICE;
922       self->gop.frame_types[i].is_ref = TRUE;
923       i_frames--;
924       continue;
925     }
926
927     self->gop.frame_types[i].slice_type = GST_H264_P_SLICE;
928     self->gop.frame_types[i].is_ref = TRUE;
929   }
930
931   /* Force the last one to be a P */
932   if (self->gop.idr_period > 1 && self->gop.ip_period > 0) {
933     self->gop.frame_types[self->gop.idr_period - 1].slice_type =
934         GST_H264_P_SLICE;
935     self->gop.frame_types[self->gop.idr_period - 1].is_ref = TRUE;
936   }
937 }
938
939 /* Consider the idr_period, num_bframes, L0/L1 reference number.
940  * TODO: Load some preset fixed GOP structure.
941  * TODO: Skip this if in lookahead mode. */
942 static void
943 _generate_gop_structure (GstVaH264Enc * self)
944 {
945   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
946   guint32 list0, list1, gop_ref_num;
947   gint32 p_frames;
948
949   /* If not set, generate a idr every second */
950   if (self->gop.idr_period == 0) {
951     self->gop.idr_period = (GST_VIDEO_INFO_FPS_N (&base->input_state->info)
952         + GST_VIDEO_INFO_FPS_D (&base->input_state->info) - 1) /
953         GST_VIDEO_INFO_FPS_D (&base->input_state->info);
954   }
955
956   /* Do not use a too huge GOP size. */
957   if (self->gop.idr_period > 1024) {
958     self->gop.idr_period = 1024;
959     GST_INFO_OBJECT (self, "Lowering the GOP size to %d", self->gop.idr_period);
960   }
961
962   update_property_uint (base, &self->prop.key_int_max, self->gop.idr_period,
963       PROP_KEY_INT_MAX);
964
965   /* Prefer have more than 1 refs for the GOP which is not very small. */
966   if (self->gop.idr_period > 8) {
967     if (self->gop.num_bframes > (self->gop.idr_period - 1) / 2) {
968       self->gop.num_bframes = (self->gop.idr_period - 1) / 2;
969       GST_INFO_OBJECT (self, "Lowering the number of num_bframes to %d",
970           self->gop.num_bframes);
971     }
972   } else {
973     /* beign and end should be ref */
974     if (self->gop.num_bframes > self->gop.idr_period - 1 - 1) {
975       if (self->gop.idr_period > 1) {
976         self->gop.num_bframes = self->gop.idr_period - 1 - 1;
977       } else {
978         self->gop.num_bframes = 0;
979       }
980       GST_INFO_OBJECT (self, "Lowering the number of num_bframes to %d",
981           self->gop.num_bframes);
982     }
983   }
984
985   if (!gst_va_encoder_get_max_num_reference (base->encoder, base->profile,
986           GST_VA_BASE_ENC_ENTRYPOINT (base), &list0, &list1)) {
987     GST_INFO_OBJECT (self, "Failed to get the max num reference");
988     list0 = 1;
989     list1 = 0;
990   }
991
992   if (list0 > self->gop.num_ref_frames)
993     list0 = self->gop.num_ref_frames;
994   if (list1 > self->gop.num_ref_frames)
995     list1 = self->gop.num_ref_frames;
996
997   if (list0 == 0) {
998     GST_INFO_OBJECT (self,
999         "No reference support, fallback to intra only stream");
1000
1001     /* It does not make sense that if only the list1 exists. */
1002     self->gop.num_ref_frames = 0;
1003
1004     self->gop.ip_period = 0;
1005     self->gop.num_bframes = 0;
1006     self->gop.b_pyramid = FALSE;
1007     self->gop.highest_pyramid_level = 0;
1008     self->gop.num_iframes = self->gop.idr_period - 1 /* The idr */ ;
1009     self->gop.ref_num_list0 = 0;
1010     self->gop.ref_num_list1 = 0;
1011     goto create_poc;
1012   }
1013
1014   if (self->gop.num_ref_frames <= 1) {
1015     GST_INFO_OBJECT (self, "The number of reference frames is only %d,"
1016         " no B frame allowed, fallback to I/P mode", self->gop.num_ref_frames);
1017     self->gop.num_bframes = 0;
1018     list1 = 0;
1019   }
1020
1021   /* b_pyramid needs at least 1 ref for B, besides the I/P */
1022   if (self->gop.b_pyramid && self->gop.num_ref_frames <= 2) {
1023     GST_INFO_OBJECT (self, "The number of reference frames is only %d,"
1024         " not enough for b_pyramid", self->gop.num_ref_frames);
1025     self->gop.b_pyramid = FALSE;
1026   }
1027
1028   if (list1 == 0 && self->gop.num_bframes > 0) {
1029     GST_INFO_OBJECT (self,
1030         "No hw reference support for list 1, fallback to I/P mode");
1031     self->gop.num_bframes = 0;
1032     self->gop.b_pyramid = FALSE;
1033   }
1034
1035   /* I/P mode, no list1 needed. */
1036   if (self->gop.num_bframes == 0)
1037     list1 = 0;
1038
1039   /* Not enough B frame, no need for b_pyramid. */
1040   if (self->gop.num_bframes <= 1)
1041     self->gop.b_pyramid = FALSE;
1042
1043   /* b pyramid has only one backward ref. */
1044   if (self->gop.b_pyramid)
1045     list1 = 1;
1046
1047   if (self->gop.num_ref_frames > list0 + list1) {
1048     self->gop.num_ref_frames = list0 + list1;
1049     GST_INFO_OBJECT (self, "HW limits, lowering the number of reference"
1050         " frames to %d", self->gop.num_ref_frames);
1051   }
1052
1053   /* How many possible refs within a GOP. */
1054   gop_ref_num = (self->gop.idr_period + self->gop.num_bframes) /
1055       (self->gop.num_bframes + 1);
1056   /* The end ref */
1057   if (self->gop.num_bframes > 0
1058       /* frame_num % (self->gop.num_bframes + 1) happens to be the end P */
1059       && (self->gop.idr_period % (self->gop.num_bframes + 1) != 1))
1060     gop_ref_num++;
1061
1062   /* Adjust reference num based on B frames and B pyramid. */
1063   if (self->gop.num_bframes == 0) {
1064     self->gop.b_pyramid = FALSE;
1065     self->gop.ref_num_list0 = self->gop.num_ref_frames;
1066     self->gop.ref_num_list1 = 0;
1067   } else if (self->gop.b_pyramid) {
1068     guint b_frames = self->gop.num_bframes;
1069     guint b_refs;
1070
1071     /* b pyramid has only one backward ref. */
1072     g_assert (list1 == 1);
1073     self->gop.ref_num_list1 = list1;
1074     self->gop.ref_num_list0 =
1075         self->gop.num_ref_frames - self->gop.ref_num_list1;
1076
1077     b_frames = b_frames / 2;
1078     b_refs = 0;
1079     while (b_frames) {
1080       /* At least 1 B ref for each level, plus begin and end 2 P/I */
1081       b_refs += 1;
1082       if (b_refs + 2 > self->gop.num_ref_frames)
1083         break;
1084
1085       self->gop.highest_pyramid_level++;
1086       b_frames = b_frames / 2;
1087     }
1088
1089     GST_INFO_OBJECT (self, "pyramid level is %d",
1090         self->gop.highest_pyramid_level);
1091   } else {
1092     /* We prefer list0. Backward refs have more latency. */
1093     self->gop.ref_num_list1 = 1;
1094     self->gop.ref_num_list0 =
1095         self->gop.num_ref_frames - self->gop.ref_num_list1;
1096     /* Balance the forward and backward refs, but not cause a big latency. */
1097     while ((self->gop.num_bframes * self->gop.ref_num_list1 <= 16)
1098         && (self->gop.ref_num_list1 <= gop_ref_num)
1099         && (self->gop.ref_num_list1 < list1)
1100         && (self->gop.ref_num_list0 / self->gop.ref_num_list1 > 4)) {
1101       self->gop.ref_num_list0--;
1102       self->gop.ref_num_list1++;
1103     }
1104
1105     if (self->gop.ref_num_list0 > list0)
1106       self->gop.ref_num_list0 = list0;
1107   }
1108
1109   /* It's OK, keep slots for GST_VIDEO_CODEC_FRAME_IS_FORCE_KEYFRAME frame. */
1110   if (self->gop.ref_num_list0 > gop_ref_num)
1111     GST_DEBUG_OBJECT (self, "num_ref_frames %d is bigger than gop_ref_num %d",
1112         self->gop.ref_num_list0, gop_ref_num);
1113
1114   /* Include the ref picture itself. */
1115   self->gop.ip_period = 1 + self->gop.num_bframes;
1116
1117   p_frames = gop_ref_num - 1 /* IDR */ ;
1118   if (p_frames < 0)
1119     p_frames = 0;
1120   if (self->gop.num_iframes > p_frames) {
1121     self->gop.num_iframes = p_frames;
1122     GST_INFO_OBJECT (self, "Too many I frames insertion, lowering it to %d",
1123         self->gop.num_iframes);
1124   }
1125
1126   if (self->gop.num_iframes > 0) {
1127     guint total_i_frames = self->gop.num_iframes + 1 /* IDR */ ;
1128     self->gop.i_period =
1129         (gop_ref_num / total_i_frames) * (self->gop.num_bframes + 1);
1130   }
1131
1132 create_poc:
1133   /* init max_frame_num, max_poc */
1134   self->gop.log2_max_frame_num = _get_log2_max_num (self->gop.idr_period);
1135   self->gop.max_frame_num = (1 << self->gop.log2_max_frame_num);
1136   self->gop.log2_max_pic_order_cnt = self->gop.log2_max_frame_num + 1;
1137   self->gop.max_pic_order_cnt = (1 << self->gop.log2_max_pic_order_cnt);
1138   self->gop.num_reorder_frames = self->gop.b_pyramid ?
1139       self->gop.highest_pyramid_level * 2 + 1 /* the last P frame. */ :
1140       self->gop.ref_num_list1;
1141   /* Should not exceed the max ref num. */
1142   self->gop.num_reorder_frames =
1143       MIN (self->gop.num_reorder_frames, self->gop.num_ref_frames);
1144   self->gop.num_reorder_frames = MIN (self->gop.num_reorder_frames, 16);
1145
1146   _create_gop_frame_types (self);
1147   _print_gop_structure (self);
1148
1149   /* updates & notifications */
1150   update_property_uint (base, &self->prop.num_ref_frames,
1151       self->gop.num_ref_frames, PROP_NUM_REF_FRAMES);
1152   update_property_uint (base, &self->prop.num_iframes, self->gop.num_iframes,
1153       PROP_IFRAMES);
1154 }
1155
1156 static void
1157 _calculate_coded_size (GstVaH264Enc * self)
1158 {
1159   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
1160   guint codedbuf_size = 0;
1161
1162   if (base->profile == VAProfileH264High
1163       || base->profile == VAProfileH264MultiviewHigh
1164       || base->profile == VAProfileH264StereoHigh) {
1165     /* The number of bits of macroblock_layer( ) data for any macroblock
1166        is not greater than 128 + RawMbBits */
1167     guint RawMbBits = 0;
1168     guint BitDepthY = 8;
1169     guint BitDepthC = 8;
1170     guint MbWidthC = 8;
1171     guint MbHeightC = 8;
1172
1173     switch (base->rt_format) {
1174       case VA_RT_FORMAT_YUV420:
1175         BitDepthY = 8;
1176         BitDepthC = 8;
1177         MbWidthC = 8;
1178         MbHeightC = 8;
1179         break;
1180       case VA_RT_FORMAT_YUV422:
1181         BitDepthY = 8;
1182         BitDepthC = 8;
1183         MbWidthC = 8;
1184         MbHeightC = 16;
1185         break;
1186       case VA_RT_FORMAT_YUV444:
1187         BitDepthY = 8;
1188         BitDepthC = 8;
1189         MbWidthC = 16;
1190         MbHeightC = 16;
1191         break;
1192       case VA_RT_FORMAT_YUV400:
1193         BitDepthY = 8;
1194         BitDepthC = 0;
1195         MbWidthC = 0;
1196         MbHeightC = 0;
1197         break;
1198       case VA_RT_FORMAT_YUV420_10:
1199         BitDepthY = 10;
1200         BitDepthC = 10;
1201         MbWidthC = 8;
1202         MbHeightC = 8;
1203         break;
1204       case VA_RT_FORMAT_YUV422_10:
1205         BitDepthY = 10;
1206         BitDepthC = 10;
1207         MbWidthC = 8;
1208         MbHeightC = 16;
1209         break;
1210       case VA_RT_FORMAT_YUV444_10:
1211         BitDepthY = 10;
1212         BitDepthC = 10;
1213         MbWidthC = 16;
1214         MbHeightC = 16;
1215         break;
1216       default:
1217         g_assert_not_reached ();
1218         break;
1219     }
1220
1221     /* The variable RawMbBits is derived as
1222      * RawMbBits = 256 * BitDepthY + 2 * MbWidthC * MbHeightC * BitDepthC */
1223     RawMbBits = 256 * BitDepthY + 2 * MbWidthC * MbHeightC * BitDepthC;
1224     codedbuf_size = (self->mb_width * self->mb_height) * (128 + RawMbBits) / 8;
1225   } else {
1226     /* The number of bits of macroblock_layer( ) data for any macroblock
1227      * is not greater than 3200 */
1228     codedbuf_size = (self->mb_width * self->mb_height) * (3200 / 8);
1229   }
1230
1231   /* Account for SPS header */
1232   /* XXX: exclude scaling lists, MVC/SVC extensions */
1233   codedbuf_size += 4 /* start code */  + GST_ROUND_UP_8 (MAX_SPS_HDR_SIZE +
1234       MAX_VUI_PARAMS_SIZE + 2 * MAX_HRD_PARAMS_SIZE) / 8;
1235
1236   /* Account for PPS header */
1237   /* XXX: exclude slice groups, scaling lists, MVC/SVC extensions */
1238   codedbuf_size += 4 + GST_ROUND_UP_8 (MAX_PPS_HDR_SIZE) / 8;
1239
1240   /* Account for slice header */
1241   codedbuf_size +=
1242       self->num_slices * (4 + GST_ROUND_UP_8 (MAX_SLICE_HDR_SIZE) / 8);
1243
1244   /* Add 5% for safety */
1245   base->codedbuf_size = (guint) ((gfloat) codedbuf_size * 1.05);
1246
1247   GST_DEBUG_OBJECT (self, "Calculate codedbuf size: %u", base->codedbuf_size);
1248 }
1249
1250 static guint
1251 _get_rtformat (GstVaH264Enc * self, GstVideoFormat format)
1252 {
1253   guint chroma;
1254
1255   chroma = gst_va_chroma_from_video_format (format);
1256
1257   /* Check whether the rtformat is supported. */
1258   if (chroma != VA_RT_FORMAT_YUV420) {
1259     GST_ERROR_OBJECT (self, "Unsupported chroma for video format: %s",
1260         gst_video_format_to_string (format));
1261     return 0;
1262   }
1263
1264   return chroma;
1265 }
1266
1267 static gboolean
1268 _init_packed_headers (GstVaH264Enc * self)
1269 {
1270   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
1271   guint32 packed_headers;
1272   guint32 desired_packed_headers = VA_ENC_PACKED_HEADER_SEQUENCE        /* SPS */
1273       | VA_ENC_PACKED_HEADER_PICTURE    /* PPS */
1274       | VA_ENC_PACKED_HEADER_SLICE      /* Slice headers */
1275       | VA_ENC_PACKED_HEADER_RAW_DATA;  /* SEI, AUD, etc. */
1276
1277   self->packed_headers = 0;
1278
1279   if (!gst_va_encoder_get_packed_headers (base->encoder, base->profile,
1280           GST_VA_BASE_ENC_ENTRYPOINT (base), &packed_headers))
1281     return FALSE;
1282
1283   if (desired_packed_headers & ~packed_headers) {
1284     GST_INFO_OBJECT (self, "Driver does not support some wanted packed headers "
1285         "(wanted %#x, found %#x)", desired_packed_headers, packed_headers);
1286   }
1287
1288   self->packed_headers = desired_packed_headers & packed_headers;
1289
1290   return TRUE;
1291 }
1292
1293
1294 static gboolean
1295 _decide_profile (GstVaH264Enc * self, VAProfile * _profile, guint * _rt_format)
1296 {
1297   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
1298   gboolean ret = FALSE;
1299   GstVideoFormat in_format;
1300   VAProfile profile;
1301   guint rt_format;
1302   GstCaps *allowed_caps = NULL;
1303   guint num_structures, i;
1304   GstStructure *structure;
1305   const GValue *v_profile;
1306   GPtrArray *candidates = NULL;
1307   gchar *profile_name;
1308
1309   candidates = g_ptr_array_new_with_free_func (g_free);
1310
1311   /* First, check whether the downstream requires a specified profile. */
1312   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (base));
1313   if (!allowed_caps)
1314     allowed_caps = gst_pad_query_caps (GST_VIDEO_ENCODER_SRC_PAD (base), NULL);
1315
1316   if (allowed_caps && !gst_caps_is_empty (allowed_caps)) {
1317     num_structures = gst_caps_get_size (allowed_caps);
1318     for (i = 0; i < num_structures; i++) {
1319       structure = gst_caps_get_structure (allowed_caps, i);
1320       v_profile = gst_structure_get_value (structure, "profile");
1321       if (!v_profile)
1322         continue;
1323
1324       if (G_VALUE_HOLDS_STRING (v_profile)) {
1325         profile_name = g_strdup (g_value_get_string (v_profile));
1326         g_ptr_array_add (candidates, profile_name);
1327       } else if (GST_VALUE_HOLDS_LIST (v_profile)) {
1328         guint j;
1329
1330         for (j = 0; j < gst_value_list_get_size (v_profile); j++) {
1331           const GValue *p = gst_value_list_get_value (v_profile, j);
1332           if (!p)
1333             continue;
1334
1335           profile_name = g_strdup (g_value_get_string (p));
1336           g_ptr_array_add (candidates, profile_name);
1337         }
1338       }
1339     }
1340   }
1341
1342   if (candidates->len == 0) {
1343     GST_ERROR_OBJECT (self, "No available profile in caps");
1344     ret = FALSE;
1345     goto out;
1346   }
1347
1348   in_format = GST_VIDEO_INFO_FORMAT (&base->input_state->info);
1349   rt_format = _get_rtformat (self, in_format);
1350   if (!rt_format) {
1351     GST_ERROR_OBJECT (self, "unsupported video format %s",
1352         gst_video_format_to_string (in_format));
1353     ret = FALSE;
1354     goto out;
1355   }
1356
1357   /* Find the suitable profile by features and check the HW
1358    * support. */
1359   ret = FALSE;
1360   for (i = 0; i < candidates->len; i++) {
1361     profile_name = g_ptr_array_index (candidates, i);
1362
1363     /* dct8x8 require at least high profile. */
1364     if (self->use_dct8x8) {
1365       if (!g_strstr_len (profile_name, -1, "high"))
1366         continue;
1367     }
1368
1369     /* cabac require at least main profile. */
1370     if (self->use_cabac) {
1371       if (!g_strstr_len (profile_name, -1, "main")
1372           && !g_strstr_len (profile_name, -1, "high"))
1373         continue;
1374     }
1375
1376     /* baseline only support I/P mode. */
1377     if (self->gop.num_bframes > 0) {
1378       if (g_strstr_len (profile_name, -1, "baseline"))
1379         continue;
1380     }
1381
1382     profile = gst_va_profile_from_name (H264, profile_name);
1383     if (profile == VAProfileNone)
1384       continue;
1385
1386     if (!gst_va_encoder_has_profile (base->encoder, profile))
1387       continue;
1388
1389     if ((rt_format & gst_va_encoder_get_rtformat (base->encoder,
1390                 profile, GST_VA_BASE_ENC_ENTRYPOINT (base))) == 0)
1391       continue;
1392
1393     *_profile = profile;
1394     *_rt_format = rt_format;
1395     ret = TRUE;
1396     goto out;
1397   }
1398
1399   /* Just use the first HW available profile and disable features if
1400    * needed. */
1401   profile_name = NULL;
1402   for (i = 0; i < candidates->len; i++) {
1403     profile_name = g_ptr_array_index (candidates, i);
1404     profile = gst_va_profile_from_name (H264, profile_name);
1405     if (profile == VAProfileNone)
1406       continue;
1407
1408     if (!gst_va_encoder_has_profile (base->encoder, profile))
1409       continue;
1410
1411     if ((rt_format & gst_va_encoder_get_rtformat (base->encoder,
1412                 profile, GST_VA_BASE_ENC_ENTRYPOINT (base))) == 0)
1413       continue;
1414
1415     *_profile = profile;
1416     *_rt_format = rt_format;
1417     ret = TRUE;
1418   }
1419
1420   if (ret == FALSE)
1421     goto out;
1422
1423   if (self->use_dct8x8 && !g_strstr_len (profile_name, -1, "high")) {
1424     GST_INFO_OBJECT (self, "Disable dct8x8, profile %s does not support it",
1425         gst_va_profile_name (profile));
1426     self->use_dct8x8 = FALSE;
1427     update_property_bool (base, &self->prop.use_dct8x8, self->use_dct8x8,
1428         PROP_DCT8X8);
1429   }
1430
1431   if (self->use_cabac && (!g_strstr_len (profile_name, -1, "main")
1432           && !g_strstr_len (profile_name, -1, "high"))) {
1433     GST_INFO_OBJECT (self, "Disable cabac, profile %s does not support it",
1434         gst_va_profile_name (profile));
1435     self->use_cabac = FALSE;
1436     update_property_bool (base, &self->prop.use_cabac, self->use_cabac,
1437         PROP_CABAC);
1438   }
1439
1440   if (self->gop.num_bframes > 0 && g_strstr_len (profile_name, -1, "baseline")) {
1441     GST_INFO_OBJECT (self, "No B frames, profile %s does not support it",
1442         gst_va_profile_name (profile));
1443     self->gop.num_bframes = 0;
1444     self->gop.b_pyramid = 0;
1445   }
1446
1447 out:
1448   g_clear_pointer (&candidates, g_ptr_array_unref);
1449   g_clear_pointer (&allowed_caps, gst_caps_unref);
1450
1451   if (ret) {
1452     GST_INFO_OBJECT (self, "Select the profile %s",
1453         gst_va_profile_name (profile));
1454   } else {
1455     GST_ERROR_OBJECT (self, "Failed to find an available profile");
1456   }
1457
1458   return ret;
1459 }
1460
1461 /* Clear all the info of last reconfig and set the fields based on
1462  * property. The reconfig may change these fields because of the
1463  * profile/level and HW limitation. */
1464 static void
1465 gst_va_h264_enc_reset_state (GstVaBaseEnc * base)
1466 {
1467   GstVaH264Enc *self = GST_VA_H264_ENC (base);
1468
1469   GST_VA_BASE_ENC_CLASS (parent_class)->reset_state (base);
1470
1471   GST_OBJECT_LOCK (self);
1472   self->use_cabac = self->prop.use_cabac;
1473   self->use_dct8x8 = self->prop.use_dct8x8;
1474   self->use_trellis = self->prop.use_trellis;
1475   self->aud = self->prop.aud;
1476   self->cc = self->prop.cc;
1477   self->num_slices = self->prop.num_slices;
1478
1479   self->gop.idr_period = self->prop.key_int_max;
1480   self->gop.num_bframes = self->prop.num_bframes;
1481   self->gop.b_pyramid = self->prop.b_pyramid;
1482   self->gop.num_iframes = self->prop.num_iframes;
1483   self->gop.num_ref_frames = self->prop.num_ref_frames;
1484
1485   self->rc.rc_ctrl_mode = self->prop.rc_ctrl;
1486   self->rc.min_qp = self->prop.min_qp;
1487   self->rc.max_qp = self->prop.max_qp;
1488   self->rc.qp_i = self->prop.qp_i;
1489   self->rc.qp_p = self->prop.qp_p;
1490   self->rc.qp_b = self->prop.qp_b;
1491   self->rc.mbbrc = self->prop.mbbrc;
1492
1493   self->rc.target_percentage = self->prop.target_percentage;
1494   self->rc.target_usage = self->prop.target_usage;
1495   self->rc.cpb_size = self->prop.cpb_size;
1496   GST_OBJECT_UNLOCK (self);
1497
1498   self->level_idc = 0;
1499   self->level_str = NULL;
1500   self->mb_width = 0;
1501   self->mb_height = 0;
1502
1503   self->gop.i_period = 0;
1504   self->gop.total_idr_count = 0;
1505   self->gop.ip_period = 0;
1506   self->gop.highest_pyramid_level = 0;
1507   memset (self->gop.frame_types, 0, sizeof (self->gop.frame_types));
1508   self->gop.cur_frame_index = 0;
1509   self->gop.cur_frame_num = 0;
1510   self->gop.max_frame_num = 0;
1511   self->gop.log2_max_frame_num = 0;
1512   self->gop.max_pic_order_cnt = 0;
1513   self->gop.log2_max_pic_order_cnt = 0;
1514   self->gop.ref_num_list0 = 0;
1515   self->gop.ref_num_list1 = 0;
1516   self->gop.num_reorder_frames = 0;
1517
1518   self->rc.max_bitrate = 0;
1519   self->rc.target_bitrate = 0;
1520   self->rc.max_bitrate_bits = 0;
1521   self->rc.target_bitrate_bits = 0;
1522   self->rc.cpb_length_bits = 0;
1523
1524   memset (&self->sequence_hdr, 0, sizeof (GstH264SPS));
1525 }
1526
1527 static gboolean
1528 gst_va_h264_enc_reconfig (GstVaBaseEnc * base)
1529 {
1530   GstVideoEncoder *venc = GST_VIDEO_ENCODER (base);
1531   GstVaH264Enc *self = GST_VA_H264_ENC (base);
1532   GstCaps *out_caps, *reconf_caps = NULL;
1533   GstVideoCodecState *output_state = NULL;
1534   GstVideoFormat format, reconf_format = GST_VIDEO_FORMAT_UNKNOWN;
1535   VAProfile profile = VAProfileNone;
1536   gboolean do_renegotiation = TRUE, do_reopen, need_negotiation;
1537   guint max_ref_frames, max_surfaces = 0, rt_format = 0, codedbuf_size;
1538   gint width, height;
1539
1540   width = GST_VIDEO_INFO_WIDTH (&base->input_state->info);
1541   height = GST_VIDEO_INFO_HEIGHT (&base->input_state->info);
1542   format = GST_VIDEO_INFO_FORMAT (&base->input_state->info);
1543   codedbuf_size = base->codedbuf_size;
1544
1545   need_negotiation =
1546       !gst_va_encoder_get_reconstruct_pool_config (base->encoder, &reconf_caps,
1547       &max_surfaces);
1548   if (!need_negotiation && reconf_caps) {
1549     GstVideoInfo vi;
1550     if (!gst_video_info_from_caps (&vi, reconf_caps))
1551       return FALSE;
1552     reconf_format = GST_VIDEO_INFO_FORMAT (&vi);
1553   }
1554
1555   if (!_decide_profile (self, &profile, &rt_format))
1556     return FALSE;
1557
1558   /* first check */
1559   do_reopen = !(base->profile == profile && base->rt_format == rt_format
1560       && format == reconf_format && width == base->width
1561       && height == base->height && self->prop.rc_ctrl == self->rc.rc_ctrl_mode);
1562
1563   if (do_reopen && gst_va_encoder_is_open (base->encoder))
1564     gst_va_encoder_close (base->encoder);
1565
1566   gst_va_base_enc_reset_state (base);
1567
1568   base->profile = profile;
1569   base->rt_format = rt_format;
1570   base->width = width;
1571   base->height = height;
1572
1573   self->mb_width = GST_ROUND_UP_16 (base->width) / 16;
1574   self->mb_height = GST_ROUND_UP_16 (base->height) / 16;
1575
1576   /* Frame rate is needed for rate control and PTS setting. */
1577   if (GST_VIDEO_INFO_FPS_N (&base->input_state->info) == 0
1578       || GST_VIDEO_INFO_FPS_D (&base->input_state->info) == 0) {
1579     GST_INFO_OBJECT (self, "Unknown framerate, just set to 30 fps");
1580     GST_VIDEO_INFO_FPS_N (&base->input_state->info) = 30;
1581     GST_VIDEO_INFO_FPS_D (&base->input_state->info) = 1;
1582   }
1583   base->frame_duration = gst_util_uint64_scale (GST_SECOND,
1584       GST_VIDEO_INFO_FPS_D (&base->input_state->info),
1585       GST_VIDEO_INFO_FPS_N (&base->input_state->info));
1586
1587   GST_DEBUG_OBJECT (self, "resolution:%dx%d, MB size: %dx%d,"
1588       " frame duration is %" GST_TIME_FORMAT,
1589       base->width, base->height, self->mb_width, self->mb_height,
1590       GST_TIME_ARGS (base->frame_duration));
1591
1592   _validate_parameters (self);
1593
1594   if (!_ensure_rate_control (self))
1595     return FALSE;
1596
1597   if (!_calculate_level (self))
1598     return FALSE;
1599
1600   _generate_gop_structure (self);
1601
1602   _calculate_coded_size (self);
1603
1604   /* updates & notifications */
1605   /* num_bframes are modified several times before */
1606   update_property_uint (base, &self->prop.num_bframes, self->gop.num_bframes,
1607       PROP_BFRAMES);
1608   update_property_bool (base, &self->prop.b_pyramid, self->gop.b_pyramid,
1609       PROP_B_PYRAMID);
1610
1611   if (!_init_packed_headers (self))
1612     return FALSE;
1613
1614   self->aud = self->aud && self->packed_headers & VA_ENC_PACKED_HEADER_RAW_DATA;
1615   update_property_bool (base, &self->prop.aud, self->aud, PROP_AUD);
1616
1617   self->cc = self->cc && self->packed_headers & VA_ENC_PACKED_HEADER_RAW_DATA;
1618   update_property_bool (base, &self->prop.cc, self->cc, PROP_CC);
1619
1620   max_ref_frames = self->gop.num_ref_frames + 3 /* scratch frames */ ;
1621
1622   /* second check after calculations */
1623   do_reopen |=
1624       !(max_ref_frames == max_surfaces && codedbuf_size == base->codedbuf_size);
1625   if (do_reopen && gst_va_encoder_is_open (base->encoder))
1626     gst_va_encoder_close (base->encoder);
1627
1628   if (!gst_va_encoder_is_open (base->encoder)
1629       && !gst_va_encoder_open (base->encoder, base->profile,
1630           format, base->rt_format, base->width, base->height,
1631           base->codedbuf_size, max_ref_frames, self->rc.rc_ctrl_mode,
1632           self->packed_headers)) {
1633     GST_ERROR_OBJECT (self, "Failed to open the VA encoder.");
1634     return FALSE;
1635   }
1636
1637   /* Add some tags */
1638   gst_va_base_enc_add_codec_tag (base, "H264");
1639
1640   out_caps = gst_va_profile_caps (base->profile);
1641   g_assert (out_caps);
1642   out_caps = gst_caps_fixate (out_caps);
1643
1644   if (self->level_str)
1645     gst_caps_set_simple (out_caps, "level", G_TYPE_STRING, self->level_str,
1646         NULL);
1647
1648   gst_caps_set_simple (out_caps, "width", G_TYPE_INT, base->width,
1649       "height", G_TYPE_INT, base->height, "alignment", G_TYPE_STRING, "au",
1650       "stream-format", G_TYPE_STRING, "byte-stream", NULL);
1651
1652   if (!need_negotiation) {
1653     output_state = gst_video_encoder_get_output_state (venc);
1654     do_renegotiation = TRUE;
1655     if (output_state) {
1656       do_renegotiation = !gst_caps_is_subset (output_state->caps, out_caps);
1657       gst_video_codec_state_unref (output_state);
1658     }
1659     if (!do_renegotiation) {
1660       gst_caps_unref (out_caps);
1661       return TRUE;
1662     }
1663   }
1664
1665   GST_DEBUG_OBJECT (self, "output caps is %" GST_PTR_FORMAT, out_caps);
1666
1667   output_state =
1668       gst_video_encoder_set_output_state (venc, out_caps, base->input_state);
1669   gst_video_codec_state_unref (output_state);
1670
1671   if (!gst_video_encoder_negotiate (venc)) {
1672     GST_ERROR_OBJECT (self, "Failed to negotiate with the downstream");
1673     return FALSE;
1674   }
1675
1676   return TRUE;
1677 }
1678
1679 static gboolean
1680 _push_one_frame (GstVaBaseEnc * base, GstVideoCodecFrame * gst_frame,
1681     gboolean last)
1682 {
1683   GstVaH264Enc *self = GST_VA_H264_ENC (base);
1684   GstVaH264EncFrame *frame;
1685
1686   g_return_val_if_fail (self->gop.cur_frame_index <= self->gop.idr_period,
1687       FALSE);
1688
1689   if (gst_frame) {
1690     /* Begin a new GOP, should have a empty reorder_list. */
1691     if (self->gop.cur_frame_index == self->gop.idr_period) {
1692       g_assert (g_queue_is_empty (&base->reorder_list));
1693       self->gop.cur_frame_index = 0;
1694       self->gop.cur_frame_num = 0;
1695     }
1696
1697     frame = _enc_frame (gst_frame);
1698     frame->poc =
1699         ((self->gop.cur_frame_index * 2) % self->gop.max_pic_order_cnt);
1700
1701     /* TODO: move most this logic onto vabaseenc class  */
1702     if (self->gop.cur_frame_index == 0) {
1703       g_assert (frame->poc == 0);
1704       GST_LOG_OBJECT (self, "system_frame_number: %d, an IDR frame, starts"
1705           " a new GOP", gst_frame->system_frame_number);
1706
1707       g_queue_clear_full (&base->ref_list,
1708           (GDestroyNotify) gst_video_codec_frame_unref);
1709
1710       GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (gst_frame);
1711     }
1712
1713     frame->type = self->gop.frame_types[self->gop.cur_frame_index].slice_type;
1714     frame->is_ref = self->gop.frame_types[self->gop.cur_frame_index].is_ref;
1715     frame->pyramid_level =
1716         self->gop.frame_types[self->gop.cur_frame_index].pyramid_level;
1717     frame->left_ref_poc_diff =
1718         self->gop.frame_types[self->gop.cur_frame_index].left_ref_poc_diff;
1719     frame->right_ref_poc_diff =
1720         self->gop.frame_types[self->gop.cur_frame_index].right_ref_poc_diff;
1721
1722     if (GST_VIDEO_CODEC_FRAME_IS_FORCE_KEYFRAME (gst_frame)) {
1723       GST_DEBUG_OBJECT (self, "system_frame_number: %d, a force key frame,"
1724           " promote its type from %s to %s", gst_frame->system_frame_number,
1725           _slice_type_name (frame->type), _slice_type_name (GST_H264_I_SLICE));
1726       frame->type = GST_H264_I_SLICE;
1727       frame->is_ref = TRUE;
1728     }
1729
1730     GST_LOG_OBJECT (self, "Push frame, system_frame_number: %d, poc %d, "
1731         "frame type %s", gst_frame->system_frame_number, frame->poc,
1732         _slice_type_name (frame->type));
1733
1734     self->gop.cur_frame_index++;
1735     g_queue_push_tail (&base->reorder_list,
1736         gst_video_codec_frame_ref (gst_frame));
1737   }
1738
1739   /* ensure the last one a non-B and end the GOP. */
1740   if (last && self->gop.cur_frame_index < self->gop.idr_period) {
1741     GstVideoCodecFrame *last_frame;
1742
1743     /* Ensure next push will start a new GOP. */
1744     self->gop.cur_frame_index = self->gop.idr_period;
1745
1746     if (!g_queue_is_empty (&base->reorder_list)) {
1747       last_frame = g_queue_peek_tail (&base->reorder_list);
1748       frame = _enc_frame (last_frame);
1749       if (frame->type == GST_H264_B_SLICE) {
1750         frame->type = GST_H264_P_SLICE;
1751         frame->is_ref = TRUE;
1752       }
1753     }
1754   }
1755
1756   return TRUE;
1757 }
1758
1759 struct RefFramesCount
1760 {
1761   gint poc;
1762   guint num;
1763 };
1764
1765 static void
1766 _count_backward_ref_num (gpointer data, gpointer user_data)
1767 {
1768   GstVaH264EncFrame *frame = _enc_frame (data);
1769   struct RefFramesCount *count = (struct RefFramesCount *) user_data;
1770
1771   g_assert (frame->poc != count->poc);
1772   if (frame->poc > count->poc)
1773     count->num++;
1774 }
1775
1776 static GstVideoCodecFrame *
1777 _pop_pyramid_b_frame (GstVaH264Enc * self)
1778 {
1779   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
1780   guint i;
1781   gint index = -1;
1782   GstVaH264EncFrame *b_vaframe;
1783   GstVideoCodecFrame *b_frame;
1784   struct RefFramesCount count;
1785
1786   g_assert (self->gop.ref_num_list1 == 1);
1787
1788   b_frame = NULL;
1789   b_vaframe = NULL;
1790
1791   /* Find the lowest level with smallest poc. */
1792   for (i = 0; i < g_queue_get_length (&base->reorder_list); i++) {
1793     GstVaH264EncFrame *vaf;
1794     GstVideoCodecFrame *f;
1795
1796     f = g_queue_peek_nth (&base->reorder_list, i);
1797
1798     if (!b_frame) {
1799       b_frame = f;
1800       b_vaframe = _enc_frame (b_frame);
1801       index = i;
1802       continue;
1803     }
1804
1805     vaf = _enc_frame (f);
1806     if (b_vaframe->pyramid_level < vaf->pyramid_level) {
1807       b_frame = f;
1808       b_vaframe = vaf;
1809       index = i;
1810       continue;
1811     }
1812
1813     if (b_vaframe->poc > vaf->poc) {
1814       b_frame = f;
1815       b_vaframe = vaf;
1816       index = i;
1817     }
1818   }
1819
1820 again:
1821   /* Check whether its refs are already poped. */
1822   g_assert (b_vaframe->left_ref_poc_diff != 0);
1823   g_assert (b_vaframe->right_ref_poc_diff != 0);
1824   for (i = 0; i < g_queue_get_length (&base->reorder_list); i++) {
1825     GstVaH264EncFrame *vaf;
1826     GstVideoCodecFrame *f;
1827
1828     f = g_queue_peek_nth (&base->reorder_list, i);
1829
1830     if (f == b_frame)
1831       continue;
1832
1833     vaf = _enc_frame (f);
1834     if (vaf->poc == b_vaframe->poc + b_vaframe->left_ref_poc_diff
1835         || vaf->poc == b_vaframe->poc + b_vaframe->right_ref_poc_diff) {
1836       b_frame = f;
1837       b_vaframe = vaf;
1838       index = i;
1839       goto again;
1840     }
1841   }
1842
1843   /* Ensure we already have enough backward refs */
1844   count.num = 0;
1845   count.poc = b_vaframe->poc;
1846   g_queue_foreach (&base->ref_list, (GFunc) _count_backward_ref_num, &count);
1847   if (count.num >= self->gop.ref_num_list1) {
1848     GstVideoCodecFrame *f;
1849
1850     /* it will unref at pop_frame */
1851     f = g_queue_pop_nth (&base->reorder_list, index);
1852     g_assert (f == b_frame);
1853   } else {
1854     b_frame = NULL;
1855   }
1856
1857   return b_frame;
1858 }
1859
1860 static gboolean
1861 _pop_one_frame (GstVaBaseEnc * base, GstVideoCodecFrame ** out_frame)
1862 {
1863   GstVaH264Enc *self = GST_VA_H264_ENC (base);
1864   GstVaH264EncFrame *vaframe;
1865   GstVideoCodecFrame *frame;
1866   struct RefFramesCount count;
1867
1868   g_return_val_if_fail (self->gop.cur_frame_index <= self->gop.idr_period,
1869       FALSE);
1870
1871   *out_frame = NULL;
1872
1873   if (g_queue_is_empty (&base->reorder_list))
1874     return TRUE;
1875
1876   /* Return the last pushed non-B immediately. */
1877   frame = g_queue_peek_tail (&base->reorder_list);
1878   vaframe = _enc_frame (frame);
1879   if (vaframe->type != GST_H264_B_SLICE) {
1880     frame = g_queue_pop_tail (&base->reorder_list);
1881     goto get_one;
1882   }
1883
1884   if (self->gop.b_pyramid) {
1885     frame = _pop_pyramid_b_frame (self);
1886     if (frame == NULL)
1887       return TRUE;
1888     goto get_one;
1889   }
1890
1891   g_assert (self->gop.ref_num_list1 > 0);
1892
1893   /* If GOP end, pop anyway. */
1894   if (self->gop.cur_frame_index == self->gop.idr_period) {
1895     frame = g_queue_pop_head (&base->reorder_list);
1896     goto get_one;
1897   }
1898
1899   /* Ensure we already have enough backward refs */
1900   frame = g_queue_peek_head (&base->reorder_list);
1901   vaframe = _enc_frame (frame);
1902   count.num = 0;
1903   count.poc = vaframe->poc;
1904   g_queue_foreach (&base->ref_list, _count_backward_ref_num, &count);
1905   if (count.num >= self->gop.ref_num_list1) {
1906     frame = g_queue_pop_head (&base->reorder_list);
1907     goto get_one;
1908   }
1909
1910   return TRUE;
1911
1912 get_one:
1913   g_assert (self->gop.cur_frame_num < self->gop.max_frame_num);
1914
1915   vaframe = _enc_frame (frame);
1916   vaframe->frame_num = self->gop.cur_frame_num;
1917
1918   /* Add the frame number for ref frames. */
1919   if (vaframe->is_ref)
1920     self->gop.cur_frame_num++;
1921
1922   if (vaframe->frame_num == 0)
1923     self->gop.total_idr_count++;
1924
1925   if (self->gop.b_pyramid && vaframe->type == GST_H264_B_SLICE) {
1926     GST_LOG_OBJECT (self, "pop a pyramid B frame with system_frame_number:"
1927         " %d, poc: %d, frame num: %d, is_ref: %s, level %d",
1928         frame->system_frame_number, vaframe->poc, vaframe->frame_num,
1929         vaframe->is_ref ? "true" : "false", vaframe->pyramid_level);
1930   } else {
1931     GST_LOG_OBJECT (self, "pop a frame with system_frame_number: %d,"
1932         " frame type: %s, poc: %d, frame num: %d, is_ref: %s",
1933         frame->system_frame_number, _slice_type_name (vaframe->type),
1934         vaframe->poc, vaframe->frame_num, vaframe->is_ref ? "true" : "false");
1935   }
1936
1937   /* unref frame popped from queue or pyramid b_frame */
1938   gst_video_codec_frame_unref (frame);
1939   *out_frame = frame;
1940   return TRUE;
1941 }
1942
1943 static gboolean
1944 gst_va_h264_enc_reorder_frame (GstVaBaseEnc * base, GstVideoCodecFrame * frame,
1945     gboolean bump_all, GstVideoCodecFrame ** out_frame)
1946 {
1947   if (!_push_one_frame (base, frame, bump_all)) {
1948     GST_ERROR_OBJECT (base, "Failed to push the input frame"
1949         " system_frame_number: %d into the reorder list",
1950         frame->system_frame_number);
1951
1952     *out_frame = NULL;
1953     return FALSE;
1954   }
1955
1956   if (!_pop_one_frame (base, out_frame)) {
1957     GST_ERROR_OBJECT (base, "Failed to pop the frame from the reorder list");
1958     *out_frame = NULL;
1959     return FALSE;
1960   }
1961
1962   return TRUE;
1963 }
1964
1965 static inline gboolean
1966 _fill_sps (GstVaH264Enc * self, VAEncSequenceParameterBufferH264 * seq_param)
1967 {
1968   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
1969   GstH264Profile profile;
1970   guint32 constraint_set0_flag, constraint_set1_flag;
1971   guint32 constraint_set2_flag, constraint_set3_flag;
1972   guint32 max_dec_frame_buffering;
1973
1974   /* let max_num_ref_frames <= MaxDpbFrames. */
1975   max_dec_frame_buffering =
1976       MIN (self->gop.num_ref_frames + 1 /* Last frame before bump */ ,
1977       16 /* DPB_MAX_SIZE */ );
1978
1979   constraint_set0_flag = 0;
1980   constraint_set1_flag = 0;
1981   constraint_set2_flag = 0;
1982   constraint_set3_flag = 0;
1983
1984   switch (base->profile) {
1985     case VAProfileH264ConstrainedBaseline:
1986       profile = GST_H264_PROFILE_BASELINE;
1987       /* A.2.1 (baseline profile constraints) */
1988       constraint_set0_flag = 1;
1989       constraint_set1_flag = 1;
1990       break;
1991     case VAProfileH264Main:
1992       profile = GST_H264_PROFILE_MAIN;
1993       /* A.2.2 (main profile constraints) */
1994       constraint_set1_flag = 1;
1995       break;
1996     case VAProfileH264High:
1997     case VAProfileH264MultiviewHigh:
1998     case VAProfileH264StereoHigh:
1999       profile = GST_H264_PROFILE_HIGH;
2000       break;
2001     default:
2002       return FALSE;
2003   }
2004
2005   /* seq_scaling_matrix_present_flag not supported now */
2006   g_assert (seq_param->seq_fields.bits.seq_scaling_matrix_present_flag == 0);
2007   /* pic_order_cnt_type only support 0 now */
2008   g_assert (seq_param->seq_fields.bits.pic_order_cnt_type == 0);
2009   /* only progressive frames encoding is supported now */
2010   g_assert (seq_param->seq_fields.bits.frame_mbs_only_flag);
2011
2012   /* *INDENT-OFF* */
2013   GST_DEBUG_OBJECT (self, "filling SPS");
2014   self->sequence_hdr = (GstH264SPS) {
2015     .id = 0,
2016     .profile_idc = profile,
2017     .constraint_set0_flag = constraint_set0_flag,
2018     .constraint_set1_flag = constraint_set1_flag,
2019     .constraint_set2_flag = constraint_set2_flag,
2020     .constraint_set3_flag = constraint_set3_flag,
2021     .level_idc = self->level_idc,
2022
2023     .chroma_format_idc = seq_param->seq_fields.bits.chroma_format_idc,
2024     .bit_depth_luma_minus8 = seq_param->bit_depth_luma_minus8,
2025     .bit_depth_chroma_minus8 = seq_param->bit_depth_chroma_minus8,
2026
2027     .log2_max_frame_num_minus4 =
2028         seq_param->seq_fields.bits.log2_max_frame_num_minus4,
2029     .pic_order_cnt_type = seq_param->seq_fields.bits.pic_order_cnt_type,
2030     .log2_max_pic_order_cnt_lsb_minus4 =
2031         seq_param->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4,
2032
2033     .num_ref_frames = seq_param->max_num_ref_frames,
2034     .gaps_in_frame_num_value_allowed_flag = 0,
2035     .pic_width_in_mbs_minus1 = seq_param->picture_width_in_mbs - 1,
2036     .pic_height_in_map_units_minus1 =
2037         (seq_param->seq_fields.bits.frame_mbs_only_flag ?
2038             seq_param->picture_height_in_mbs - 1 :
2039             seq_param->picture_height_in_mbs / 2 - 1),
2040     .frame_mbs_only_flag = seq_param->seq_fields.bits.frame_mbs_only_flag,
2041     .mb_adaptive_frame_field_flag = 0,
2042     .direct_8x8_inference_flag =
2043         seq_param->seq_fields.bits.direct_8x8_inference_flag,
2044     .frame_cropping_flag = seq_param->frame_cropping_flag,
2045     .frame_crop_left_offset = seq_param->frame_crop_left_offset,
2046     .frame_crop_right_offset = seq_param->frame_crop_right_offset,
2047     .frame_crop_top_offset = seq_param->frame_crop_top_offset,
2048     .frame_crop_bottom_offset = seq_param->frame_crop_bottom_offset,
2049
2050     .vui_parameters_present_flag = seq_param->vui_parameters_present_flag,
2051     .vui_parameters = {
2052       .aspect_ratio_info_present_flag =
2053           seq_param->vui_fields.bits.aspect_ratio_info_present_flag,
2054       .aspect_ratio_idc = seq_param->aspect_ratio_idc,
2055       .sar_width = seq_param->sar_width,
2056       .sar_height = seq_param->sar_height,
2057       .overscan_info_present_flag = 0,
2058       .overscan_appropriate_flag = 0,
2059       .chroma_loc_info_present_flag = 0,
2060       .timing_info_present_flag =
2061           seq_param->vui_fields.bits.timing_info_present_flag,
2062       .num_units_in_tick = seq_param->num_units_in_tick,
2063       .time_scale = seq_param->time_scale,
2064       .fixed_frame_rate_flag = seq_param->vui_fields.bits.fixed_frame_rate_flag,
2065
2066       /* We do not write hrd and no need for buffering period SEI. */
2067       .nal_hrd_parameters_present_flag = 0,
2068       .vcl_hrd_parameters_present_flag = 0,
2069
2070       .low_delay_hrd_flag = seq_param->vui_fields.bits.low_delay_hrd_flag,
2071       .pic_struct_present_flag = 1,
2072       .bitstream_restriction_flag =
2073           seq_param->vui_fields.bits.bitstream_restriction_flag,
2074       .motion_vectors_over_pic_boundaries_flag =
2075           seq_param->vui_fields.bits.motion_vectors_over_pic_boundaries_flag,
2076       .max_bytes_per_pic_denom = 2,
2077       .max_bits_per_mb_denom = 1,
2078       .log2_max_mv_length_horizontal =
2079           seq_param->vui_fields.bits.log2_max_mv_length_horizontal,
2080       .log2_max_mv_length_vertical =
2081           seq_param->vui_fields.bits.log2_max_mv_length_vertical,
2082       .num_reorder_frames = self->gop.num_reorder_frames,
2083       .max_dec_frame_buffering = max_dec_frame_buffering,
2084     },
2085   };
2086   /* *INDENT-ON* */
2087
2088   return TRUE;
2089 }
2090
2091 static gboolean
2092 _add_sequence_header (GstVaH264Enc * self, GstVaH264EncFrame * frame)
2093 {
2094   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2095   guint size;
2096 #define SPS_SIZE 4 + GST_ROUND_UP_8 (MAX_SPS_HDR_SIZE + MAX_VUI_PARAMS_SIZE + \
2097     2 * MAX_HRD_PARAMS_SIZE) / 8
2098   guint8 packed_sps[SPS_SIZE] = { 0, };
2099 #undef SPS_SIZE
2100
2101   size = sizeof (packed_sps);
2102   if (gst_h264_bit_writer_sps (&self->sequence_hdr, TRUE, packed_sps,
2103           &size) != GST_H264_BIT_WRITER_OK) {
2104     GST_ERROR_OBJECT (self, "Failed to generate the sequence header");
2105     return FALSE;
2106   }
2107
2108   if (!gst_va_encoder_add_packed_header (base->encoder, frame->picture,
2109           VAEncPackedHeaderSequence, packed_sps, size * 8, FALSE)) {
2110     GST_ERROR_OBJECT (self, "Failed to add the packed sequence header");
2111     return FALSE;
2112   }
2113
2114   return TRUE;
2115 }
2116
2117 static inline void
2118 _fill_sequence_param (GstVaH264Enc * self,
2119     VAEncSequenceParameterBufferH264 * sequence)
2120 {
2121   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2122   gboolean direct_8x8_inference_flag = TRUE;
2123
2124   g_assert (self->gop.log2_max_frame_num >= 4);
2125   g_assert (self->gop.log2_max_pic_order_cnt >= 4);
2126
2127   /* A.2.3 Extended profile:
2128    * Sequence parameter sets shall have direct_8x8_inference_flag
2129    * equal to 1.
2130    *
2131    * A.3.3 Profile-specific level limits:
2132    * direct_8x8_inference_flag is not relevant to the Baseline,
2133    * Constrained Baseline, Constrained High, High 10 Intra, High 4:2:2
2134    * Intra, High 4:4:4 Intra, and CAVLC 4:4:4 Intra profiles as these
2135    * profiles do not allow B slice types, and
2136    * direct_8x8_inference_flag is equal to 1 for all levels of the
2137    * Extended profile. Table A-4.  We only have constrained baseline
2138    * here. */
2139   if (base->profile == VAProfileH264ConstrainedBaseline)
2140     direct_8x8_inference_flag = FALSE;
2141
2142   /* *INDENT-OFF* */
2143   *sequence = (VAEncSequenceParameterBufferH264) {
2144     .seq_parameter_set_id = 0,
2145     .level_idc = self->level_idc,
2146     .intra_period =
2147         self->gop.i_period > 0 ? self->gop.i_period : self->gop.idr_period,
2148     .intra_idr_period = self->gop.idr_period,
2149     .ip_period = self->gop.ip_period,
2150     .bits_per_second = self->rc.target_bitrate_bits,
2151     .max_num_ref_frames = self->gop.num_ref_frames,
2152     .picture_width_in_mbs = self->mb_width,
2153     .picture_height_in_mbs = self->mb_height,
2154
2155     .seq_fields.bits = {
2156       /* Only support 4:2:0 now. */
2157       .chroma_format_idc = 1,
2158       .frame_mbs_only_flag = 1,
2159       .mb_adaptive_frame_field_flag = FALSE,
2160       .seq_scaling_matrix_present_flag = FALSE,
2161       .direct_8x8_inference_flag = direct_8x8_inference_flag,
2162       .log2_max_frame_num_minus4 = self->gop.log2_max_frame_num - 4,
2163       .pic_order_cnt_type = 0,
2164       .log2_max_pic_order_cnt_lsb_minus4 = self->gop.log2_max_pic_order_cnt - 4,
2165     },
2166     .bit_depth_luma_minus8 = 0,
2167     .bit_depth_chroma_minus8 = 0,
2168
2169     .vui_parameters_present_flag = TRUE,
2170     .vui_fields.bits = {
2171       .aspect_ratio_info_present_flag = TRUE,
2172       .timing_info_present_flag = TRUE,
2173       .bitstream_restriction_flag = TRUE,
2174       .log2_max_mv_length_horizontal = 15,
2175       .log2_max_mv_length_vertical = 15,
2176       .fixed_frame_rate_flag = 1,
2177       .low_delay_hrd_flag = 0,
2178       .motion_vectors_over_pic_boundaries_flag = TRUE,
2179     },
2180     .aspect_ratio_idc = 0xff,
2181     /* FIXME: what if no framerate info is provided */
2182     .sar_width = GST_VIDEO_INFO_PAR_N (&base->input_state->info),
2183     .sar_height = GST_VIDEO_INFO_PAR_D (&base->input_state->info),
2184     .num_units_in_tick = GST_VIDEO_INFO_FPS_D (&base->input_state->info),
2185     .time_scale = GST_VIDEO_INFO_FPS_N (&base->input_state->info) * 2,
2186   };
2187   /* *INDENT-ON* */
2188
2189   /* frame_cropping_flag */
2190   if (base->width & 15 || base->height & 15) {
2191     static const guint SubWidthC[] = { 1, 2, 2, 1 };
2192     static const guint SubHeightC[] = { 1, 2, 1, 1 };
2193     const guint CropUnitX =
2194         SubWidthC[sequence->seq_fields.bits.chroma_format_idc];
2195     const guint CropUnitY =
2196         SubHeightC[sequence->seq_fields.bits.chroma_format_idc] *
2197         (2 - sequence->seq_fields.bits.frame_mbs_only_flag);
2198
2199     sequence->frame_cropping_flag = 1;
2200     sequence->frame_crop_left_offset = 0;
2201     sequence->frame_crop_right_offset = (16 * self->mb_width -
2202         base->width) / CropUnitX;
2203     sequence->frame_crop_top_offset = 0;
2204     sequence->frame_crop_bottom_offset = (16 * self->mb_height -
2205         base->height) / CropUnitY;
2206   }
2207 }
2208
2209 static gboolean
2210 _add_sequence_parameter (GstVaH264Enc * self, GstVaEncodePicture * picture,
2211     VAEncSequenceParameterBufferH264 * sequence)
2212 {
2213   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2214
2215   if (!gst_va_encoder_add_param (base->encoder, picture,
2216           VAEncSequenceParameterBufferType, sequence, sizeof (*sequence))) {
2217     GST_ERROR_OBJECT (self, "Failed to create the sequence parameter");
2218     return FALSE;
2219   }
2220
2221   return TRUE;
2222 }
2223
2224 static inline gboolean
2225 _fill_picture_parameter (GstVaH264Enc * self, GstVaH264EncFrame * frame,
2226     VAEncPictureParameterBufferH264 * pic_param)
2227 {
2228   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2229   guint i;
2230
2231   /* *INDENT-OFF* */
2232   *pic_param = (VAEncPictureParameterBufferH264) {
2233     .CurrPic = {
2234       .picture_id =
2235           gst_va_encode_picture_get_reconstruct_surface (frame->picture),
2236       .TopFieldOrderCnt = frame->poc,
2237     },
2238     .coded_buf = frame->picture->coded_buffer,
2239     /* Only support one sps and pps now. */
2240     .pic_parameter_set_id = 0,
2241     .seq_parameter_set_id = 0,
2242     /* means last encoding picture, EOS nal added. */
2243     .last_picture = frame->last_frame,
2244     .frame_num = frame->frame_num,
2245
2246     .pic_init_qp = self->rc.qp_i,
2247     /* Use slice's these fields to control ref num. */
2248     .num_ref_idx_l0_active_minus1 = 0,
2249     .num_ref_idx_l1_active_minus1 = 0,
2250     .chroma_qp_index_offset = 0,
2251     .second_chroma_qp_index_offset = 0,
2252     /* picture fields */
2253     .pic_fields.bits.idr_pic_flag = (frame->frame_num == 0),
2254     .pic_fields.bits.reference_pic_flag = frame->is_ref,
2255     .pic_fields.bits.entropy_coding_mode_flag = self->use_cabac,
2256     .pic_fields.bits.weighted_pred_flag = 0,
2257     .pic_fields.bits.weighted_bipred_idc = 0,
2258     .pic_fields.bits.constrained_intra_pred_flag = 0,
2259     .pic_fields.bits.transform_8x8_mode_flag = self->use_dct8x8,
2260     /* enable debloking */
2261     .pic_fields.bits.deblocking_filter_control_present_flag = 1,
2262     .pic_fields.bits.redundant_pic_cnt_present_flag = 0,
2263     /* bottom_field_pic_order_in_frame_present_flag */
2264     .pic_fields.bits.pic_order_present_flag = 0,
2265     .pic_fields.bits.pic_scaling_matrix_present_flag = 0,
2266   };
2267   /* *INDENT-ON* */
2268
2269   /* Non I frame, construct reference list. */
2270   i = 0;
2271   if (frame->type != GST_H264_I_SLICE) {
2272     GstVaH264EncFrame *f;
2273
2274     if (g_queue_is_empty (&base->ref_list)) {
2275       GST_ERROR_OBJECT (self, "No reference found for frame type %s",
2276           _slice_type_name (frame->type));
2277       return FALSE;
2278     }
2279
2280     g_assert (g_queue_get_length (&base->ref_list) <= self->gop.num_ref_frames);
2281
2282     /* ref frames in queue are already sorted by frame_num. */
2283     for (; i < g_queue_get_length (&base->ref_list); i++) {
2284       f = _enc_frame (g_queue_peek_nth (&base->ref_list, i));
2285
2286       pic_param->ReferenceFrames[i].picture_id =
2287           gst_va_encode_picture_get_reconstruct_surface (f->picture);
2288       pic_param->ReferenceFrames[i].TopFieldOrderCnt = f->poc;
2289       pic_param->ReferenceFrames[i].flags =
2290           VA_PICTURE_H264_SHORT_TERM_REFERENCE;
2291       pic_param->ReferenceFrames[i].frame_idx = f->frame_num;
2292     }
2293   }
2294   for (; i < 16; ++i)
2295     pic_param->ReferenceFrames[i].picture_id = VA_INVALID_ID;
2296
2297   return TRUE;
2298 };
2299
2300 static gboolean
2301 _add_picture_parameter (GstVaH264Enc * self, GstVaH264EncFrame * frame,
2302     VAEncPictureParameterBufferH264 * pic_param)
2303 {
2304   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2305
2306   if (!gst_va_encoder_add_param (base->encoder, frame->picture,
2307           VAEncPictureParameterBufferType, pic_param,
2308           sizeof (VAEncPictureParameterBufferH264))) {
2309     GST_ERROR_OBJECT (self, "Failed to create the picture parameter");
2310     return FALSE;
2311   }
2312
2313   return TRUE;
2314 }
2315
2316 static void
2317 _fill_pps (VAEncPictureParameterBufferH264 * pic_param, GstH264SPS * sps,
2318     GstH264PPS * pps)
2319 {
2320   /* *INDENT-OFF* */
2321   *pps = (GstH264PPS) {
2322     .id = 0,
2323     .sequence = sps,
2324     .entropy_coding_mode_flag =
2325         pic_param->pic_fields.bits.entropy_coding_mode_flag,
2326     .pic_order_present_flag =
2327         pic_param->pic_fields.bits.pic_order_present_flag,
2328     .num_slice_groups_minus1 = 0,
2329
2330     .num_ref_idx_l0_active_minus1 = pic_param->num_ref_idx_l0_active_minus1,
2331     .num_ref_idx_l1_active_minus1 = pic_param->num_ref_idx_l1_active_minus1,
2332
2333     .weighted_pred_flag = pic_param->pic_fields.bits.weighted_pred_flag,
2334     .weighted_bipred_idc = pic_param->pic_fields.bits.weighted_bipred_idc,
2335     .pic_init_qp_minus26 = pic_param->pic_init_qp - 26,
2336     .pic_init_qs_minus26 = 0,
2337     .chroma_qp_index_offset = pic_param->chroma_qp_index_offset,
2338     .deblocking_filter_control_present_flag =
2339         pic_param->pic_fields.bits.deblocking_filter_control_present_flag,
2340     .constrained_intra_pred_flag =
2341         pic_param->pic_fields.bits.constrained_intra_pred_flag,
2342     .redundant_pic_cnt_present_flag =
2343         pic_param->pic_fields.bits.redundant_pic_cnt_present_flag,
2344     .transform_8x8_mode_flag =
2345         pic_param->pic_fields.bits.transform_8x8_mode_flag,
2346     /* unsupport scaling lists */
2347     .pic_scaling_matrix_present_flag = 0,
2348     .second_chroma_qp_index_offset = pic_param->second_chroma_qp_index_offset,
2349   };
2350   /* *INDENT-ON* */
2351 }
2352
2353 static gboolean
2354 _add_picture_header (GstVaH264Enc * self, GstVaH264EncFrame * frame,
2355     GstH264PPS * pps)
2356 {
2357   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2358 #define PPS_SIZE 4 + GST_ROUND_UP_8 (MAX_PPS_HDR_SIZE) / 8
2359   guint8 packed_pps[PPS_SIZE] = { 0, };
2360 #undef PPS_SIZE
2361   guint size;
2362
2363   size = sizeof (packed_pps);
2364   if (gst_h264_bit_writer_pps (pps, TRUE, packed_pps,
2365           &size) != GST_H264_BIT_WRITER_OK) {
2366     GST_ERROR_OBJECT (self, "Failed to generate the picture header");
2367     return FALSE;
2368   }
2369
2370   if (!gst_va_encoder_add_packed_header (base->encoder, frame->picture,
2371           VAEncPackedHeaderPicture, packed_pps, size * 8, FALSE)) {
2372     GST_ERROR_OBJECT (self, "Failed to add the packed picture header");
2373     return FALSE;
2374   }
2375
2376   return TRUE;
2377 }
2378
2379 static gboolean
2380 _add_one_slice (GstVaH264Enc * self, GstVaH264EncFrame * frame,
2381     gint start_mb, gint mb_size,
2382     VAEncSliceParameterBufferH264 * slice,
2383     GstVaH264EncFrame * list0[16], guint list0_num,
2384     GstVaH264EncFrame * list1[16], guint list1_num)
2385 {
2386   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2387   int8_t slice_qp_delta = 0;
2388   gint i;
2389
2390   /* *INDENT-OFF* */
2391   if (self->rc.rc_ctrl_mode == VA_RC_CQP) {
2392     if (frame->type == GST_H264_P_SLICE) {
2393       slice_qp_delta = self->rc.qp_p - self->rc.qp_i;
2394     } else if (frame->type == GST_H264_B_SLICE) {
2395       slice_qp_delta = (int8_t) (self->rc.qp_b - self->rc.qp_i);
2396     }
2397     g_assert (slice_qp_delta <= 51 && slice_qp_delta >= -51);
2398   }
2399
2400   *slice = (VAEncSliceParameterBufferH264) {
2401     .macroblock_address = start_mb,
2402     .num_macroblocks = mb_size,
2403     .macroblock_info = VA_INVALID_ID,
2404     .slice_type = (uint8_t) frame->type,
2405     /* Only one parameter set supported now. */
2406     .pic_parameter_set_id = 0,
2407     .idr_pic_id = self->gop.total_idr_count,
2408     .pic_order_cnt_lsb = frame->poc,
2409     /* Not support top/bottom. */
2410     .delta_pic_order_cnt_bottom = 0,
2411     .delta_pic_order_cnt[0] = 0,
2412     .delta_pic_order_cnt[1] = 0,
2413
2414     .direct_spatial_mv_pred_flag = TRUE,
2415     /* .num_ref_idx_active_override_flag = , */
2416     /* .num_ref_idx_l0_active_minus1 = , */
2417     /* .num_ref_idx_l1_active_minus1 = , */
2418     /* Set the reference list later. */
2419
2420     .luma_log2_weight_denom = 0,
2421     .chroma_log2_weight_denom = 0,
2422     .luma_weight_l0_flag = 0,
2423     .chroma_weight_l0_flag = 0,
2424     .luma_weight_l1_flag = 0,
2425     .chroma_weight_l1_flag = 0,
2426
2427     .cabac_init_idc = 0,
2428     /* Just use picture default setting. */
2429     .slice_qp_delta = slice_qp_delta,
2430
2431     .disable_deblocking_filter_idc = 0,
2432     .slice_alpha_c0_offset_div2 = 2,
2433     .slice_beta_offset_div2 = 2,
2434   };
2435   /* *INDENT-ON* */
2436
2437   if (frame->type == GST_H264_B_SLICE || frame->type == GST_H264_P_SLICE) {
2438     slice->num_ref_idx_active_override_flag = (list0_num > 0 || list1_num > 0);
2439     slice->num_ref_idx_l0_active_minus1 = list0_num > 0 ? list0_num - 1 : 0;
2440     if (frame->type == GST_H264_B_SLICE)
2441       slice->num_ref_idx_l1_active_minus1 = list1_num > 0 ? list1_num - 1 : 0;
2442   }
2443
2444   i = 0;
2445   if (frame->type != GST_H264_I_SLICE) {
2446     for (; i < list0_num; i++) {
2447       slice->RefPicList0[i].picture_id =
2448           gst_va_encode_picture_get_reconstruct_surface (list0[i]->picture);
2449       slice->RefPicList0[i].TopFieldOrderCnt = list0[i]->poc;
2450       slice->RefPicList0[i].flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
2451       slice->RefPicList0[i].frame_idx = list0[i]->frame_num;
2452     }
2453   }
2454   for (; i < G_N_ELEMENTS (slice->RefPicList0); ++i) {
2455     slice->RefPicList0[i].picture_id = VA_INVALID_SURFACE;
2456     slice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
2457   }
2458
2459   i = 0;
2460   if (frame->type == GST_H264_B_SLICE) {
2461     for (; i < list1_num; i++) {
2462       slice->RefPicList1[i].picture_id =
2463           gst_va_encode_picture_get_reconstruct_surface (list1[i]->picture);
2464       slice->RefPicList1[i].TopFieldOrderCnt = list1[i]->poc;
2465       slice->RefPicList1[i].flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
2466       slice->RefPicList1[i].frame_idx = list1[i]->frame_num;
2467     }
2468   }
2469   for (; i < G_N_ELEMENTS (slice->RefPicList1); ++i) {
2470     slice->RefPicList1[i].picture_id = VA_INVALID_SURFACE;
2471     slice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
2472   }
2473
2474   if (!gst_va_encoder_add_param (base->encoder, frame->picture,
2475           VAEncSliceParameterBufferType, slice,
2476           sizeof (VAEncSliceParameterBufferH264))) {
2477     GST_ERROR_OBJECT (self, "Failed to create the slice parameter");
2478     return FALSE;
2479   }
2480
2481   return TRUE;
2482 }
2483
2484 static gint
2485 _poc_asc_compare (const GstVaH264EncFrame ** a, const GstVaH264EncFrame ** b)
2486 {
2487   return (*a)->poc - (*b)->poc;
2488 }
2489
2490 static gint
2491 _poc_des_compare (const GstVaH264EncFrame ** a, const GstVaH264EncFrame ** b)
2492 {
2493   return (*b)->poc - (*a)->poc;
2494 }
2495
2496 static gint
2497 _frame_num_asc_compare (const GstVaH264EncFrame ** a,
2498     const GstVaH264EncFrame ** b)
2499 {
2500   return (*a)->frame_num - (*b)->frame_num;
2501 }
2502
2503 static gint
2504 _frame_num_des_compare (const GstVaH264EncFrame ** a,
2505     const GstVaH264EncFrame ** b)
2506 {
2507   return (*b)->frame_num - (*a)->frame_num;
2508 }
2509
2510 /* If all the pic_num in the same order, OK. */
2511 static gboolean
2512 _ref_list_need_reorder (GstVaH264EncFrame * list[16], guint list_num,
2513     gboolean is_asc)
2514 {
2515   guint i;
2516   gint pic_num_diff;
2517
2518   if (list_num <= 1)
2519     return FALSE;
2520
2521   for (i = 1; i < list_num; i++) {
2522     pic_num_diff = list[i]->frame_num - list[i - 1]->frame_num;
2523     g_assert (pic_num_diff != 0);
2524
2525     if (pic_num_diff > 0 && !is_asc)
2526       return TRUE;
2527
2528     if (pic_num_diff < 0 && is_asc)
2529       return TRUE;
2530   }
2531
2532   return FALSE;
2533 }
2534
2535 static void
2536 _insert_ref_pic_list_modification (GstH264SliceHdr * slice_hdr,
2537     GstVaH264EncFrame * list[16], guint list_num, gboolean is_asc)
2538 {
2539   GstVaH264EncFrame *list_by_pic_num[16] = { NULL, };
2540   guint modification_num, i;
2541   GstH264RefPicListModification *ref_pic_list_modification = NULL;
2542   gint pic_num_diff, pic_num_lx_pred;
2543
2544   memcpy (list_by_pic_num, list, sizeof (GstVaH264EncFrame *) * list_num);
2545
2546   if (is_asc) {
2547     g_qsort_with_data (list_by_pic_num, list_num, sizeof (gpointer),
2548         (GCompareDataFunc) _frame_num_asc_compare, NULL);
2549   } else {
2550     g_qsort_with_data (list_by_pic_num, list_num, sizeof (gpointer),
2551         (GCompareDataFunc) _frame_num_des_compare, NULL);
2552   }
2553
2554   modification_num = 0;
2555   for (i = 0; i < list_num; i++) {
2556     if (list_by_pic_num[i]->poc != list[i]->poc)
2557       modification_num = i + 1;
2558   }
2559   g_assert (modification_num > 0);
2560
2561   if (is_asc) {
2562     slice_hdr->ref_pic_list_modification_flag_l1 = 1;
2563     slice_hdr->n_ref_pic_list_modification_l1 =
2564         modification_num + 1 /* The end operation. */ ;
2565     ref_pic_list_modification = slice_hdr->ref_pic_list_modification_l1;
2566   } else {
2567     slice_hdr->ref_pic_list_modification_flag_l0 = 1;
2568     slice_hdr->n_ref_pic_list_modification_l0 =
2569         modification_num + 1 /* The end operation. */ ;
2570     ref_pic_list_modification = slice_hdr->ref_pic_list_modification_l0;
2571   }
2572
2573   pic_num_lx_pred = slice_hdr->frame_num;
2574   for (i = 0; i < modification_num; i++) {
2575     pic_num_diff = list[i]->frame_num - pic_num_lx_pred;
2576     /* For the nex loop. */
2577     pic_num_lx_pred = list[i]->frame_num;
2578
2579     g_assert (pic_num_diff != 0);
2580
2581     if (pic_num_diff > 0) {
2582       ref_pic_list_modification->modification_of_pic_nums_idc = 1;
2583       ref_pic_list_modification->value.abs_diff_pic_num_minus1 =
2584           pic_num_diff - 1;
2585     } else {
2586       ref_pic_list_modification->modification_of_pic_nums_idc = 0;
2587       ref_pic_list_modification->value.abs_diff_pic_num_minus1 =
2588           (-pic_num_diff) - 1;
2589     }
2590
2591     ref_pic_list_modification++;
2592   }
2593
2594   ref_pic_list_modification->modification_of_pic_nums_idc = 3;
2595 }
2596
2597 static void
2598 _insert_ref_pic_marking_for_unused_frame (GstH264SliceHdr * slice_hdr,
2599     gint cur_frame_num, gint unused_frame_num)
2600 {
2601   GstH264RefPicMarking *refpicmarking;
2602
2603   slice_hdr->dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag = 1;
2604   slice_hdr->dec_ref_pic_marking.n_ref_pic_marking = 2;
2605
2606   refpicmarking = &slice_hdr->dec_ref_pic_marking.ref_pic_marking[0];
2607
2608   refpicmarking->memory_management_control_operation = 1;
2609   refpicmarking->difference_of_pic_nums_minus1 =
2610       cur_frame_num - unused_frame_num - 1;
2611
2612   refpicmarking = &slice_hdr->dec_ref_pic_marking.ref_pic_marking[1];
2613   refpicmarking->memory_management_control_operation = 0;
2614 }
2615
2616 static gboolean
2617 _add_slice_header (GstVaH264Enc * self, GstVaH264EncFrame * frame,
2618     GstH264PPS * pps, VAEncSliceParameterBufferH264 * slice,
2619     GstVaH264EncFrame * list0[16], guint list0_num,
2620     GstVaH264EncFrame * list1[16], guint list1_num)
2621 {
2622   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2623   GstH264SliceHdr slice_hdr;
2624   guint size, trail_bits;
2625   GstH264NalUnitType nal_type = GST_H264_NAL_SLICE;
2626 #define SLICE_HDR_SIZE 4 + GST_ROUND_UP_8 (MAX_SLICE_HDR_SIZE) / 8
2627   guint8 packed_slice_hdr[SLICE_HDR_SIZE] = { 0, };
2628 #undef SLICE_HDR_SIZE
2629
2630   if (frame->frame_num == 0)
2631     nal_type = GST_H264_NAL_SLICE_IDR;
2632
2633   /* *INDENT-OFF* */
2634   slice_hdr = (GstH264SliceHdr) {
2635     .first_mb_in_slice = slice->macroblock_address,
2636     .type = slice->slice_type,
2637     .pps = pps,
2638     .frame_num = frame->frame_num,
2639     /* interlaced not supported now. */
2640     .field_pic_flag = 0,
2641     .bottom_field_flag = 0,
2642     .idr_pic_id = (frame->frame_num == 0 ? slice->idr_pic_id : 0),
2643     /* only pic_order_cnt_type 1 is supported now. */
2644     .pic_order_cnt_lsb = slice->pic_order_cnt_lsb,
2645     .delta_pic_order_cnt_bottom = slice->delta_pic_order_cnt_bottom,
2646      /* Only for B frame. */
2647     .direct_spatial_mv_pred_flag =
2648         (frame->type == GST_H264_B_SLICE ?
2649          slice->direct_spatial_mv_pred_flag : 0),
2650
2651     .num_ref_idx_active_override_flag = slice->num_ref_idx_active_override_flag,
2652     .num_ref_idx_l0_active_minus1 = slice->num_ref_idx_l0_active_minus1,
2653     .num_ref_idx_l1_active_minus1 = slice->num_ref_idx_l1_active_minus1,
2654     /* Calculate it later. */
2655     .ref_pic_list_modification_flag_l0 = 0,
2656     .ref_pic_list_modification_flag_l1 = 0,
2657     /* We have weighted_pred_flag and weighted_bipred_idc 0 here, no
2658      * need weight_table. */
2659
2660     .dec_ref_pic_marking = {
2661       .no_output_of_prior_pics_flag = 0,
2662       .long_term_reference_flag = 0,
2663       /* If not sliding_window, we set it later. */
2664       .adaptive_ref_pic_marking_mode_flag = 0,
2665     },
2666
2667     .cabac_init_idc = slice->cabac_init_idc,
2668     .slice_qp_delta = slice->slice_qp_delta,
2669
2670     .disable_deblocking_filter_idc = slice->disable_deblocking_filter_idc,
2671     .slice_alpha_c0_offset_div2 = slice->slice_alpha_c0_offset_div2,
2672     .slice_beta_offset_div2 = slice->slice_beta_offset_div2,
2673   };
2674   /* *INDENT-ON* */
2675
2676   /* Reorder the ref lists if needed. */
2677   if (list0_num > 1) {
2678     /* list0 is in poc descend order now. */
2679     if (_ref_list_need_reorder (list0, list0_num, FALSE))
2680       _insert_ref_pic_list_modification (&slice_hdr, list0, list0_num, FALSE);
2681   }
2682
2683   if (list0_num > 1) {
2684     /* list0 is in poc ascend order now. */
2685     if (_ref_list_need_reorder (list1, list1_num, TRUE)) {
2686       _insert_ref_pic_list_modification (&slice_hdr, list1, list1_num, TRUE);
2687     }
2688   }
2689
2690   /* Mark the unused reference explicitly which this frame replaces. */
2691   if (frame->unused_for_reference_pic_num >= 0) {
2692     g_assert (frame->is_ref);
2693     _insert_ref_pic_marking_for_unused_frame (&slice_hdr, frame->frame_num,
2694         frame->unused_for_reference_pic_num);
2695   }
2696
2697   size = sizeof (packed_slice_hdr);
2698   trail_bits = 0;
2699   if (gst_h264_bit_writer_slice_hdr (&slice_hdr, TRUE, nal_type, frame->is_ref,
2700           packed_slice_hdr, &size, &trail_bits) != GST_H264_BIT_WRITER_OK) {
2701     GST_ERROR_OBJECT (self, "Failed to generate the slice header");
2702     return FALSE;
2703   }
2704
2705   if (!gst_va_encoder_add_packed_header (base->encoder, frame->picture,
2706           VAEncPackedHeaderSlice, packed_slice_hdr, size * 8 + trail_bits,
2707           FALSE)) {
2708     GST_ERROR_OBJECT (self, "Failed to add the packed slice header");
2709     return FALSE;
2710   }
2711
2712   return TRUE;
2713 }
2714
2715 static gboolean
2716 _add_aud (GstVaH264Enc * self, GstVaH264EncFrame * frame)
2717 {
2718   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2719   guint8 aud_data[8] = { 0, };
2720   guint size;
2721   guint8 primary_pic_type = 0;
2722
2723   switch (frame->type) {
2724     case GST_H264_I_SLICE:
2725       primary_pic_type = 0;
2726       break;
2727     case GST_H264_P_SLICE:
2728       primary_pic_type = 1;
2729       break;
2730     case GST_H264_B_SLICE:
2731       primary_pic_type = 2;
2732       break;
2733     default:
2734       g_assert_not_reached ();
2735       break;
2736   }
2737
2738   size = sizeof (aud_data);
2739   if (gst_h264_bit_writer_aud (primary_pic_type, TRUE, aud_data,
2740           &size) != GST_H264_BIT_WRITER_OK) {
2741     GST_ERROR_OBJECT (self, "Failed to generate the AUD");
2742     return FALSE;
2743   }
2744
2745   if (!gst_va_encoder_add_packed_header (base->encoder, frame->picture,
2746           VAEncPackedHeaderRawData, aud_data, size * 8, FALSE)) {
2747     GST_ERROR_OBJECT (self, "Failed to add the AUD");
2748     return FALSE;
2749   }
2750
2751   return TRUE;
2752 }
2753
2754 static void
2755 _create_sei_cc_message (GstVideoCaptionMeta * cc_meta,
2756     GstH264SEIMessage * sei_msg)
2757 {
2758   guint8 *data;
2759   GstH264RegisteredUserData *user_data;
2760
2761   sei_msg->payloadType = GST_H264_SEI_REGISTERED_USER_DATA;
2762
2763   user_data = &sei_msg->payload.registered_user_data;
2764
2765   user_data->country_code = 181;
2766   user_data->size = 10 + cc_meta->size;
2767
2768   data = g_malloc (user_data->size);
2769
2770   /* 16-bits itu_t_t35_provider_code */
2771   data[0] = 0;
2772   data[1] = 49;
2773   /* 32-bits ATSC_user_identifier */
2774   data[2] = 'G';
2775   data[3] = 'A';
2776   data[4] = '9';
2777   data[5] = '4';
2778   /* 8-bits ATSC1_data_user_data_type_code */
2779   data[6] = 3;
2780   /* 8-bits:
2781    * 1 bit process_em_data_flag (0)
2782    * 1 bit process_cc_data_flag (1)
2783    * 1 bit additional_data_flag (0)
2784    * 5-bits cc_count
2785    */
2786   data[7] = ((cc_meta->size / 3) & 0x1f) | 0x40;
2787   /* 8 bits em_data, unused */
2788   data[8] = 255;
2789
2790   memcpy (data + 9, cc_meta->data, cc_meta->size);
2791
2792   /* 8 marker bits */
2793   data[user_data->size - 1] = 255;
2794
2795   user_data->data = data;
2796 }
2797
2798 static gboolean
2799 _create_sei_cc_data (GPtrArray * cc_list, guint8 * sei_data, guint * data_size)
2800 {
2801   GArray *msg_list = NULL;
2802   GstH264BitWriterResult ret;
2803   gint i;
2804
2805   msg_list = g_array_new (TRUE, TRUE, sizeof (GstH264SEIMessage));
2806   g_array_set_clear_func (msg_list, (GDestroyNotify) gst_h264_sei_clear);
2807   g_array_set_size (msg_list, cc_list->len);
2808
2809   for (i = 0; i < cc_list->len; i++) {
2810     GstH264SEIMessage *msg = &g_array_index (msg_list, GstH264SEIMessage, i);
2811     _create_sei_cc_message (g_ptr_array_index (cc_list, i), msg);
2812   }
2813
2814   ret = gst_h264_bit_writer_sei (msg_list, TRUE, sei_data, data_size);
2815
2816   g_array_unref (msg_list);
2817
2818   return (ret == GST_H264_BIT_WRITER_OK);
2819 }
2820
2821 static void
2822 _add_sei_cc (GstVaH264Enc * self, GstVideoCodecFrame * gst_frame)
2823 {
2824   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2825   GstVaH264EncFrame *frame;
2826   GPtrArray *cc_list = NULL;
2827   GstVideoCaptionMeta *cc_meta;
2828   gpointer iter = NULL;
2829   guint8 *packed_sei = NULL;
2830   guint sei_size = 0;
2831
2832   frame = _enc_frame (gst_frame);
2833
2834   /* SEI header size */
2835   sei_size = 6;
2836   while ((cc_meta = (GstVideoCaptionMeta *)
2837           gst_buffer_iterate_meta_filtered (gst_frame->input_buffer, &iter,
2838               GST_VIDEO_CAPTION_META_API_TYPE))) {
2839     if (cc_meta->caption_type != GST_VIDEO_CAPTION_TYPE_CEA708_RAW)
2840       continue;
2841
2842     if (!cc_list)
2843       cc_list = g_ptr_array_new ();
2844
2845     g_ptr_array_add (cc_list, cc_meta);
2846     /* Add enough SEI message size for bitwriter. */
2847     sei_size += cc_meta->size + 50;
2848   }
2849
2850   if (!cc_list)
2851     goto out;
2852
2853   packed_sei = g_malloc0 (sei_size);
2854
2855   if (!_create_sei_cc_data (cc_list, packed_sei, &sei_size)) {
2856     GST_WARNING_OBJECT (self, "Failed to write the SEI CC data");
2857     goto out;
2858   }
2859
2860   if (!gst_va_encoder_add_packed_header (base->encoder, frame->picture,
2861           VAEncPackedHeaderRawData, packed_sei, sei_size * 8, FALSE)) {
2862     GST_WARNING_OBJECT (self, "Failed to add SEI CC data");
2863     goto out;
2864   }
2865
2866 out:
2867   g_clear_pointer (&cc_list, g_ptr_array_unref);
2868   if (packed_sei)
2869     g_free (packed_sei);
2870 }
2871
2872 static gboolean
2873 _encode_one_frame (GstVaH264Enc * self, GstVideoCodecFrame * gst_frame)
2874 {
2875   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
2876   VAEncPictureParameterBufferH264 pic_param;
2877   GstH264PPS pps;
2878   GstVaH264EncFrame *list0[16] = { NULL, };
2879   guint list0_num = 0;
2880   GstVaH264EncFrame *list1[16] = { NULL, };
2881   guint list1_num = 0;
2882   guint slice_of_mbs, slice_mod_mbs, slice_start_mb, slice_mbs;
2883   gint i;
2884   GstVaH264EncFrame *frame;
2885
2886   g_return_val_if_fail (gst_frame, FALSE);
2887
2888   frame = _enc_frame (gst_frame);
2889
2890   if (self->aud && !_add_aud (self, frame))
2891     return FALSE;
2892
2893   /* Repeat the SPS for IDR. */
2894   if (frame->poc == 0) {
2895     VAEncSequenceParameterBufferH264 sequence;
2896
2897     if (!gst_va_base_enc_add_rate_control_parameter (base, frame->picture,
2898             self->rc.rc_ctrl_mode, self->rc.max_bitrate_bits,
2899             self->rc.target_percentage, self->rc.qp_i, self->rc.min_qp,
2900             self->rc.max_qp, self->rc.mbbrc))
2901       return FALSE;
2902
2903     if (!gst_va_base_enc_add_quality_level_parameter (base, frame->picture,
2904             self->rc.target_usage))
2905       return FALSE;
2906
2907     if (!gst_va_base_enc_add_frame_rate_parameter (base, frame->picture))
2908       return FALSE;
2909
2910     if (!gst_va_base_enc_add_hrd_parameter (base, frame->picture,
2911             self->rc.rc_ctrl_mode, self->rc.cpb_length_bits))
2912       return FALSE;
2913
2914     if (!gst_va_base_enc_add_trellis_parameter (base, frame->picture,
2915             self->use_trellis))
2916       return FALSE;
2917
2918     _fill_sequence_param (self, &sequence);
2919     if (!_fill_sps (self, &sequence))
2920       return FALSE;
2921
2922     if (!_add_sequence_parameter (self, frame->picture, &sequence))
2923       return FALSE;
2924
2925     if ((self->packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE)
2926         && !_add_sequence_header (self, frame))
2927       return FALSE;
2928   }
2929
2930   /* Non I frame, construct reference list. */
2931   if (frame->type != GST_H264_I_SLICE) {
2932     GstVaH264EncFrame *vaf;
2933     GstVideoCodecFrame *f;
2934
2935     for (i = g_queue_get_length (&base->ref_list) - 1; i >= 0; i--) {
2936       f = g_queue_peek_nth (&base->ref_list, i);
2937       vaf = _enc_frame (f);
2938       if (vaf->poc > frame->poc)
2939         continue;
2940
2941       list0[list0_num] = vaf;
2942       list0_num++;
2943     }
2944
2945     /* reorder to select the most nearest forward frames. */
2946     g_qsort_with_data (list0, list0_num, sizeof (gpointer),
2947         (GCompareDataFunc) _poc_des_compare, NULL);
2948
2949     if (list0_num > self->gop.ref_num_list0)
2950       list0_num = self->gop.ref_num_list0;
2951   }
2952
2953   if (frame->type == GST_H264_B_SLICE) {
2954     GstVaH264EncFrame *vaf;
2955     GstVideoCodecFrame *f;
2956
2957     for (i = 0; i < g_queue_get_length (&base->ref_list); i++) {
2958       f = g_queue_peek_nth (&base->ref_list, i);
2959       vaf = _enc_frame (f);
2960       if (vaf->poc < frame->poc)
2961         continue;
2962
2963       list1[list1_num] = vaf;
2964       list1_num++;
2965     }
2966
2967     /* reorder to select the most nearest backward frames. */
2968     g_qsort_with_data (list1, list1_num, sizeof (gpointer),
2969         (GCompareDataFunc) _poc_asc_compare, NULL);
2970
2971     if (list1_num > self->gop.ref_num_list1)
2972       list1_num = self->gop.ref_num_list1;
2973   }
2974
2975   g_assert (list0_num + list1_num <= self->gop.num_ref_frames);
2976
2977   if (!_fill_picture_parameter (self, frame, &pic_param))
2978     return FALSE;
2979   if (!_add_picture_parameter (self, frame, &pic_param))
2980     return FALSE;
2981   _fill_pps (&pic_param, &self->sequence_hdr, &pps);
2982
2983   if ((self->packed_headers & VA_ENC_PACKED_HEADER_PICTURE)
2984       && frame->type == GST_H264_I_SLICE
2985       && !_add_picture_header (self, frame, &pps))
2986     return FALSE;
2987
2988   if (self->cc) {
2989     /* CC errors are not fatal */
2990     _add_sei_cc (self, gst_frame);
2991   }
2992
2993   slice_of_mbs = self->mb_width * self->mb_height / self->num_slices;
2994   slice_mod_mbs = self->mb_width * self->mb_height % self->num_slices;
2995   slice_start_mb = 0;
2996   slice_mbs = 0;
2997   for (i = 0; i < self->num_slices; i++) {
2998     VAEncSliceParameterBufferH264 slice;
2999
3000     slice_mbs = slice_of_mbs;
3001     /* divide the remainder to each equally */
3002     if (slice_mod_mbs) {
3003       slice_mbs++;
3004       slice_mod_mbs--;
3005     }
3006
3007     if (!_add_one_slice (self, frame, slice_start_mb, slice_mbs, &slice,
3008             list0, list0_num, list1, list1_num))
3009       return FALSE;
3010
3011     if ((self->packed_headers & VA_ENC_PACKED_HEADER_SLICE) &&
3012         (!_add_slice_header (self, frame, &pps, &slice, list0, list0_num,
3013                 list1, list1_num)))
3014       return FALSE;
3015
3016     slice_start_mb += slice_mbs;
3017   }
3018
3019   if (!gst_va_encoder_encode (base->encoder, frame->picture)) {
3020     GST_ERROR_OBJECT (self, "Encode frame error");
3021     return FALSE;
3022   }
3023
3024   return TRUE;
3025 }
3026
3027 static gboolean
3028 gst_va_h264_enc_flush (GstVideoEncoder * venc)
3029 {
3030   GstVaH264Enc *self = GST_VA_H264_ENC (venc);
3031
3032   /* begin from an IDR after flush. */
3033   self->gop.cur_frame_index = 0;
3034   self->gop.cur_frame_num = 0;
3035
3036   return GST_VIDEO_ENCODER_CLASS (parent_class)->flush (venc);
3037 }
3038
3039 static void
3040 gst_va_h264_enc_prepare_output (GstVaBaseEnc * base, GstVideoCodecFrame * frame)
3041 {
3042   GstVaH264Enc *self = GST_VA_H264_ENC (base);
3043   GstVaH264EncFrame *frame_enc;
3044
3045   frame_enc = _enc_frame (frame);
3046
3047   frame->pts =
3048       base->start_pts + base->frame_duration * frame_enc->total_frame_count;
3049   /* The PTS should always be later than the DTS. */
3050   frame->dts = base->start_pts + base->frame_duration *
3051       ((gint64) base->output_frame_count -
3052       (gint64) self->gop.num_reorder_frames);
3053   base->output_frame_count++;
3054   frame->duration = base->frame_duration;
3055 }
3056
3057 static gint
3058 _sort_by_frame_num (gconstpointer a, gconstpointer b, gpointer user_data)
3059 {
3060   GstVaH264EncFrame *frame1 = _enc_frame ((GstVideoCodecFrame *) a);
3061   GstVaH264EncFrame *frame2 = _enc_frame ((GstVideoCodecFrame *) b);
3062
3063   g_assert (frame1->frame_num != frame2->frame_num);
3064
3065   return frame1->frame_num - frame2->frame_num;
3066 }
3067
3068 static GstVideoCodecFrame *
3069 _find_unused_reference_frame (GstVaH264Enc * self, GstVaH264EncFrame * frame)
3070 {
3071   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
3072   GstVaH264EncFrame *b_vaframe;
3073   GstVideoCodecFrame *b_frame;
3074   guint i;
3075
3076   /* We still have more space. */
3077   if (g_queue_get_length (&base->ref_list) < self->gop.num_ref_frames)
3078     return NULL;
3079
3080   /* Not b_pyramid, sliding window is enough. */
3081   if (!self->gop.b_pyramid)
3082     return g_queue_peek_head (&base->ref_list);
3083
3084   /* I/P frame, just using sliding window. */
3085   if (frame->type != GST_H264_B_SLICE)
3086     return g_queue_peek_head (&base->ref_list);
3087
3088   /* Choose the B frame with lowest POC. */
3089   b_frame = NULL;
3090   b_vaframe = NULL;
3091   for (i = 0; i < g_queue_get_length (&base->ref_list); i++) {
3092     GstVaH264EncFrame *vaf;
3093     GstVideoCodecFrame *f;
3094
3095     f = g_queue_peek_nth (&base->ref_list, i);
3096     vaf = _enc_frame (f);
3097     if (vaf->type != GST_H264_B_SLICE)
3098       continue;
3099
3100     if (!b_frame) {
3101       b_frame = f;
3102       b_vaframe = _enc_frame (b_frame);
3103       continue;
3104     }
3105
3106     b_vaframe = _enc_frame (b_frame);
3107     g_assert (vaf->poc != b_vaframe->poc);
3108     if (vaf->poc < b_vaframe->poc) {
3109       b_frame = f;
3110       b_vaframe = _enc_frame (b_frame);
3111     }
3112   }
3113
3114   /* No B frame as ref. */
3115   if (!b_frame)
3116     return g_queue_peek_head (&base->ref_list);
3117
3118   if (b_frame != g_queue_peek_head (&base->ref_list)) {
3119     b_vaframe = _enc_frame (b_frame);
3120     frame->unused_for_reference_pic_num = b_vaframe->frame_num;
3121     GST_LOG_OBJECT (self, "The frame with POC: %d, pic_num %d will be"
3122         " replaced by the frame with POC: %d, pic_num %d explicitly by"
3123         " using memory_management_control_operation=1",
3124         b_vaframe->poc, b_vaframe->frame_num, frame->poc, frame->frame_num);
3125   }
3126
3127   return b_frame;
3128 }
3129
3130 static GstFlowReturn
3131 gst_va_h264_enc_encode_frame (GstVaBaseEnc * base,
3132     GstVideoCodecFrame * gst_frame, gboolean is_last)
3133 {
3134   GstVaH264Enc *self = GST_VA_H264_ENC (base);
3135   GstVaH264EncFrame *frame;
3136   GstVideoCodecFrame *unused_ref = NULL;
3137
3138   frame = _enc_frame (gst_frame);
3139   frame->last_frame = is_last;
3140
3141   g_assert (frame->picture == NULL);
3142   frame->picture = gst_va_encode_picture_new (base->encoder,
3143       gst_frame->input_buffer);
3144
3145   if (!frame->picture) {
3146     GST_ERROR_OBJECT (self, "Failed to create the encode picture");
3147     return GST_FLOW_ERROR;
3148   }
3149
3150   if (frame->is_ref)
3151     unused_ref = _find_unused_reference_frame (self, frame);
3152
3153   if (!_encode_one_frame (self, gst_frame)) {
3154     GST_ERROR_OBJECT (self, "Failed to encode the frame");
3155     return GST_FLOW_ERROR;
3156   }
3157
3158   g_queue_push_tail (&base->output_list, gst_video_codec_frame_ref (gst_frame));
3159
3160   if (frame->is_ref) {
3161     if (unused_ref) {
3162       if (!g_queue_remove (&base->ref_list, unused_ref))
3163         g_assert_not_reached ();
3164
3165       gst_video_codec_frame_unref (unused_ref);
3166     }
3167
3168     /* Add it into the reference list. */
3169     g_queue_push_tail (&base->ref_list, gst_video_codec_frame_ref (gst_frame));
3170     g_queue_sort (&base->ref_list, _sort_by_frame_num, NULL);
3171
3172     g_assert (g_queue_get_length (&base->ref_list) <= self->gop.num_ref_frames);
3173   }
3174
3175   return GST_FLOW_OK;
3176 }
3177
3178 static gboolean
3179 gst_va_h264_enc_new_frame (GstVaBaseEnc * base, GstVideoCodecFrame * frame)
3180 {
3181   GstVaH264EncFrame *frame_in;
3182
3183   frame_in = gst_va_enc_frame_new ();
3184   frame_in->total_frame_count = base->input_frame_count++;
3185   gst_video_codec_frame_set_user_data (frame, frame_in, gst_va_enc_frame_free);
3186
3187   return TRUE;
3188 }
3189
3190 /* *INDENT-OFF* */
3191 static const gchar *sink_caps_str =
3192     GST_VIDEO_CAPS_MAKE_WITH_FEATURES (GST_CAPS_FEATURE_MEMORY_VA,
3193         "{ NV12 }") " ;"
3194     GST_VIDEO_CAPS_MAKE ("{ NV12 }");
3195 /* *INDENT-ON* */
3196
3197 static const gchar *src_caps_str = "video/x-h264";
3198
3199 static gpointer
3200 _register_debug_category (gpointer data)
3201 {
3202   GST_DEBUG_CATEGORY_INIT (gst_va_h264enc_debug, "vah264enc", 0,
3203       "VA h264 encoder");
3204
3205   return NULL;
3206 }
3207
3208 static void
3209 gst_va_h264_enc_init (GTypeInstance * instance, gpointer g_class)
3210 {
3211   GstVaH264Enc *self = GST_VA_H264_ENC (instance);
3212
3213   /* default values */
3214   self->prop.key_int_max = 0;
3215   self->prop.num_bframes = 0;
3216   self->prop.num_iframes = 0;
3217   self->prop.num_ref_frames = 3;
3218   self->prop.b_pyramid = FALSE;
3219   self->prop.num_slices = 1;
3220   self->prop.min_qp = 1;
3221   self->prop.max_qp = 51;
3222   self->prop.qp_i = 26;
3223   self->prop.qp_p = 26;
3224   self->prop.qp_b = 26;
3225   self->prop.use_dct8x8 = TRUE;
3226   self->prop.use_cabac = TRUE;
3227   self->prop.use_trellis = FALSE;
3228   self->prop.aud = FALSE;
3229   self->prop.cc = TRUE;
3230   self->prop.mbbrc = 0;
3231   self->prop.bitrate = 0;
3232   self->prop.target_percentage = 66;
3233   self->prop.target_usage = 4;
3234   if (properties[PROP_RATE_CONTROL]) {
3235     self->prop.rc_ctrl =
3236         G_PARAM_SPEC_ENUM (properties[PROP_RATE_CONTROL])->default_value;
3237   } else {
3238     self->prop.rc_ctrl = VA_RC_NONE;
3239   }
3240   self->prop.cpb_size = 0;
3241 }
3242
3243 static void
3244 gst_va_h264_enc_set_property (GObject * object, guint prop_id,
3245     const GValue * value, GParamSpec * pspec)
3246 {
3247   GstVaH264Enc *self = GST_VA_H264_ENC (object);
3248   GstVaBaseEnc *base = GST_VA_BASE_ENC (self);
3249
3250   GST_OBJECT_LOCK (self);
3251
3252   switch (prop_id) {
3253     case PROP_KEY_INT_MAX:
3254       self->prop.key_int_max = g_value_get_uint (value);
3255       break;
3256     case PROP_BFRAMES:
3257       self->prop.num_bframes = g_value_get_uint (value);
3258       break;
3259     case PROP_IFRAMES:
3260       self->prop.num_iframes = g_value_get_uint (value);
3261       break;
3262     case PROP_NUM_REF_FRAMES:
3263       self->prop.num_ref_frames = g_value_get_uint (value);
3264       break;
3265     case PROP_B_PYRAMID:
3266       self->prop.b_pyramid = g_value_get_boolean (value);
3267       break;
3268     case PROP_NUM_SLICES:
3269       self->prop.num_slices = g_value_get_uint (value);
3270       break;
3271     case PROP_MIN_QP:
3272       self->prop.min_qp = g_value_get_uint (value);
3273       break;
3274     case PROP_MAX_QP:
3275       self->prop.max_qp = g_value_get_uint (value);
3276       break;
3277     case PROP_QP_I:
3278       self->prop.qp_i = g_value_get_uint (value);
3279       g_atomic_int_set (&GST_VA_BASE_ENC (self)->reconf, TRUE);
3280       break;
3281     case PROP_QP_P:
3282       self->prop.qp_p = g_value_get_uint (value);
3283       g_atomic_int_set (&GST_VA_BASE_ENC (self)->reconf, TRUE);
3284       break;
3285     case PROP_QP_B:
3286       self->prop.qp_b = g_value_get_uint (value);
3287       g_atomic_int_set (&GST_VA_BASE_ENC (self)->reconf, TRUE);
3288       break;
3289     case PROP_DCT8X8:
3290       self->prop.use_dct8x8 = g_value_get_boolean (value);
3291       break;
3292     case PROP_CABAC:
3293       self->prop.use_cabac = g_value_get_boolean (value);
3294       break;
3295     case PROP_TRELLIS:
3296       self->prop.use_trellis = g_value_get_boolean (value);
3297       break;
3298     case PROP_AUD:
3299       self->prop.aud = g_value_get_boolean (value);
3300       break;
3301     case PROP_CC:
3302       self->prop.cc = g_value_get_boolean (value);
3303       break;
3304     case PROP_MBBRC:{
3305       /* Macroblock-level rate control.
3306        * 0: use default,
3307        * 1: always enable,
3308        * 2: always disable,
3309        * other: reserved. */
3310       switch (g_value_get_enum (value)) {
3311         case GST_VA_FEATURE_DISABLED:
3312           self->prop.mbbrc = 2;
3313           break;
3314         case GST_VA_FEATURE_ENABLED:
3315           self->prop.mbbrc = 1;
3316           break;
3317         case GST_VA_FEATURE_AUTO:
3318           self->prop.mbbrc = 0;
3319           break;
3320       }
3321       break;
3322     }
3323     case PROP_BITRATE:
3324       self->prop.bitrate = g_value_get_uint (value);
3325       g_atomic_int_set (&GST_VA_BASE_ENC (self)->reconf, TRUE);
3326       break;
3327     case PROP_TARGET_PERCENTAGE:
3328       self->prop.target_percentage = g_value_get_uint (value);
3329       g_atomic_int_set (&GST_VA_BASE_ENC (self)->reconf, TRUE);
3330       break;
3331     case PROP_TARGET_USAGE:
3332       self->prop.target_usage = g_value_get_uint (value);
3333       g_atomic_int_set (&GST_VA_BASE_ENC (self)->reconf, TRUE);
3334       break;
3335     case PROP_RATE_CONTROL:
3336       self->prop.rc_ctrl = g_value_get_enum (value);
3337       g_atomic_int_set (&GST_VA_BASE_ENC (self)->reconf, TRUE);
3338       break;
3339     case PROP_CPB_SIZE:
3340       self->prop.cpb_size = g_value_get_uint (value);
3341       break;
3342     default:
3343       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3344   }
3345
3346   GST_OBJECT_UNLOCK (self);
3347
3348 #ifndef GST_DISABLE_GST_DEBUG
3349   if (!g_atomic_int_get (&GST_VA_BASE_ENC (self)->reconf)
3350       && base->encoder && gst_va_encoder_is_open (base->encoder)) {
3351     GST_WARNING_OBJECT (self, "Property `%s` change ignored while processing.",
3352         pspec->name);
3353   }
3354 #endif
3355
3356 }
3357
3358 static void
3359 gst_va_h264_enc_get_property (GObject * object, guint prop_id,
3360     GValue * value, GParamSpec * pspec)
3361 {
3362   GstVaH264Enc *const self = GST_VA_H264_ENC (object);
3363
3364   GST_OBJECT_LOCK (self);
3365
3366   switch (prop_id) {
3367     case PROP_KEY_INT_MAX:
3368       g_value_set_uint (value, self->prop.key_int_max);
3369       break;
3370     case PROP_BFRAMES:
3371       g_value_set_uint (value, self->prop.num_bframes);
3372       break;
3373     case PROP_IFRAMES:
3374       g_value_set_uint (value, self->prop.num_iframes);
3375       break;
3376     case PROP_NUM_REF_FRAMES:
3377       g_value_set_uint (value, self->prop.num_ref_frames);
3378       break;
3379     case PROP_B_PYRAMID:
3380       g_value_set_boolean (value, self->prop.b_pyramid);
3381       break;
3382     case PROP_NUM_SLICES:
3383       g_value_set_uint (value, self->prop.num_slices);
3384       break;
3385     case PROP_MIN_QP:
3386       g_value_set_uint (value, self->prop.min_qp);
3387       break;
3388     case PROP_MAX_QP:
3389       g_value_set_uint (value, self->prop.max_qp);
3390       break;
3391     case PROP_QP_I:
3392       g_value_set_uint (value, self->prop.qp_i);
3393       break;
3394     case PROP_QP_P:
3395       g_value_set_uint (value, self->prop.qp_p);
3396       break;
3397     case PROP_QP_B:
3398       g_value_set_uint (value, self->prop.qp_b);
3399       break;
3400     case PROP_DCT8X8:
3401       g_value_set_boolean (value, self->prop.use_dct8x8);
3402       break;
3403     case PROP_CABAC:
3404       g_value_set_boolean (value, self->prop.use_cabac);
3405       break;
3406     case PROP_TRELLIS:
3407       g_value_set_boolean (value, self->prop.use_trellis);
3408       break;
3409     case PROP_AUD:
3410       g_value_set_boolean (value, self->prop.aud);
3411       break;
3412     case PROP_CC:
3413       g_value_set_boolean (value, self->prop.cc);
3414       break;
3415     case PROP_MBBRC:
3416       g_value_set_enum (value, self->prop.mbbrc);
3417       break;
3418     case PROP_BITRATE:
3419       g_value_set_uint (value, self->prop.bitrate);
3420       break;
3421     case PROP_TARGET_PERCENTAGE:
3422       g_value_set_uint (value, self->prop.target_percentage);
3423       break;
3424     case PROP_TARGET_USAGE:
3425       g_value_set_uint (value, self->prop.target_usage);
3426       break;
3427     case PROP_RATE_CONTROL:
3428       g_value_set_enum (value, self->prop.rc_ctrl);
3429       break;
3430     case PROP_CPB_SIZE:
3431       g_value_set_uint (value, self->prop.cpb_size);
3432       break;
3433     default:
3434       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3435   }
3436
3437   GST_OBJECT_UNLOCK (self);
3438 }
3439
3440 static void
3441 gst_va_h264_enc_class_init (gpointer g_klass, gpointer class_data)
3442 {
3443   GstCaps *src_doc_caps, *sink_doc_caps;
3444   GstPadTemplate *sink_pad_templ, *src_pad_templ;
3445   GObjectClass *object_class = G_OBJECT_CLASS (g_klass);
3446   GstElementClass *element_class = GST_ELEMENT_CLASS (g_klass);
3447   GstVideoEncoderClass *venc_class = GST_VIDEO_ENCODER_CLASS (g_klass);
3448   GstVaBaseEncClass *va_enc_class = GST_VA_BASE_ENC_CLASS (g_klass);
3449   GstVaH264EncClass *vah264enc_class = GST_VA_H264_ENC_CLASS (g_klass);
3450   GstVaDisplay *display;
3451   GstVaEncoder *encoder;
3452   struct CData *cdata = class_data;
3453   gchar *long_name;
3454   const gchar *name, *desc;
3455   gint n_props = N_PROPERTIES;
3456   GParamFlags param_flags =
3457       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT;
3458
3459   if (cdata->entrypoint == VAEntrypointEncSlice) {
3460     desc = "VA-API based H.264 video encoder";
3461     name = "VA-API H.264 Encoder";
3462   } else {
3463     desc = "VA-API based H.264 low power video encoder";
3464     name = "VA-API H.264 Low Power Encoder";
3465   }
3466
3467   if (cdata->description)
3468     long_name = g_strdup_printf ("%s in %s", name, cdata->description);
3469   else
3470     long_name = g_strdup (name);
3471
3472   gst_element_class_set_metadata (element_class, long_name,
3473       "Codec/Encoder/Video/Hardware", desc, "He Junyan <junyan.he@intel.com>");
3474
3475   sink_doc_caps = gst_caps_from_string (sink_caps_str);
3476   src_doc_caps = gst_caps_from_string (src_caps_str);
3477
3478   parent_class = g_type_class_peek_parent (g_klass);
3479
3480   va_enc_class->codec = H264;
3481   va_enc_class->entrypoint = cdata->entrypoint;
3482   va_enc_class->render_device_path = g_strdup (cdata->render_device_path);
3483
3484   sink_pad_templ = gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
3485       cdata->sink_caps);
3486   gst_element_class_add_pad_template (element_class, sink_pad_templ);
3487
3488   gst_pad_template_set_documentation_caps (sink_pad_templ, sink_doc_caps);
3489   gst_caps_unref (sink_doc_caps);
3490
3491   src_pad_templ = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
3492       cdata->src_caps);
3493   gst_element_class_add_pad_template (element_class, src_pad_templ);
3494
3495   gst_pad_template_set_documentation_caps (src_pad_templ, src_doc_caps);
3496   gst_caps_unref (src_doc_caps);
3497
3498   object_class->set_property = gst_va_h264_enc_set_property;
3499   object_class->get_property = gst_va_h264_enc_get_property;
3500
3501   venc_class->flush = GST_DEBUG_FUNCPTR (gst_va_h264_enc_flush);
3502
3503   va_enc_class->reset_state = GST_DEBUG_FUNCPTR (gst_va_h264_enc_reset_state);
3504   va_enc_class->reconfig = GST_DEBUG_FUNCPTR (gst_va_h264_enc_reconfig);
3505   va_enc_class->new_frame = GST_DEBUG_FUNCPTR (gst_va_h264_enc_new_frame);
3506   va_enc_class->reorder_frame =
3507       GST_DEBUG_FUNCPTR (gst_va_h264_enc_reorder_frame);
3508   va_enc_class->encode_frame = GST_DEBUG_FUNCPTR (gst_va_h264_enc_encode_frame);
3509   va_enc_class->prepare_output =
3510       GST_DEBUG_FUNCPTR (gst_va_h264_enc_prepare_output);
3511
3512   {
3513     display =
3514         gst_va_display_drm_new_from_path (va_enc_class->render_device_path);
3515     encoder = gst_va_encoder_new (display, va_enc_class->codec,
3516         va_enc_class->entrypoint);
3517     if (gst_va_encoder_get_rate_control_enum (encoder,
3518             vah264enc_class->rate_control)) {
3519       gchar *basename = g_path_get_basename (va_enc_class->render_device_path);
3520       g_snprintf (vah264enc_class->rate_control_type_name,
3521           G_N_ELEMENTS (vah264enc_class->rate_control_type_name) - 1,
3522           "GstVaEncoderRateControl_%" GST_FOURCC_FORMAT "%s_%s",
3523           GST_FOURCC_ARGS (va_enc_class->codec),
3524           (va_enc_class->entrypoint == VAEntrypointEncSliceLP) ? "_LP" : "",
3525           basename);
3526       vah264enc_class->rate_control_type =
3527           g_enum_register_static (vah264enc_class->rate_control_type_name,
3528           vah264enc_class->rate_control);
3529       gst_type_mark_as_plugin_api (vah264enc_class->rate_control_type, 0);
3530       g_free (basename);
3531     }
3532     gst_object_unref (encoder);
3533     gst_object_unref (display);
3534   }
3535
3536   g_free (long_name);
3537   g_free (cdata->description);
3538   g_free (cdata->render_device_path);
3539   gst_caps_unref (cdata->src_caps);
3540   gst_caps_unref (cdata->sink_caps);
3541   g_free (cdata);
3542
3543   /**
3544    * GstVaH264Enc:key-int-max:
3545    *
3546    * The maximal distance between two keyframes.
3547    */
3548   properties[PROP_KEY_INT_MAX] = g_param_spec_uint ("key-int-max",
3549       "Key frame maximal interval",
3550       "The maximal distance between two keyframes. It decides the size of GOP"
3551       " (0: auto-calculate)", 0, MAX_GOP_SIZE, 0, param_flags);
3552
3553   /**
3554    * GstVaH264Enc:b-frames:
3555    *
3556    * Number of B-frames between two reference frames.
3557    */
3558   properties[PROP_BFRAMES] = g_param_spec_uint ("b-frames", "B Frames",
3559       "Number of B frames between I and P reference frames", 0, 31, 0,
3560       param_flags);
3561
3562   /**
3563    * GstVaH264Enc:i-frames:
3564    *
3565    * Force the number of i-frames insertion within one GOP.
3566    */
3567   properties[PROP_IFRAMES] = g_param_spec_uint ("i-frames", "I Frames",
3568       "Force the number of I frames insertion within one GOP, not including the "
3569       "first IDR frame", 0, 1023, 0, param_flags);
3570
3571   /**
3572    * GstVaH264Enc:ref-frames:
3573    *
3574    * The number of reference frames.
3575    */
3576   properties[PROP_NUM_REF_FRAMES] = g_param_spec_uint ("ref-frames",
3577       "Number of Reference Frames",
3578       "Number of reference frames, including both the forward and the backward",
3579       0, 16, 3, param_flags);
3580
3581   /**
3582    * GstVaH264Enc:b-pyramid:
3583    *
3584    * Enable the b-pyramid reference structure in GOP.
3585    */
3586   properties[PROP_B_PYRAMID] = g_param_spec_boolean ("b-pyramid", "b pyramid",
3587       "Enable the b-pyramid reference structure in the GOP", FALSE,
3588       param_flags);
3589
3590   /**
3591    * GstVaH264Enc:num-slices:
3592    *
3593    * The number of slices per frame.
3594    */
3595   properties[PROP_NUM_SLICES] = g_param_spec_uint ("num-slices",
3596       "Number of Slices", "Number of slices per frame", 1, 200, 1, param_flags);
3597
3598   /**
3599    * GstVaH264Enc:max-qp:
3600    *
3601    * The maximum quantizer value.
3602    */
3603   properties[PROP_MAX_QP] = g_param_spec_uint ("max-qp", "Maximum QP",
3604       "Maximum quantizer value for each frame", 0, 51, 51, param_flags);
3605
3606   /**
3607    * GstVaH264Enc:min-qp:
3608    *
3609    * The minimum quantizer value.
3610    */
3611   properties[PROP_MIN_QP] = g_param_spec_uint ("min-qp", "Minimum QP",
3612       "Minimum quantizer value for each frame", 0, 51, 1, param_flags);
3613
3614   /**
3615    * GstVaH264Enc:qpi:
3616    *
3617    * The quantizer value for I frame.
3618    *
3619    * In CQP mode, it specifies the QP of I frame, in other mode, it specifies
3620    * the init QP of all frames.
3621    */
3622   properties[PROP_QP_I] = g_param_spec_uint ("qpi", "I Frame QP",
3623       "The quantizer value for I frame. In CQP mode, it specifies the QP of I "
3624       "frame, in other mode, it specifies the init QP of all frames", 0, 51, 26,
3625       param_flags | GST_PARAM_MUTABLE_PLAYING);
3626
3627   /**
3628    * GstVaH264Enc:qpp:
3629    *
3630    * The quantizer value for P frame. Available only in CQP mode.
3631    */
3632   properties[PROP_QP_P] = g_param_spec_uint ("qpp",
3633       "The quantizer value for P frame",
3634       "The quantizer value for P frame. Available only in CQP mode",
3635       0, 51, 26, param_flags | GST_PARAM_MUTABLE_PLAYING);
3636
3637   /**
3638    * GstVaH264Enc:qpb:
3639    *
3640    * The quantizer value for B frame. Available only in CQP mode.
3641    */
3642   properties[PROP_QP_B] = g_param_spec_uint ("qpb",
3643       "The quantizer value for B frame",
3644       "The quantizer value for B frame. Available only in CQP mode",
3645       0, 51, 26, param_flags | GST_PARAM_MUTABLE_PLAYING);
3646
3647   /**
3648    * GstVaH264Enc:dct8x8:
3649    *
3650    * Enable adaptive use of 8x8 transforms in I-frames. This improves
3651    * the compression ratio but requires high profile at least.
3652    */
3653   properties[PROP_DCT8X8] = g_param_spec_boolean ("dct8x8", "Enable 8x8 DCT",
3654       "Enable adaptive use of 8x8 transforms in I-frames", TRUE, param_flags);
3655
3656   /**
3657    * GstVaH264Enc:cabac:
3658    *
3659    * It enables CABAC entropy coding mode to improve compression ratio,
3660    * but requires main profile at least.
3661    */
3662   properties[PROP_CABAC] = g_param_spec_boolean ("cabac", "Enable CABAC",
3663       "Enable CABAC entropy coding mode", TRUE, param_flags);
3664
3665   /**
3666    * GstVaH264Enc:trellis:
3667    *
3668    * It enable the trellis quantization method. Trellis is an improved
3669    * quantization algorithm.
3670    */
3671   properties[PROP_TRELLIS] = g_param_spec_boolean ("trellis", "Enable trellis",
3672       "Enable the trellis quantization method", FALSE, param_flags);
3673
3674   /**
3675    * GstVaH264Enc:aud:
3676    *
3677    * Insert the AU (Access Unit) delimeter for each frame.
3678    */
3679   properties[PROP_AUD] = g_param_spec_boolean ("aud", "Insert AUD",
3680       "Insert AU (Access Unit) delimeter for each frame", FALSE, param_flags);
3681
3682   /**
3683    * GstVaH264Enc:cc-insert:
3684    *
3685    * Closed Caption Insert mode. Only CEA-708 RAW format is supported for now.
3686    */
3687   properties[PROP_CC] = g_param_spec_boolean ("cc-insert",
3688       "Insert Closed Captions",
3689       "Insert CEA-708 Closed Captions",
3690       TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT);
3691
3692   /**
3693    * GstVaH264Enc:mbbrc:
3694    *
3695    * Macroblock level bitrate control. Not available in CQP mode.
3696    */
3697   properties[PROP_MBBRC] = g_param_spec_enum ("mbbrc",
3698       "Macroblock level Bitrate Control",
3699       "Macroblock level Bitrate Control. Not available in CQP mode",
3700       GST_TYPE_VA_FEATURE, GST_VA_FEATURE_AUTO, param_flags);
3701
3702   /**
3703    * GstVaH264Enc:bitrate:
3704    *
3705    * The desired target bitrate, expressed in kbps. Not available in CQP mode.
3706    *
3707    * * **CBR**: This applies equally to the minimum, maximum and target bitrate.
3708    * * **VBR**: This applies to the target bitrate. The driver will use the
3709    *   "target-percentage" together to calculate the minimum and maximum
3710    *   bitrate.
3711    * * **VCM**: This applies to the target bitrate. The minimum and maximum
3712    *   bitrate are not needed.
3713    */
3714   properties[PROP_BITRATE] = g_param_spec_uint ("bitrate", "Bitrate (kbps)",
3715       "The desired bitrate expressed in kbps (0: auto-calculate)",
3716       0, 2000 * 1024, 0, param_flags | GST_PARAM_MUTABLE_PLAYING);
3717
3718   /**
3719    * GstVaH264Enc:target-percentage:
3720    *
3721    * The target percentage of the max bitrate, and expressed in uint, equal to
3722    * "target percentage" * 100. Available only when rate-control is VBR.
3723    *
3724    * "target percentage" = "target bitrate" * 100 /  "max bitrate"
3725    *
3726    * The driver uses it to calculate the minimum and maximum bitrate.
3727    */
3728   properties[PROP_TARGET_PERCENTAGE] = g_param_spec_uint ("target-percentage",
3729       "target bitrate percentage",
3730       "The percentage for 'target bitrate'/'maximum bitrate' (Only in VBR)",
3731       50, 100, 66, param_flags | GST_PARAM_MUTABLE_PLAYING);
3732
3733   /**
3734    * GstVaH264Enc:target-usage:
3735    *
3736    * The target usage of the encoder.
3737    *
3738    * It controls and balances the encoding speed and the encoding quality. The
3739    * lower value has better quality but slower speed, the higher value has
3740    * faster speed but lower quality.
3741    */
3742   properties[PROP_TARGET_USAGE] = g_param_spec_uint ("target-usage",
3743       "target usage",
3744       "The target usage to control and balance the encoding speed/quality",
3745       1, 7, 4, param_flags | GST_PARAM_MUTABLE_PLAYING);
3746
3747   /**
3748    * GstVaH264Enc:cpb-size:
3749    *
3750    * The desired max CPB size in Kb (0: auto-calculate).
3751    */
3752   properties[PROP_CPB_SIZE] = g_param_spec_uint ("cpb-size",
3753       "max CPB size in Kb",
3754       "The desired max CPB size in Kb (0: auto-calculate)", 0, 2000 * 1024, 0,
3755       param_flags | GST_PARAM_MUTABLE_PLAYING);
3756
3757   if (vah264enc_class->rate_control_type > 0) {
3758     properties[PROP_RATE_CONTROL] = g_param_spec_enum ("rate-control",
3759         "rate control mode", "The desired rate control mode for the encoder",
3760         vah264enc_class->rate_control_type,
3761         vah264enc_class->rate_control[0].value,
3762         GST_PARAM_CONDITIONALLY_AVAILABLE | GST_PARAM_MUTABLE_PLAYING
3763         | param_flags);
3764   } else {
3765     n_props--;
3766     properties[PROP_RATE_CONTROL] = NULL;
3767   }
3768
3769   g_object_class_install_properties (object_class, n_props, properties);
3770 }
3771
3772 static GstCaps *
3773 _complete_src_caps (GstCaps * srccaps)
3774 {
3775   GstCaps *caps = gst_caps_copy (srccaps);
3776
3777   gst_caps_set_simple (caps, "alignment", G_TYPE_STRING, "au", "stream-format",
3778       G_TYPE_STRING, "byte-stream", NULL);
3779
3780   return caps;
3781 }
3782
3783 gboolean
3784 gst_va_h264_enc_register (GstPlugin * plugin, GstVaDevice * device,
3785     GstCaps * sink_caps, GstCaps * src_caps, guint rank,
3786     VAEntrypoint entrypoint)
3787 {
3788   static GOnce debug_once = G_ONCE_INIT;
3789   GType type;
3790   GTypeInfo type_info = {
3791     .class_size = sizeof (GstVaH264EncClass),
3792     .class_init = gst_va_h264_enc_class_init,
3793     .instance_size = sizeof (GstVaH264Enc),
3794     .instance_init = gst_va_h264_enc_init,
3795   };
3796   struct CData *cdata;
3797   gboolean ret;
3798   gchar *type_name, *feature_name;
3799
3800   g_return_val_if_fail (GST_IS_PLUGIN (plugin), FALSE);
3801   g_return_val_if_fail (GST_IS_VA_DEVICE (device), FALSE);
3802   g_return_val_if_fail (GST_IS_CAPS (sink_caps), FALSE);
3803   g_return_val_if_fail (GST_IS_CAPS (src_caps), FALSE);
3804   g_return_val_if_fail (entrypoint == VAEntrypointEncSlice ||
3805       entrypoint == VAEntrypointEncSliceLP, FALSE);
3806
3807   cdata = g_new (struct CData, 1);
3808   cdata->entrypoint = entrypoint;
3809   cdata->description = NULL;
3810   cdata->render_device_path = g_strdup (device->render_device_path);
3811   cdata->sink_caps = gst_caps_ref (sink_caps);
3812   cdata->src_caps = _complete_src_caps (src_caps);
3813
3814   /* class data will be leaked if the element never gets instantiated */
3815   GST_MINI_OBJECT_FLAG_SET (cdata->sink_caps,
3816       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
3817   GST_MINI_OBJECT_FLAG_SET (cdata->src_caps,
3818       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
3819
3820   type_info.class_data = cdata;
3821
3822   /* The first encoder to be registered should use a constant name,
3823    * like vah264enc, for any additional encoders, we create unique
3824    * names, using inserting the render device name. */
3825   if (device->index == 0) {
3826     if (entrypoint == VAEntrypointEncSlice) {
3827       type_name = g_strdup ("GstVaH264Enc");
3828       feature_name = g_strdup ("vah264enc");
3829     } else {
3830       type_name = g_strdup ("GstVaH264LPEnc");
3831       feature_name = g_strdup ("vah264lpenc");
3832     }
3833   } else {
3834     gchar *basename = g_path_get_basename (device->render_device_path);
3835     if (entrypoint == VAEntrypointEncSlice) {
3836       type_name = g_strdup_printf ("GstVa%sH264Enc", basename);
3837       feature_name = g_strdup_printf ("va%sh264enc", basename);
3838     } else {
3839       type_name = g_strdup_printf ("GstVa%sH264LPEnc", basename);
3840       feature_name = g_strdup_printf ("va%sh264lpenc", basename);
3841     }
3842     cdata->description = basename;
3843     /* lower rank for non-first device */
3844     if (rank > 0)
3845       rank--;
3846   }
3847
3848   g_once (&debug_once, _register_debug_category, NULL);
3849   type = g_type_register_static (GST_TYPE_VA_BASE_ENC,
3850       type_name, &type_info, 0);
3851   ret = gst_element_register (plugin, feature_name, rank, type);
3852
3853   g_free (type_name);
3854   g_free (feature_name);
3855
3856   return ret;
3857 }