encoder: h264: fix multiple slices support in packed headers mode.
[platform/upstream/gstreamer-vaapi.git] / gst-libs / gst / vaapi / gstvaapiencoder_h264.c
1 /*
2  *  gstvaapiencoder_h264.c - H.264 encoder
3  *
4  *  Copyright (C) 2012-2014 Intel Corporation
5  *    Author: Wind Yuan <feng.yuan@intel.com>
6  *    Author: Gwenole Beauchesne <gwenole.beauchesne@intel.com>
7  *
8  *  This library is free software; you can redistribute it and/or
9  *  modify it under the terms of the GNU Lesser General Public License
10  *  as published by the Free Software Foundation; either version 2.1
11  *  of the License, or (at your option) any later version.
12  *
13  *  This library is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  *  Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public
19  *  License along with this library; if not, write to the Free
20  *  Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  *  Boston, MA 02110-1301 USA
22  */
23
24 #include "sysdeps.h"
25 #include <va/va.h>
26 #include <va/va_enc_h264.h>
27 #include <gst/base/gstbitwriter.h>
28 #include <gst/codecparsers/gsth264parser.h>
29 #include "gstvaapicompat.h"
30 #include "gstvaapiencoder_priv.h"
31 #include "gstvaapiencoder_h264.h"
32 #include "gstvaapiutils_h264.h"
33 #include "gstvaapiutils_h264_priv.h"
34 #include "gstvaapicodedbufferproxy_priv.h"
35 #include "gstvaapisurface.h"
36
37 #define DEBUG 1
38 #include "gstvaapidebug.h"
39
40 /* Define the maximum number of views supported */
41 #define MAX_NUM_VIEWS 2
42
43 /* Define the maximum IDR period */
44 #define MAX_IDR_PERIOD 512
45
46 /* Default CPB length (in milliseconds) */
47 #define DEFAULT_CPB_LENGTH 1500
48
49 /* Scale factor for CPB size (HRD cpb_size_scale: min = 4) */
50 #define SX_CPB_SIZE 4
51
52 /* Scale factor for bitrate (HRD bit_rate_scale: min = 6) */
53 #define SX_BITRATE 6
54
55 /* Define default rate control mode ("constant-qp") */
56 #define DEFAULT_RATECONTROL GST_VAAPI_RATECONTROL_CQP
57
58 /* Supported set of VA rate controls, within this implementation */
59 #define SUPPORTED_RATECONTROLS                          \
60   (GST_VAAPI_RATECONTROL_MASK (CQP)  |                  \
61    GST_VAAPI_RATECONTROL_MASK (CBR)  |                  \
62    GST_VAAPI_RATECONTROL_MASK (VBR)  |                  \
63    GST_VAAPI_RATECONTROL_MASK (VBR_CONSTRAINED))
64
65 /* Supported set of tuning options, within this implementation */
66 #define SUPPORTED_TUNE_OPTIONS                          \
67   (GST_VAAPI_ENCODER_TUNE_MASK (NONE) |                 \
68    GST_VAAPI_ENCODER_TUNE_MASK (HIGH_COMPRESSION))
69
70 /* Supported set of VA packed headers, within this implementation */
71 #define SUPPORTED_PACKED_HEADERS                \
72   (VA_ENC_PACKED_HEADER_SEQUENCE |              \
73    VA_ENC_PACKED_HEADER_PICTURE  |              \
74    VA_ENC_PACKED_HEADER_SLICE    |              \
75    VA_ENC_PACKED_HEADER_RAW_DATA)
76
77 #define GST_H264_NAL_REF_IDC_NONE        0
78 #define GST_H264_NAL_REF_IDC_LOW         1
79 #define GST_H264_NAL_REF_IDC_MEDIUM      2
80 #define GST_H264_NAL_REF_IDC_HIGH        3
81
82 typedef struct
83 {
84   GstVaapiSurfaceProxy *pic;
85   guint poc;
86   guint frame_num;
87 } GstVaapiEncoderH264Ref;
88
89 typedef enum
90 {
91   GST_VAAPI_ENC_H264_REORD_NONE = 0,
92   GST_VAAPI_ENC_H264_REORD_DUMP_FRAMES = 1,
93   GST_VAAPI_ENC_H264_REORD_WAIT_FRAMES = 2
94 } GstVaapiEncH264ReorderState;
95
96 typedef struct _GstVaapiH264ViewRefPool
97 {
98   GQueue ref_list;
99   guint max_ref_frames;
100   guint max_reflist0_count;
101   guint max_reflist1_count;
102 } GstVaapiH264ViewRefPool;
103
104 typedef struct _GstVaapiH264ViewReorderPool
105 {
106   GQueue reorder_frame_list;
107   guint reorder_state;
108   guint frame_index;
109   guint cur_frame_num;
110   guint cur_present_index;
111 } GstVaapiH264ViewReorderPool;
112
113 static inline gboolean
114 _poc_greater_than (guint poc1, guint poc2, guint max_poc)
115 {
116   return (((poc1 - poc2) & (max_poc - 1)) < max_poc / 2);
117 }
118
119 /* Get slice_type value for H.264 specification */
120 static guint8
121 h264_get_slice_type (GstVaapiPictureType type)
122 {
123   switch (type) {
124     case GST_VAAPI_PICTURE_TYPE_I:
125       return GST_H264_I_SLICE;
126     case GST_VAAPI_PICTURE_TYPE_P:
127       return GST_H264_P_SLICE;
128     case GST_VAAPI_PICTURE_TYPE_B:
129       return GST_H264_B_SLICE;
130     default:
131       break;
132   }
133   return -1;
134 }
135
136 /* Get log2_max_frame_num value for H.264 specification */
137 static guint
138 h264_get_log2_max_frame_num (guint num)
139 {
140   guint ret = 0;
141
142   while (num) {
143     ++ret;
144     num >>= 1;
145   }
146   if (ret <= 4)
147     ret = 4;
148   else if (ret > 10)
149     ret = 10;
150   /* must be greater than 4 */
151   return ret;
152 }
153
154 /* Determines the cpbBrNalFactor based on the supplied profile */
155 static guint
156 h264_get_cpb_nal_factor (GstVaapiProfile profile)
157 {
158   guint f;
159
160   /* Table A-2 */
161   switch (profile) {
162     case GST_VAAPI_PROFILE_H264_HIGH:
163       f = 1500;
164       break;
165     case GST_VAAPI_PROFILE_H264_HIGH10:
166       f = 3600;
167       break;
168     case GST_VAAPI_PROFILE_H264_HIGH_422:
169     case GST_VAAPI_PROFILE_H264_HIGH_444:
170       f = 4800;
171       break;
172     default:
173       f = 1200;
174       break;
175   }
176   return f;
177 }
178
179 /* ------------------------------------------------------------------------- */
180 /* --- H.264 Bitstream Writer                                            --- */
181 /* ------------------------------------------------------------------------- */
182
183 #define WRITE_UINT32(bs, val, nbits) do {                       \
184     if (!gst_bit_writer_put_bits_uint32 (bs, val, nbits)) {     \
185       GST_WARNING ("failed to write uint32, nbits: %d", nbits); \
186       goto bs_error;                                            \
187     }                                                           \
188   } while (0)
189
190 #define WRITE_UE(bs, val) do {                  \
191     if (!bs_write_ue (bs, val)) {               \
192       GST_WARNING ("failed to write ue(v)");    \
193       goto bs_error;                            \
194     }                                           \
195   } while (0)
196
197 #define WRITE_SE(bs, val) do {                  \
198     if (!bs_write_se (bs, val)) {               \
199       GST_WARNING ("failed to write se(v)");    \
200       goto bs_error;                            \
201     }                                           \
202   } while (0)
203
204 /* Write an unsigned integer Exp-Golomb-coded syntax element. i.e. ue(v) */
205 static gboolean
206 bs_write_ue (GstBitWriter * bs, guint32 value)
207 {
208   guint32 size_in_bits = 0;
209   guint32 tmp_value = ++value;
210
211   while (tmp_value) {
212     ++size_in_bits;
213     tmp_value >>= 1;
214   }
215   if (size_in_bits > 1
216       && !gst_bit_writer_put_bits_uint32 (bs, 0, size_in_bits - 1))
217     return FALSE;
218   if (!gst_bit_writer_put_bits_uint32 (bs, value, size_in_bits))
219     return FALSE;
220   return TRUE;
221 }
222
223 /* Write a signed integer Exp-Golomb-coded syntax element. i.e. se(v) */
224 static gboolean
225 bs_write_se (GstBitWriter * bs, gint32 value)
226 {
227   guint32 new_val;
228
229   if (value <= 0)
230     new_val = -(value << 1);
231   else
232     new_val = (value << 1) - 1;
233
234   if (!bs_write_ue (bs, new_val))
235     return FALSE;
236   return TRUE;
237 }
238
239 /* Write the NAL unit header */
240 static gboolean
241 bs_write_nal_header (GstBitWriter * bs, guint32 nal_ref_idc,
242     guint32 nal_unit_type)
243 {
244   WRITE_UINT32 (bs, 0, 1);
245   WRITE_UINT32 (bs, nal_ref_idc, 2);
246   WRITE_UINT32 (bs, nal_unit_type, 5);
247   return TRUE;
248
249   /* ERRORS */
250 bs_error:
251   {
252     GST_WARNING ("failed to write NAL unit header");
253     return FALSE;
254   }
255 }
256
257 /* Write the MVC NAL unit header extension */
258 static gboolean
259 bs_write_nal_header_mvc_extension (GstBitWriter * bs,
260     GstVaapiEncPicture * picture, guint32 view_id)
261 {
262   guint32 svc_extension_flag = 0;
263   guint32 non_idr_flag = 1;
264   guint32 priority_id = 0;
265   guint32 temporal_id = 0;
266   guint32 anchor_pic_flag = 0;
267   guint32 inter_view_flag = 0;
268
269   if (GST_VAAPI_ENC_PICTURE_IS_IDR (picture))
270     non_idr_flag = 0;
271
272   if (picture->type == GST_VAAPI_PICTURE_TYPE_I)
273     anchor_pic_flag = 1;
274   /* svc_extension_flag == 0 for mvc stream */
275   WRITE_UINT32 (bs, svc_extension_flag, 1);
276
277   WRITE_UINT32 (bs, non_idr_flag, 1);
278   WRITE_UINT32 (bs, priority_id, 6);
279   WRITE_UINT32 (bs, view_id, 10);
280   WRITE_UINT32 (bs, temporal_id, 3);
281   WRITE_UINT32 (bs, anchor_pic_flag, 1);
282   WRITE_UINT32 (bs, inter_view_flag, 1);
283   WRITE_UINT32 (bs, 1, 1);
284
285   return TRUE;
286
287   /* ERRORS */
288 bs_error:
289   {
290     GST_WARNING ("failed to write NAL unit header");
291     return FALSE;
292   }
293 }
294
295 /* Write the NAL unit trailing bits */
296 static gboolean
297 bs_write_trailing_bits (GstBitWriter * bs)
298 {
299   if (!gst_bit_writer_put_bits_uint32 (bs, 1, 1))
300     goto bs_error;
301   gst_bit_writer_align_bytes_unchecked (bs, 0);
302   return TRUE;
303
304   /* ERRORS */
305 bs_error:
306   {
307     GST_WARNING ("failed to write NAL unit trailing bits");
308     return FALSE;
309   }
310 }
311
312 /* Write an SPS NAL unit */
313 static gboolean
314 bs_write_sps_data (GstBitWriter * bs,
315     const VAEncSequenceParameterBufferH264 * seq_param, GstVaapiProfile profile,
316     const VAEncMiscParameterHRD * hrd_params)
317 {
318   guint8 profile_idc;
319   guint32 constraint_set0_flag, constraint_set1_flag;
320   guint32 constraint_set2_flag, constraint_set3_flag;
321   guint32 gaps_in_frame_num_value_allowed_flag = 0;     // ??
322   gboolean nal_hrd_parameters_present_flag;
323
324   guint32 b_qpprime_y_zero_transform_bypass = 0;
325   guint32 residual_color_transform_flag = 0;
326   guint32 pic_height_in_map_units =
327       (seq_param->seq_fields.bits.frame_mbs_only_flag ?
328       seq_param->picture_height_in_mbs : seq_param->picture_height_in_mbs / 2);
329   guint32 mb_adaptive_frame_field =
330       !seq_param->seq_fields.bits.frame_mbs_only_flag;
331   guint32 i = 0;
332
333   profile_idc = gst_vaapi_utils_h264_get_profile_idc (profile);
334   constraint_set0_flag =        /* A.2.1 (baseline profile constraints) */
335       profile == GST_VAAPI_PROFILE_H264_BASELINE ||
336       profile == GST_VAAPI_PROFILE_H264_CONSTRAINED_BASELINE;
337   constraint_set1_flag =        /* A.2.2 (main profile constraints) */
338       profile == GST_VAAPI_PROFILE_H264_MAIN ||
339       profile == GST_VAAPI_PROFILE_H264_CONSTRAINED_BASELINE;
340   constraint_set2_flag = 0;
341   constraint_set3_flag = 0;
342
343   /* profile_idc */
344   WRITE_UINT32 (bs, profile_idc, 8);
345   /* constraint_set0_flag */
346   WRITE_UINT32 (bs, constraint_set0_flag, 1);
347   /* constraint_set1_flag */
348   WRITE_UINT32 (bs, constraint_set1_flag, 1);
349   /* constraint_set2_flag */
350   WRITE_UINT32 (bs, constraint_set2_flag, 1);
351   /* constraint_set3_flag */
352   WRITE_UINT32 (bs, constraint_set3_flag, 1);
353   /* reserved_zero_4bits */
354   WRITE_UINT32 (bs, 0, 4);
355   /* level_idc */
356   WRITE_UINT32 (bs, seq_param->level_idc, 8);
357   /* seq_parameter_set_id */
358   WRITE_UE (bs, seq_param->seq_parameter_set_id);
359
360   if (profile == GST_VAAPI_PROFILE_H264_HIGH ||
361       profile == GST_VAAPI_PROFILE_H264_MULTIVIEW_HIGH ||
362       profile == GST_VAAPI_PROFILE_H264_STEREO_HIGH) {
363     /* for high profile */
364     /* chroma_format_idc  = 1, 4:2:0 */
365     WRITE_UE (bs, seq_param->seq_fields.bits.chroma_format_idc);
366     if (3 == seq_param->seq_fields.bits.chroma_format_idc) {
367       WRITE_UINT32 (bs, residual_color_transform_flag, 1);
368     }
369     /* bit_depth_luma_minus8 */
370     WRITE_UE (bs, seq_param->bit_depth_luma_minus8);
371     /* bit_depth_chroma_minus8 */
372     WRITE_UE (bs, seq_param->bit_depth_chroma_minus8);
373     /* b_qpprime_y_zero_transform_bypass */
374     WRITE_UINT32 (bs, b_qpprime_y_zero_transform_bypass, 1);
375
376     /* seq_scaling_matrix_present_flag  */
377     g_assert (seq_param->seq_fields.bits.seq_scaling_matrix_present_flag == 0);
378     WRITE_UINT32 (bs,
379         seq_param->seq_fields.bits.seq_scaling_matrix_present_flag, 1);
380
381 #if 0
382     if (seq_param->seq_fields.bits.seq_scaling_matrix_present_flag) {
383       for (i = 0;
384           i < (seq_param->seq_fields.bits.chroma_format_idc != 3 ? 8 : 12);
385           i++) {
386         gst_bit_writer_put_bits_uint8 (bs,
387             seq_param->seq_fields.bits.seq_scaling_list_present_flag, 1);
388         if (seq_param->seq_fields.bits.seq_scaling_list_present_flag) {
389           g_assert (0);
390           /* FIXME, need write scaling list if seq_scaling_matrix_present_flag ==1 */
391         }
392       }
393     }
394 #endif
395   }
396
397   /* log2_max_frame_num_minus4 */
398   WRITE_UE (bs, seq_param->seq_fields.bits.log2_max_frame_num_minus4);
399   /* pic_order_cnt_type */
400   WRITE_UE (bs, seq_param->seq_fields.bits.pic_order_cnt_type);
401
402   if (seq_param->seq_fields.bits.pic_order_cnt_type == 0) {
403     /* log2_max_pic_order_cnt_lsb_minus4 */
404     WRITE_UE (bs, seq_param->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4);
405   } else if (seq_param->seq_fields.bits.pic_order_cnt_type == 1) {
406     g_assert (0 && "only POC type 0 is supported");
407     WRITE_UINT32 (bs,
408         seq_param->seq_fields.bits.delta_pic_order_always_zero_flag, 1);
409     WRITE_SE (bs, seq_param->offset_for_non_ref_pic);
410     WRITE_SE (bs, seq_param->offset_for_top_to_bottom_field);
411     WRITE_UE (bs, seq_param->num_ref_frames_in_pic_order_cnt_cycle);
412     for (i = 0; i < seq_param->num_ref_frames_in_pic_order_cnt_cycle; i++) {
413       WRITE_SE (bs, seq_param->offset_for_ref_frame[i]);
414     }
415   }
416
417   /* num_ref_frames */
418   WRITE_UE (bs, seq_param->max_num_ref_frames);
419   /* gaps_in_frame_num_value_allowed_flag */
420   WRITE_UINT32 (bs, gaps_in_frame_num_value_allowed_flag, 1);
421
422   /* pic_width_in_mbs_minus1 */
423   WRITE_UE (bs, seq_param->picture_width_in_mbs - 1);
424   /* pic_height_in_map_units_minus1 */
425   WRITE_UE (bs, pic_height_in_map_units - 1);
426   /* frame_mbs_only_flag */
427   WRITE_UINT32 (bs, seq_param->seq_fields.bits.frame_mbs_only_flag, 1);
428
429   if (!seq_param->seq_fields.bits.frame_mbs_only_flag) {        //ONLY mbs
430     g_assert (0 && "only progressive frames encoding is supported");
431     WRITE_UINT32 (bs, mb_adaptive_frame_field, 1);
432   }
433
434   /* direct_8x8_inference_flag */
435   WRITE_UINT32 (bs, 0, 1);
436   /* frame_cropping_flag */
437   WRITE_UINT32 (bs, seq_param->frame_cropping_flag, 1);
438
439   if (seq_param->frame_cropping_flag) {
440     /* frame_crop_left_offset */
441     WRITE_UE (bs, seq_param->frame_crop_left_offset);
442     /* frame_crop_right_offset */
443     WRITE_UE (bs, seq_param->frame_crop_right_offset);
444     /* frame_crop_top_offset */
445     WRITE_UE (bs, seq_param->frame_crop_top_offset);
446     /* frame_crop_bottom_offset */
447     WRITE_UE (bs, seq_param->frame_crop_bottom_offset);
448   }
449
450   /* vui_parameters_present_flag */
451   WRITE_UINT32 (bs, seq_param->vui_parameters_present_flag, 1);
452   if (seq_param->vui_parameters_present_flag) {
453     /* aspect_ratio_info_present_flag */
454     WRITE_UINT32 (bs,
455         seq_param->vui_fields.bits.aspect_ratio_info_present_flag, 1);
456     if (seq_param->vui_fields.bits.aspect_ratio_info_present_flag) {
457       WRITE_UINT32 (bs, seq_param->aspect_ratio_idc, 8);
458       if (seq_param->aspect_ratio_idc == 0xFF) {
459         WRITE_UINT32 (bs, seq_param->sar_width, 16);
460         WRITE_UINT32 (bs, seq_param->sar_height, 16);
461       }
462     }
463
464     /* overscan_info_present_flag */
465     WRITE_UINT32 (bs, 0, 1);
466     /* video_signal_type_present_flag */
467     WRITE_UINT32 (bs, 0, 1);
468     /* chroma_loc_info_present_flag */
469     WRITE_UINT32 (bs, 0, 1);
470
471     /* timing_info_present_flag */
472     WRITE_UINT32 (bs, seq_param->vui_fields.bits.timing_info_present_flag, 1);
473     if (seq_param->vui_fields.bits.timing_info_present_flag) {
474       WRITE_UINT32 (bs, seq_param->num_units_in_tick, 32);
475       WRITE_UINT32 (bs, seq_param->time_scale, 32);
476       WRITE_UINT32 (bs, 1, 1);  /* fixed_frame_rate_flag */
477     }
478
479     /* nal_hrd_parameters_present_flag */
480     nal_hrd_parameters_present_flag = seq_param->bits_per_second > 0;
481     nal_hrd_parameters_present_flag = FALSE;    /* XXX: disabled for now */
482     WRITE_UINT32 (bs, nal_hrd_parameters_present_flag, 1);
483     if (nal_hrd_parameters_present_flag) {
484       /* hrd_parameters */
485       /* cpb_cnt_minus1 */
486       WRITE_UE (bs, 0);
487       WRITE_UINT32 (bs, SX_BITRATE - 6, 4);     /* bit_rate_scale */
488       WRITE_UINT32 (bs, SX_CPB_SIZE - 4, 4);    /* cpb_size_scale */
489
490       for (i = 0; i < 1; ++i) {
491         /* bit_rate_value_minus1[0] */
492         WRITE_UE (bs, (seq_param->bits_per_second >> SX_BITRATE) - 1);
493         /* cpb_size_value_minus1[0] */
494         WRITE_UE (bs, (hrd_params->buffer_size >> SX_CPB_SIZE) - 1);
495         /* cbr_flag[0] */
496         WRITE_UINT32 (bs, 1, 1);
497       }
498       /* initial_cpb_removal_delay_length_minus1 */
499       WRITE_UINT32 (bs, 23, 5);
500       /* cpb_removal_delay_length_minus1 */
501       WRITE_UINT32 (bs, 23, 5);
502       /* dpb_output_delay_length_minus1 */
503       WRITE_UINT32 (bs, 23, 5);
504       /* time_offset_length  */
505       WRITE_UINT32 (bs, 23, 5);
506     }
507
508     /* vcl_hrd_parameters_present_flag */
509     WRITE_UINT32 (bs, 0, 1);
510
511     if (nal_hrd_parameters_present_flag
512         || 0 /*vcl_hrd_parameters_present_flag */ ) {
513       /* low_delay_hrd_flag */
514       WRITE_UINT32 (bs, 0, 1);
515     }
516     /* pic_struct_present_flag */
517     WRITE_UINT32 (bs, 0, 1);
518     /* bs_restriction_flag */
519     WRITE_UINT32 (bs, 0, 1);
520   }
521   return TRUE;
522
523   /* ERRORS */
524 bs_error:
525   {
526     GST_WARNING ("failed to write SPS NAL unit");
527     return FALSE;
528   }
529 }
530
531 static gboolean
532 bs_write_sps (GstBitWriter * bs,
533     const VAEncSequenceParameterBufferH264 * seq_param, GstVaapiProfile profile,
534     const VAEncMiscParameterHRD * hrd_params)
535 {
536   if (!bs_write_sps_data (bs, seq_param, profile, hrd_params))
537     return FALSE;
538
539   /* rbsp_trailing_bits */
540   bs_write_trailing_bits (bs);
541
542   return FALSE;
543 }
544
545 static gboolean
546 bs_write_subset_sps (GstBitWriter * bs,
547     const VAEncSequenceParameterBufferH264 * seq_param, GstVaapiProfile profile,
548     guint num_views, const VAEncMiscParameterHRD * hrd_params)
549 {
550   guint32 i, j, k;
551
552   if (!bs_write_sps_data (bs, seq_param, profile, hrd_params))
553     return FALSE;
554
555   if (profile == GST_VAAPI_PROFILE_H264_STEREO_HIGH ||
556       profile == GST_VAAPI_PROFILE_H264_MULTIVIEW_HIGH) {
557     guint32 num_views_minus1, num_level_values_signalled_minus1;
558
559     num_views_minus1 = num_views - 1;
560     g_assert (num_views_minus1 < 1024);
561
562     /* bit equal to one */
563     WRITE_UINT32 (bs, 1, 1);
564
565     WRITE_UE (bs, num_views_minus1);
566
567     for (i = 0; i <= num_views_minus1; i++)
568       WRITE_UE (bs, i);
569
570     for (i = 1; i <= num_views_minus1; i++) {
571       guint32 num_anchor_refs_l0 = 15;
572       WRITE_UE (bs, num_anchor_refs_l0);
573       for (j = 0; j < num_anchor_refs_l0; j++)
574         WRITE_UE (bs, 0);
575
576       guint32 num_anchor_refs_l1 = 15;
577       WRITE_UE (bs, num_anchor_refs_l1);
578       for (j = 0; j < num_anchor_refs_l1; j++)
579         WRITE_UE (bs, 0);
580     }
581
582     for (i = 1; i <= num_views_minus1; i++) {
583       guint num_non_anchor_refs_l0 = 15;
584       WRITE_UE (bs, num_non_anchor_refs_l0);
585       for (j = 0; j < num_non_anchor_refs_l0; j++)
586         WRITE_UE (bs, 0);
587
588       guint num_non_anchor_refs_l1 = 15;
589       WRITE_UE (bs, num_non_anchor_refs_l1);
590       for (j = 0; j < num_non_anchor_refs_l1; j++)
591         WRITE_UE (bs, 0);
592     }
593
594     /* num level values signalled minus1 */
595     num_level_values_signalled_minus1 = 0;
596     g_assert (num_level_values_signalled_minus1 < 64);
597
598     for (i = 0; i <= num_level_values_signalled_minus1; i++) {
599       guint16 num_applicable_ops_minus1 = 0;
600       g_assert (num_applicable_ops_minus1 < 1024);
601
602       WRITE_UINT32 (bs, seq_param->level_idc, 8);
603       WRITE_UE (bs, num_applicable_ops_minus1);
604
605       for (j = 0; j <= num_applicable_ops_minus1; j++) {
606         guint8 temporal_id = 0;
607         guint16 num_target_views_minus1 = 1;
608
609         WRITE_UINT32 (bs, temporal_id, 3);
610         WRITE_UE (bs, num_target_views_minus1);
611
612         for (k = 0; k <= num_target_views_minus1; k++)
613           WRITE_UE (bs, k);
614
615         WRITE_UE (bs, num_views_minus1);
616       }
617     }
618
619     /* mvc_vui_parameters_present_flag */
620     WRITE_UINT32 (bs, 0, 1);
621   }
622
623   /* additional_extension2_flag */
624   WRITE_UINT32 (bs, 0, 1);
625
626   /* rbsp_trailing_bits */
627   bs_write_trailing_bits (bs);
628   return TRUE;
629
630   /* ERRORS */
631 bs_error:
632   {
633     GST_WARNING ("failed to write subset SPS NAL unit");
634     return FALSE;
635   }
636   return FALSE;
637 }
638
639 /* Write a PPS NAL unit */
640 static gboolean
641 bs_write_pps (GstBitWriter * bs,
642     const VAEncPictureParameterBufferH264 * pic_param, GstVaapiProfile profile)
643 {
644   guint32 num_slice_groups_minus1 = 0;
645   guint32 pic_init_qs_minus26 = 0;
646   guint32 redundant_pic_cnt_present_flag = 0;
647
648   /* pic_parameter_set_id */
649   WRITE_UE (bs, pic_param->pic_parameter_set_id);
650   /* seq_parameter_set_id */
651   WRITE_UE (bs, pic_param->seq_parameter_set_id);
652   /* entropy_coding_mode_flag */
653   WRITE_UINT32 (bs, pic_param->pic_fields.bits.entropy_coding_mode_flag, 1);
654   /* pic_order_present_flag */
655   WRITE_UINT32 (bs, pic_param->pic_fields.bits.pic_order_present_flag, 1);
656   /* slice_groups-1 */
657   WRITE_UE (bs, num_slice_groups_minus1);
658
659   if (num_slice_groups_minus1 > 0) {
660      /*FIXME*/ g_assert (0 && "unsupported arbitrary slice ordering (ASO)");
661   }
662   WRITE_UE (bs, pic_param->num_ref_idx_l0_active_minus1);
663   WRITE_UE (bs, pic_param->num_ref_idx_l1_active_minus1);
664   WRITE_UINT32 (bs, pic_param->pic_fields.bits.weighted_pred_flag, 1);
665   WRITE_UINT32 (bs, pic_param->pic_fields.bits.weighted_bipred_idc, 2);
666   /* pic_init_qp_minus26 */
667   WRITE_SE (bs, pic_param->pic_init_qp - 26);
668   /* pic_init_qs_minus26 */
669   WRITE_SE (bs, pic_init_qs_minus26);
670   /* chroma_qp_index_offset */
671   WRITE_SE (bs, pic_param->chroma_qp_index_offset);
672
673   WRITE_UINT32 (bs,
674       pic_param->pic_fields.bits.deblocking_filter_control_present_flag, 1);
675   WRITE_UINT32 (bs, pic_param->pic_fields.bits.constrained_intra_pred_flag, 1);
676   WRITE_UINT32 (bs, redundant_pic_cnt_present_flag, 1);
677
678   /* more_rbsp_data */
679   if (profile == GST_VAAPI_PROFILE_H264_HIGH) {
680     WRITE_UINT32 (bs, pic_param->pic_fields.bits.transform_8x8_mode_flag, 1);
681     WRITE_UINT32 (bs,
682         pic_param->pic_fields.bits.pic_scaling_matrix_present_flag, 1);
683     if (pic_param->pic_fields.bits.pic_scaling_matrix_present_flag) {
684       g_assert (0 && "unsupported scaling lists");
685       /* FIXME */
686       /*
687          for (i = 0; i <
688          (6+(-( (chroma_format_idc ! = 3) ? 2 : 6) * -pic_param->pic_fields.bits.transform_8x8_mode_flag));
689          i++) {
690          gst_bit_writer_put_bits_uint8(bs, pic_param->pic_fields.bits.pic_scaling_list_present_flag, 1);
691          }
692        */
693     }
694     WRITE_SE (bs, pic_param->second_chroma_qp_index_offset);
695   }
696
697   /* rbsp_trailing_bits */
698   bs_write_trailing_bits (bs);
699   return TRUE;
700
701   /* ERRORS */
702 bs_error:
703   {
704     GST_WARNING ("failed to write PPS NAL unit");
705     return FALSE;
706   }
707 }
708
709 /* ------------------------------------------------------------------------- */
710 /* --- H.264 Encoder                                                     --- */
711 /* ------------------------------------------------------------------------- */
712
713 #define GST_VAAPI_ENCODER_H264_CAST(encoder) \
714     ((GstVaapiEncoderH264 *)(encoder))
715
716 struct _GstVaapiEncoderH264
717 {
718   GstVaapiEncoder parent_instance;
719
720   GstVaapiProfile profile;
721   GstVaapiLevelH264 level;
722   guint8 profile_idc;
723   guint8 max_profile_idc;
724   guint8 hw_max_profile_idc;
725   guint8 level_idc;
726   guint32 idr_period;
727   guint32 init_qp;
728   guint32 min_qp;
729   guint32 num_slices;
730   guint32 num_bframes;
731   guint32 mb_width;
732   guint32 mb_height;
733   gboolean use_cabac;
734   gboolean use_dct8x8;
735   GstClockTime cts_offset;
736
737   /* frame, poc */
738   guint32 max_frame_num;
739   guint32 log2_max_frame_num;
740   guint32 max_pic_order_cnt;
741   guint32 log2_max_pic_order_cnt;
742   guint32 idr_num;
743   guint8 pic_order_cnt_type;
744   guint8 delta_pic_order_always_zero_flag;
745
746   GstBuffer *sps_data;
747   GstBuffer *subset_sps_data;
748   GstBuffer *pps_data;
749
750   guint bitrate_bits;           // bitrate (bits)
751   guint cpb_length;             // length of CPB buffer (ms)
752   guint cpb_length_bits;        // length of CPB buffer (bits)
753
754   /* MVC */
755   gboolean is_mvc;
756   guint32 view_idx;
757   guint32 num_views;
758   GstVaapiH264ViewRefPool ref_pools[MAX_NUM_VIEWS];
759   GstVaapiH264ViewReorderPool reorder_pools[MAX_NUM_VIEWS];
760 };
761
762 /* Write a Slice NAL unit */
763 static gboolean
764 bs_write_slice (GstBitWriter * bs,
765     const VAEncSliceParameterBufferH264 * slice_param,
766     GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
767 {
768   const VAEncPictureParameterBufferH264 *const pic_param = picture->param;
769   guint32 field_pic_flag = 0;
770   guint32 ref_pic_list_modification_flag_l0 = 0;
771   guint32 ref_pic_list_modification_flag_l1 = 0;
772   guint32 no_output_of_prior_pics_flag = 0;
773   guint32 long_term_reference_flag = 0;
774   guint32 adaptive_ref_pic_marking_mode_flag = 0;
775
776   /* first_mb_in_slice */
777   WRITE_UE (bs, slice_param->macroblock_address);
778   /* slice_type */
779   WRITE_UE (bs, slice_param->slice_type);
780   /* pic_parameter_set_id */
781   WRITE_UE (bs, slice_param->pic_parameter_set_id);
782   /* frame_num */
783   WRITE_UINT32 (bs, picture->frame_num, encoder->log2_max_frame_num);
784
785   /* XXX: only frames (i.e. non-interlaced) are supported for now */
786   /* frame_mbs_only_flag == 0 */
787
788   /* idr_pic_id */
789   if (GST_VAAPI_ENC_PICTURE_IS_IDR (picture))
790     WRITE_UE (bs, slice_param->idr_pic_id);
791
792   /* XXX: only POC type 0 is supported */
793   if (!encoder->pic_order_cnt_type) {
794     WRITE_UINT32 (bs, slice_param->pic_order_cnt_lsb,
795         encoder->log2_max_pic_order_cnt);
796     /* bottom_field_pic_order_in_frame_present_flag is FALSE */
797     if (pic_param->pic_fields.bits.pic_order_present_flag && !field_pic_flag)
798       WRITE_SE (bs, slice_param->delta_pic_order_cnt_bottom);
799   } else if (encoder->pic_order_cnt_type == 1 &&
800       !encoder->delta_pic_order_always_zero_flag) {
801     WRITE_SE (bs, slice_param->delta_pic_order_cnt[0]);
802     if (pic_param->pic_fields.bits.pic_order_present_flag && !field_pic_flag)
803       WRITE_SE (bs, slice_param->delta_pic_order_cnt[1]);
804   }
805   /* redundant_pic_cnt_present_flag is FALSE, no redundant coded pictures */
806
807   /* only works for B-frames */
808   if (slice_param->slice_type == 1)
809     WRITE_UINT32 (bs, slice_param->direct_spatial_mv_pred_flag, 1);
810
811   /* not supporting SP slices */
812   if (slice_param->slice_type == 0 || slice_param->slice_type == 1) {
813     WRITE_UINT32 (bs, slice_param->num_ref_idx_active_override_flag, 1);
814     if (slice_param->num_ref_idx_active_override_flag) {
815       WRITE_UE (bs, slice_param->num_ref_idx_l0_active_minus1);
816       if (slice_param->slice_type == 1)
817         WRITE_UE (bs, slice_param->num_ref_idx_l1_active_minus1);
818     }
819   }
820   /* XXX: not supporting custom reference picture list modifications */
821   if ((slice_param->slice_type != 2) && (slice_param->slice_type != 4))
822     WRITE_UINT32 (bs, ref_pic_list_modification_flag_l0, 1);
823   if (slice_param->slice_type == 1)
824     WRITE_UINT32 (bs, ref_pic_list_modification_flag_l1, 1);
825
826   /* we have: weighted_pred_flag == FALSE and */
827   /*        : weighted_bipred_idc == FALSE */
828   if ((pic_param->pic_fields.bits.weighted_pred_flag &&
829           (slice_param->slice_type == 0)) ||
830       ((pic_param->pic_fields.bits.weighted_bipred_idc == 1) &&
831           (slice_param->slice_type == 1))) {
832     /* XXXX: add pred_weight_table() */
833   }
834
835   /* dec_ref_pic_marking() */
836   if (slice_param->slice_type == 0 || slice_param->slice_type == 2) {
837     if (GST_VAAPI_ENC_PICTURE_IS_IDR (picture)) {
838       /* no_output_of_prior_pics_flag = 0 */
839       WRITE_UINT32 (bs, no_output_of_prior_pics_flag, 1);
840       /* long_term_reference_flag = 0 */
841       WRITE_UINT32 (bs, long_term_reference_flag, 1);
842     } else {
843       /* only sliding_window reference picture marking mode is supported */
844       /* adpative_ref_pic_marking_mode_flag = 0 */
845       WRITE_UINT32 (bs, adaptive_ref_pic_marking_mode_flag, 1);
846     }
847   }
848
849   /* cabac_init_idc */
850   if (pic_param->pic_fields.bits.entropy_coding_mode_flag &&
851       slice_param->slice_type != 2)
852     WRITE_UE (bs, slice_param->cabac_init_idc);
853   /*slice_qp_delta */
854   WRITE_SE (bs, slice_param->slice_qp_delta);
855
856   /* XXX: only supporting I, P and B type slices */
857   /* no sp_for_switch_flag and no slice_qs_delta */
858
859   if (pic_param->pic_fields.bits.deblocking_filter_control_present_flag) {
860     /* disable_deblocking_filter_idc */
861     WRITE_UE (bs, slice_param->disable_deblocking_filter_idc);
862     if (slice_param->disable_deblocking_filter_idc != 1) {
863       WRITE_SE (bs, slice_param->slice_alpha_c0_offset_div2);
864       WRITE_SE (bs, slice_param->slice_beta_offset_div2);
865     }
866   }
867
868   /* XXX: unsupported arbitrary slice ordering (ASO) */
869   /* num_slic_groups_minus1 should be zero */
870   return TRUE;
871
872   /* ERRORS */
873 bs_error:
874   {
875     GST_WARNING ("failed to write Slice NAL unit");
876     return FALSE;
877   }
878 }
879
880 static inline void
881 _check_sps_pps_status (GstVaapiEncoderH264 * encoder,
882     const guint8 * nal, guint32 size)
883 {
884   guint8 nal_type;
885   gsize ret;
886   gboolean has_subset_sps;
887
888   g_assert (size);
889
890   has_subset_sps = !encoder->is_mvc || (encoder->subset_sps_data != NULL);
891   if (encoder->sps_data && encoder->pps_data && has_subset_sps)
892     return;
893
894   nal_type = nal[0] & 0x1F;
895   switch (nal_type) {
896     case GST_H264_NAL_SPS:
897       encoder->sps_data = gst_buffer_new_allocate (NULL, size, NULL);
898       ret = gst_buffer_fill (encoder->sps_data, 0, nal, size);
899       g_assert (ret == size);
900       break;
901     case GST_H264_NAL_SUBSET_SPS:
902       encoder->subset_sps_data = gst_buffer_new_allocate (NULL, size, NULL);
903       ret = gst_buffer_fill (encoder->subset_sps_data, 0, nal, size);
904       g_assert (ret == size);
905       break;
906     case GST_H264_NAL_PPS:
907       encoder->pps_data = gst_buffer_new_allocate (NULL, size, NULL);
908       ret = gst_buffer_fill (encoder->pps_data, 0, nal, size);
909       g_assert (ret == size);
910       break;
911     default:
912       break;
913   }
914 }
915
916 /* Determines the largest supported profile by the underlying hardware */
917 static gboolean
918 ensure_hw_profile_limits (GstVaapiEncoderH264 * encoder)
919 {
920   GstVaapiDisplay *const display = GST_VAAPI_ENCODER_DISPLAY (encoder);
921   GArray *profiles;
922   guint i, profile_idc, max_profile_idc;
923
924   if (encoder->hw_max_profile_idc)
925     return TRUE;
926
927   profiles = gst_vaapi_display_get_encode_profiles (display);
928   if (!profiles)
929     return FALSE;
930
931   max_profile_idc = 0;
932   for (i = 0; i < profiles->len; i++) {
933     const GstVaapiProfile profile =
934         g_array_index (profiles, GstVaapiProfile, i);
935     profile_idc = gst_vaapi_utils_h264_get_profile_idc (profile);
936     if (!profile_idc)
937       continue;
938     if (max_profile_idc < profile_idc)
939       max_profile_idc = profile_idc;
940   }
941   g_array_unref (profiles);
942
943   encoder->hw_max_profile_idc = max_profile_idc;
944   return TRUE;
945 }
946
947 /* Derives the profile supported by the underlying hardware */
948 static gboolean
949 ensure_hw_profile (GstVaapiEncoderH264 * encoder)
950 {
951   GstVaapiDisplay *const display = GST_VAAPI_ENCODER_DISPLAY (encoder);
952   GstVaapiEntrypoint entrypoint = GST_VAAPI_ENTRYPOINT_SLICE_ENCODE;
953   GstVaapiProfile profile, profiles[4];
954   guint i, num_profiles = 0;
955
956   profiles[num_profiles++] = encoder->profile;
957   switch (encoder->profile) {
958     case GST_VAAPI_PROFILE_H264_CONSTRAINED_BASELINE:
959       profiles[num_profiles++] = GST_VAAPI_PROFILE_H264_BASELINE;
960       profiles[num_profiles++] = GST_VAAPI_PROFILE_H264_MAIN;
961       // fall-through
962     case GST_VAAPI_PROFILE_H264_MAIN:
963       profiles[num_profiles++] = GST_VAAPI_PROFILE_H264_HIGH;
964       break;
965     default:
966       break;
967   }
968
969   profile = GST_VAAPI_PROFILE_UNKNOWN;
970   for (i = 0; i < num_profiles; i++) {
971     if (gst_vaapi_display_has_encoder (display, profiles[i], entrypoint)) {
972       profile = profiles[i];
973       break;
974     }
975   }
976   if (profile == GST_VAAPI_PROFILE_UNKNOWN)
977     goto error_unsupported_profile;
978
979   GST_VAAPI_ENCODER_CAST (encoder)->profile = profile;
980   return TRUE;
981
982   /* ERRORS */
983 error_unsupported_profile:
984   {
985     GST_ERROR ("unsupported HW profile (0x%08x)", encoder->profile);
986     return FALSE;
987   }
988 }
989
990 /* Check target decoder constraints */
991 static gboolean
992 ensure_profile_limits (GstVaapiEncoderH264 * encoder)
993 {
994   GstVaapiProfile profile;
995
996   if (!encoder->max_profile_idc
997       || encoder->profile_idc <= encoder->max_profile_idc)
998     return TRUE;
999
1000   GST_WARNING ("lowering coding tools to meet target decoder constraints");
1001
1002   /* Try Main profile coding tools */
1003   if (encoder->max_profile_idc < 100) {
1004     encoder->use_dct8x8 = FALSE;
1005     profile = GST_VAAPI_PROFILE_H264_MAIN;
1006   }
1007
1008   /* Try Constrained Baseline profile coding tools */
1009   if (encoder->max_profile_idc < 77) {
1010     encoder->num_bframes = 0;
1011     encoder->use_cabac = FALSE;
1012     profile = GST_VAAPI_PROFILE_H264_CONSTRAINED_BASELINE;
1013   }
1014
1015   encoder->profile = profile;
1016   encoder->profile_idc = encoder->max_profile_idc;
1017   return TRUE;
1018 }
1019
1020 /* Derives the minimum profile from the active coding tools */
1021 static gboolean
1022 ensure_profile (GstVaapiEncoderH264 * encoder)
1023 {
1024   GstVaapiProfile profile;
1025
1026   /* Always start from "constrained-baseline" profile for maximum
1027      compatibility */
1028   profile = GST_VAAPI_PROFILE_H264_CONSTRAINED_BASELINE;
1029
1030   /* Main profile coding tools */
1031   if (encoder->num_bframes > 0 || encoder->use_cabac)
1032     profile = GST_VAAPI_PROFILE_H264_MAIN;
1033
1034   /* High profile coding tools */
1035   if (encoder->use_dct8x8)
1036     profile = GST_VAAPI_PROFILE_H264_HIGH;
1037
1038   /* MVC profiles coding tools */
1039   if (encoder->num_views == 2)
1040     profile = GST_VAAPI_PROFILE_H264_STEREO_HIGH;
1041   else if (encoder->num_views > 2)
1042     profile = GST_VAAPI_PROFILE_H264_MULTIVIEW_HIGH;
1043
1044   encoder->profile = profile;
1045   encoder->profile_idc = gst_vaapi_utils_h264_get_profile_idc (profile);
1046   return TRUE;
1047 }
1048
1049 /* Derives the level from the currently set limits */
1050 static gboolean
1051 ensure_level (GstVaapiEncoderH264 * encoder)
1052 {
1053   const guint cpb_factor = h264_get_cpb_nal_factor (encoder->profile);
1054   const GstVaapiH264LevelLimits *limits_table;
1055   guint i, num_limits, PicSizeMbs, MaxDpbMbs, MaxMBPS;
1056
1057   PicSizeMbs = encoder->mb_width * encoder->mb_height;
1058   MaxDpbMbs = PicSizeMbs * ((encoder->num_bframes) ? 2 : 1);
1059   MaxMBPS = gst_util_uint64_scale_int_ceil (PicSizeMbs,
1060       GST_VAAPI_ENCODER_FPS_N (encoder), GST_VAAPI_ENCODER_FPS_D (encoder));
1061
1062   limits_table = gst_vaapi_utils_h264_get_level_limits_table (&num_limits);
1063   for (i = 0; i < num_limits; i++) {
1064     const GstVaapiH264LevelLimits *const limits = &limits_table[i];
1065     if (PicSizeMbs <= limits->MaxFS &&
1066         MaxDpbMbs <= limits->MaxDpbMbs &&
1067         MaxMBPS <= limits->MaxMBPS && (!encoder->bitrate_bits
1068             || encoder->bitrate_bits <= (limits->MaxBR * cpb_factor)) &&
1069         (!encoder->cpb_length_bits ||
1070             encoder->cpb_length_bits <= (limits->MaxCPB * cpb_factor)))
1071       break;
1072   }
1073   if (i == num_limits)
1074     goto error_unsupported_level;
1075
1076   encoder->level = limits_table[i].level;
1077   encoder->level_idc = limits_table[i].level_idc;
1078   return TRUE;
1079
1080   /* ERRORS */
1081 error_unsupported_level:
1082   {
1083     GST_ERROR ("failed to find a suitable level matching codec config");
1084     return FALSE;
1085   }
1086 }
1087
1088 /* Enable "high-compression" tuning options */
1089 static gboolean
1090 ensure_tuning_high_compression (GstVaapiEncoderH264 * encoder)
1091 {
1092   guint8 profile_idc;
1093
1094   if (!ensure_hw_profile_limits (encoder))
1095     return FALSE;
1096
1097   profile_idc = encoder->hw_max_profile_idc;
1098   if (encoder->max_profile_idc && encoder->max_profile_idc < profile_idc)
1099     profile_idc = encoder->max_profile_idc;
1100
1101   /* Tuning options to enable Main profile */
1102   if (profile_idc >= 77 && profile_idc != 88) {
1103     encoder->use_cabac = TRUE;
1104     if (!encoder->num_bframes)
1105       encoder->num_bframes = 1;
1106   }
1107
1108   /* Tuning options to enable High profile */
1109   if (profile_idc >= 100) {
1110     encoder->use_dct8x8 = TRUE;
1111   }
1112   return TRUE;
1113 }
1114
1115 /* Ensure tuning options */
1116 static gboolean
1117 ensure_tuning (GstVaapiEncoderH264 * encoder)
1118 {
1119   gboolean success;
1120
1121   switch (GST_VAAPI_ENCODER_TUNE (encoder)) {
1122     case GST_VAAPI_ENCODER_TUNE_HIGH_COMPRESSION:
1123       success = ensure_tuning_high_compression (encoder);
1124       break;
1125     default:
1126       success = TRUE;
1127       break;
1128   }
1129   return success;
1130 }
1131
1132 /* Handle new GOP starts */
1133 static void
1134 reset_gop_start (GstVaapiEncoderH264 * encoder)
1135 {
1136   GstVaapiH264ViewReorderPool *const reorder_pool =
1137       &encoder->reorder_pools[encoder->view_idx];
1138
1139   reorder_pool->frame_index = 1;
1140   reorder_pool->cur_frame_num = 0;
1141   reorder_pool->cur_present_index = 0;
1142   ++encoder->idr_num;
1143 }
1144
1145 /* Marks the supplied picture as a B-frame */
1146 static void
1147 set_b_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1148 {
1149   GstVaapiH264ViewReorderPool *const reorder_pool =
1150       &encoder->reorder_pools[encoder->view_idx];
1151
1152   g_assert (pic && encoder);
1153   g_return_if_fail (pic->type == GST_VAAPI_PICTURE_TYPE_NONE);
1154   pic->type = GST_VAAPI_PICTURE_TYPE_B;
1155   pic->frame_num = (reorder_pool->cur_frame_num % encoder->max_frame_num);
1156 }
1157
1158 /* Marks the supplied picture as a P-frame */
1159 static void
1160 set_p_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1161 {
1162   GstVaapiH264ViewReorderPool *const reorder_pool =
1163       &encoder->reorder_pools[encoder->view_idx];
1164
1165   g_return_if_fail (pic->type == GST_VAAPI_PICTURE_TYPE_NONE);
1166   pic->type = GST_VAAPI_PICTURE_TYPE_P;
1167   pic->frame_num = (reorder_pool->cur_frame_num % encoder->max_frame_num);
1168 }
1169
1170 /* Marks the supplied picture as an I-frame */
1171 static void
1172 set_i_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1173 {
1174   GstVaapiH264ViewReorderPool *const reorder_pool =
1175       &encoder->reorder_pools[encoder->view_idx];
1176
1177   g_return_if_fail (pic->type == GST_VAAPI_PICTURE_TYPE_NONE);
1178   pic->type = GST_VAAPI_PICTURE_TYPE_I;
1179   pic->frame_num = (reorder_pool->cur_frame_num % encoder->max_frame_num);
1180
1181   g_assert (pic->frame);
1182   GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (pic->frame);
1183 }
1184
1185 /* Marks the supplied picture as an IDR frame */
1186 static void
1187 set_idr_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1188 {
1189   g_return_if_fail (pic->type == GST_VAAPI_PICTURE_TYPE_NONE);
1190   pic->type = GST_VAAPI_PICTURE_TYPE_I;
1191   pic->frame_num = 0;
1192   pic->poc = 0;
1193   GST_VAAPI_ENC_PICTURE_FLAG_SET (pic, GST_VAAPI_ENC_PICTURE_FLAG_IDR);
1194
1195   g_assert (pic->frame);
1196   GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (pic->frame);
1197 }
1198
1199 /* Marks the supplied picture a a key-frame */
1200 static void
1201 set_key_frame (GstVaapiEncPicture * picture,
1202     GstVaapiEncoderH264 * encoder, gboolean is_idr)
1203 {
1204   if (is_idr) {
1205     reset_gop_start (encoder);
1206     set_idr_frame (picture, encoder);
1207   } else
1208     set_i_frame (picture, encoder);
1209 }
1210
1211 /* Fills in VA HRD parameters */
1212 static void
1213 fill_hrd_params (GstVaapiEncoderH264 * encoder, VAEncMiscParameterHRD * hrd)
1214 {
1215   if (encoder->bitrate_bits > 0) {
1216     hrd->buffer_size = encoder->cpb_length_bits;
1217     hrd->initial_buffer_fullness = hrd->buffer_size / 2;
1218   } else {
1219     hrd->buffer_size = 0;
1220     hrd->initial_buffer_fullness = 0;
1221   }
1222 }
1223
1224 /* Adds the supplied sequence header (SPS) to the list of packed
1225    headers to pass down as-is to the encoder */
1226 static gboolean
1227 add_packed_sequence_header (GstVaapiEncoderH264 * encoder,
1228     GstVaapiEncPicture * picture, GstVaapiEncSequence * sequence)
1229 {
1230   GstVaapiEncPackedHeader *packed_seq;
1231   GstBitWriter bs;
1232   VAEncPackedHeaderParameterBuffer packed_seq_param = { 0 };
1233   const VAEncSequenceParameterBufferH264 *const seq_param = sequence->param;
1234   GstVaapiProfile profile = encoder->profile;
1235
1236   VAEncMiscParameterHRD hrd_params;
1237   guint32 data_bit_size;
1238   guint8 *data;
1239
1240   fill_hrd_params (encoder, &hrd_params);
1241
1242   gst_bit_writer_init (&bs, 128 * 8);
1243   WRITE_UINT32 (&bs, 0x00000001, 32);   /* start code */
1244   bs_write_nal_header (&bs, GST_H264_NAL_REF_IDC_HIGH, GST_H264_NAL_SPS);
1245
1246   /* Set High profile for encoding the MVC base view. Otherwise, some
1247      traditional decoder cannot recognize MVC profile streams with
1248      only the base view in there */
1249   if (profile == GST_VAAPI_PROFILE_H264_MULTIVIEW_HIGH ||
1250       profile == GST_VAAPI_PROFILE_H264_STEREO_HIGH)
1251     profile = GST_VAAPI_PROFILE_H264_HIGH;
1252
1253   bs_write_sps (&bs, seq_param, profile, &hrd_params);
1254
1255   g_assert (GST_BIT_WRITER_BIT_SIZE (&bs) % 8 == 0);
1256   data_bit_size = GST_BIT_WRITER_BIT_SIZE (&bs);
1257   data = GST_BIT_WRITER_DATA (&bs);
1258
1259   packed_seq_param.type = VAEncPackedHeaderSequence;
1260   packed_seq_param.bit_length = data_bit_size;
1261   packed_seq_param.has_emulation_bytes = 0;
1262
1263   packed_seq = gst_vaapi_enc_packed_header_new (GST_VAAPI_ENCODER (encoder),
1264       &packed_seq_param, sizeof (packed_seq_param),
1265       data, (data_bit_size + 7) / 8);
1266   g_assert (packed_seq);
1267
1268   gst_vaapi_enc_picture_add_packed_header (picture, packed_seq);
1269   gst_vaapi_codec_object_replace (&packed_seq, NULL);
1270
1271   /* store sps data */
1272   _check_sps_pps_status (encoder, data + 4, data_bit_size / 8 - 4);
1273   gst_bit_writer_clear (&bs, TRUE);
1274   return TRUE;
1275
1276   /* ERRORS */
1277 bs_error:
1278   {
1279     GST_WARNING ("failed to write SPS NAL unit");
1280     gst_bit_writer_clear (&bs, TRUE);
1281     return FALSE;
1282   }
1283 }
1284
1285 static gboolean
1286 add_packed_sequence_header_mvc (GstVaapiEncoderH264 * encoder,
1287     GstVaapiEncPicture * picture, GstVaapiEncSequence * sequence)
1288 {
1289   GstVaapiEncPackedHeader *packed_seq;
1290   GstBitWriter bs;
1291   VAEncPackedHeaderParameterBuffer packed_header_param_buffer = { 0 };
1292   const VAEncSequenceParameterBufferH264 *const seq_param = sequence->param;
1293   VAEncMiscParameterHRD hrd_params;
1294   guint32 data_bit_size;
1295   guint8 *data;
1296
1297   fill_hrd_params (encoder, &hrd_params);
1298
1299   /* non-base layer, pack one subset sps */
1300   gst_bit_writer_init (&bs, 128 * 8);
1301   WRITE_UINT32 (&bs, 0x00000001, 32);   /* start code */
1302   bs_write_nal_header (&bs, GST_H264_NAL_REF_IDC_HIGH, GST_H264_NAL_SUBSET_SPS);
1303
1304   bs_write_subset_sps (&bs, seq_param, encoder->profile, encoder->num_views,
1305       &hrd_params);
1306
1307   g_assert (GST_BIT_WRITER_BIT_SIZE (&bs) % 8 == 0);
1308   data_bit_size = GST_BIT_WRITER_BIT_SIZE (&bs);
1309   data = GST_BIT_WRITER_DATA (&bs);
1310
1311   packed_header_param_buffer.type = VAEncPackedHeaderSequence;
1312   packed_header_param_buffer.bit_length = data_bit_size;
1313   packed_header_param_buffer.has_emulation_bytes = 0;
1314
1315   packed_seq = gst_vaapi_enc_packed_header_new (GST_VAAPI_ENCODER (encoder),
1316       &packed_header_param_buffer, sizeof (packed_header_param_buffer),
1317       data, (data_bit_size + 7) / 8);
1318   g_assert (packed_seq);
1319
1320   gst_vaapi_enc_picture_add_packed_header (picture, packed_seq);
1321   gst_vaapi_mini_object_replace ((GstVaapiMiniObject **) & packed_seq, NULL);
1322
1323   /* store subset sps data */
1324   _check_sps_pps_status (encoder, data + 4, data_bit_size / 8 - 4);
1325   gst_bit_writer_clear (&bs, TRUE);
1326   return TRUE;
1327
1328   /* ERRORS */
1329 bs_error:
1330   {
1331     GST_WARNING ("failed to write SPS NAL unit");
1332     gst_bit_writer_clear (&bs, TRUE);
1333     return FALSE;
1334   }
1335 }
1336
1337 /* Adds the supplied picture header (PPS) to the list of packed
1338    headers to pass down as-is to the encoder */
1339 static gboolean
1340 add_packed_picture_header (GstVaapiEncoderH264 * encoder,
1341     GstVaapiEncPicture * picture)
1342 {
1343   GstVaapiEncPackedHeader *packed_pic;
1344   GstBitWriter bs;
1345   VAEncPackedHeaderParameterBuffer packed_pic_param = { 0 };
1346   const VAEncPictureParameterBufferH264 *const pic_param = picture->param;
1347   guint32 data_bit_size;
1348   guint8 *data;
1349
1350   gst_bit_writer_init (&bs, 128 * 8);
1351   WRITE_UINT32 (&bs, 0x00000001, 32);   /* start code */
1352   bs_write_nal_header (&bs, GST_H264_NAL_REF_IDC_HIGH, GST_H264_NAL_PPS);
1353   bs_write_pps (&bs, pic_param, encoder->profile);
1354   g_assert (GST_BIT_WRITER_BIT_SIZE (&bs) % 8 == 0);
1355   data_bit_size = GST_BIT_WRITER_BIT_SIZE (&bs);
1356   data = GST_BIT_WRITER_DATA (&bs);
1357
1358   packed_pic_param.type = VAEncPackedHeaderPicture;
1359   packed_pic_param.bit_length = data_bit_size;
1360   packed_pic_param.has_emulation_bytes = 0;
1361
1362   packed_pic = gst_vaapi_enc_packed_header_new (GST_VAAPI_ENCODER (encoder),
1363       &packed_pic_param, sizeof (packed_pic_param),
1364       data, (data_bit_size + 7) / 8);
1365   g_assert (packed_pic);
1366
1367   gst_vaapi_enc_picture_add_packed_header (picture, packed_pic);
1368   gst_vaapi_codec_object_replace (&packed_pic, NULL);
1369
1370   /* store pps data */
1371   _check_sps_pps_status (encoder, data + 4, data_bit_size / 8 - 4);
1372   gst_bit_writer_clear (&bs, TRUE);
1373   return TRUE;
1374
1375   /* ERRORS */
1376 bs_error:
1377   {
1378     GST_WARNING ("failed to write PPS NAL unit");
1379     gst_bit_writer_clear (&bs, TRUE);
1380     return FALSE;
1381   }
1382 }
1383
1384 static gboolean
1385 get_nal_hdr_attributes (GstVaapiEncPicture * picture,
1386     guint8 * nal_ref_idc, guint8 * nal_unit_type)
1387 {
1388   switch (picture->type) {
1389     case GST_VAAPI_PICTURE_TYPE_I:
1390       *nal_ref_idc = GST_H264_NAL_REF_IDC_HIGH;
1391       if (GST_VAAPI_ENC_PICTURE_IS_IDR (picture))
1392         *nal_unit_type = GST_H264_NAL_SLICE_IDR;
1393       else
1394         *nal_unit_type = GST_H264_NAL_SLICE;
1395       break;
1396     case GST_VAAPI_PICTURE_TYPE_P:
1397       *nal_ref_idc = GST_H264_NAL_REF_IDC_MEDIUM;
1398       *nal_unit_type = GST_H264_NAL_SLICE;
1399       break;
1400     case GST_VAAPI_PICTURE_TYPE_B:
1401       *nal_ref_idc = GST_H264_NAL_REF_IDC_NONE;
1402       *nal_unit_type = GST_H264_NAL_SLICE;
1403       break;
1404     default:
1405       return FALSE;
1406   }
1407   return TRUE;
1408 }
1409
1410 /* Adds the supplied prefix nal header to the list of packed
1411    headers to pass down as-is to the encoder */
1412 static gboolean
1413 add_packed_prefix_nal_header (GstVaapiEncoderH264 * encoder,
1414     GstVaapiEncPicture * picture, GstVaapiEncSlice * slice)
1415 {
1416   GstVaapiEncPackedHeader *packed_prefix_nal;
1417   GstBitWriter bs;
1418   VAEncPackedHeaderParameterBuffer packed_prefix_nal_param = { 0 };
1419   guint32 data_bit_size;
1420   guint8 *data;
1421   guint8 nal_ref_idc, nal_unit_type;
1422
1423   gst_bit_writer_init (&bs, 128 * 8);
1424   WRITE_UINT32 (&bs, 0x00000001, 32);   /* start code */
1425
1426   if (!get_nal_hdr_attributes (picture, &nal_ref_idc, &nal_unit_type))
1427     goto bs_error;
1428   nal_unit_type = GST_H264_NAL_PREFIX_UNIT;
1429
1430   bs_write_nal_header (&bs, nal_ref_idc, nal_unit_type);
1431   bs_write_nal_header_mvc_extension (&bs, picture, encoder->view_idx);
1432   g_assert (GST_BIT_WRITER_BIT_SIZE (&bs) % 8 == 0);
1433   data_bit_size = GST_BIT_WRITER_BIT_SIZE (&bs);
1434   data = GST_BIT_WRITER_DATA (&bs);
1435
1436   packed_prefix_nal_param.type = VAEncPackedHeaderRawData;
1437   packed_prefix_nal_param.bit_length = data_bit_size;
1438   packed_prefix_nal_param.has_emulation_bytes = 0;
1439
1440   packed_prefix_nal =
1441       gst_vaapi_enc_packed_header_new (GST_VAAPI_ENCODER (encoder),
1442       &packed_prefix_nal_param, sizeof (packed_prefix_nal_param), data,
1443       (data_bit_size + 7) / 8);
1444   g_assert (packed_prefix_nal);
1445
1446   gst_vaapi_enc_slice_add_packed_header (slice, packed_prefix_nal);
1447   gst_vaapi_codec_object_replace (&packed_prefix_nal, NULL);
1448
1449   gst_bit_writer_clear (&bs, TRUE);
1450
1451   return TRUE;
1452
1453   /* ERRORS */
1454 bs_error:
1455   {
1456     GST_WARNING ("failed to write Prefix NAL unit header");
1457     gst_bit_writer_clear (&bs, TRUE);
1458     return FALSE;
1459   }
1460 }
1461
1462 /* Adds the supplied slice header to the list of packed
1463    headers to pass down as-is to the encoder */
1464 static gboolean
1465 add_packed_slice_header (GstVaapiEncoderH264 * encoder,
1466     GstVaapiEncPicture * picture, GstVaapiEncSlice * slice)
1467 {
1468   GstVaapiEncPackedHeader *packed_slice;
1469   GstBitWriter bs;
1470   VAEncPackedHeaderParameterBuffer packed_slice_param = { 0 };
1471   const VAEncSliceParameterBufferH264 *const slice_param = slice->param;
1472   guint32 data_bit_size;
1473   guint8 *data;
1474   guint8 nal_ref_idc, nal_unit_type;
1475
1476   gst_bit_writer_init (&bs, 128 * 8);
1477   WRITE_UINT32 (&bs, 0x00000001, 32);   /* start code */
1478
1479   if (!get_nal_hdr_attributes (picture, &nal_ref_idc, &nal_unit_type))
1480     goto bs_error;
1481   bs_write_nal_header (&bs, nal_ref_idc, nal_unit_type);
1482
1483   bs_write_slice (&bs, slice_param, encoder, picture);
1484   data_bit_size = GST_BIT_WRITER_BIT_SIZE (&bs);
1485   data = GST_BIT_WRITER_DATA (&bs);
1486
1487   packed_slice_param.type = VAEncPackedHeaderSlice;
1488   packed_slice_param.bit_length = data_bit_size;
1489   packed_slice_param.has_emulation_bytes = 0;
1490
1491   packed_slice = gst_vaapi_enc_packed_header_new (GST_VAAPI_ENCODER (encoder),
1492       &packed_slice_param, sizeof (packed_slice_param),
1493       data, (data_bit_size + 7) / 8);
1494   g_assert (packed_slice);
1495
1496   gst_vaapi_enc_slice_add_packed_header (slice, packed_slice);
1497   gst_vaapi_codec_object_replace (&packed_slice, NULL);
1498
1499   gst_bit_writer_clear (&bs, TRUE);
1500   return TRUE;
1501
1502   /* ERRORS */
1503 bs_error:
1504   {
1505     GST_WARNING ("failed to write Slice NAL unit header");
1506     gst_bit_writer_clear (&bs, TRUE);
1507     return FALSE;
1508   }
1509 }
1510
1511 /* Reference picture management */
1512 static void
1513 reference_pic_free (GstVaapiEncoderH264 * encoder, GstVaapiEncoderH264Ref * ref)
1514 {
1515   if (!ref)
1516     return;
1517   if (ref->pic)
1518     gst_vaapi_encoder_release_surface (GST_VAAPI_ENCODER (encoder), ref->pic);
1519   g_slice_free (GstVaapiEncoderH264Ref, ref);
1520 }
1521
1522 static inline GstVaapiEncoderH264Ref *
1523 reference_pic_create (GstVaapiEncoderH264 * encoder,
1524     GstVaapiEncPicture * picture, GstVaapiSurfaceProxy * surface)
1525 {
1526   GstVaapiEncoderH264Ref *const ref = g_slice_new0 (GstVaapiEncoderH264Ref);
1527
1528   ref->pic = surface;
1529   ref->frame_num = picture->frame_num;
1530   ref->poc = picture->poc;
1531   return ref;
1532 }
1533
1534 static gboolean
1535 reference_list_update (GstVaapiEncoderH264 * encoder,
1536     GstVaapiEncPicture * picture, GstVaapiSurfaceProxy * surface)
1537 {
1538   GstVaapiEncoderH264Ref *ref;
1539   GstVaapiH264ViewRefPool *const ref_pool =
1540       &encoder->ref_pools[encoder->view_idx];
1541
1542   if (GST_VAAPI_PICTURE_TYPE_B == picture->type) {
1543     gst_vaapi_encoder_release_surface (GST_VAAPI_ENCODER (encoder), surface);
1544     return TRUE;
1545   }
1546   if (GST_VAAPI_ENC_PICTURE_IS_IDR (picture)) {
1547     while (!g_queue_is_empty (&ref_pool->ref_list))
1548       reference_pic_free (encoder, g_queue_pop_head (&ref_pool->ref_list));
1549   } else if (g_queue_get_length (&ref_pool->ref_list) >=
1550       ref_pool->max_ref_frames) {
1551     reference_pic_free (encoder, g_queue_pop_head (&ref_pool->ref_list));
1552   }
1553   ref = reference_pic_create (encoder, picture, surface);
1554   g_queue_push_tail (&ref_pool->ref_list, ref);
1555   g_assert (g_queue_get_length (&ref_pool->ref_list) <=
1556       ref_pool->max_ref_frames);
1557   return TRUE;
1558 }
1559
1560 static gboolean
1561 reference_list_init (GstVaapiEncoderH264 * encoder,
1562     GstVaapiEncPicture * picture,
1563     GstVaapiEncoderH264Ref ** reflist_0,
1564     guint * reflist_0_count,
1565     GstVaapiEncoderH264Ref ** reflist_1, guint * reflist_1_count)
1566 {
1567   GstVaapiEncoderH264Ref *tmp;
1568   GstVaapiH264ViewRefPool *const ref_pool =
1569       &encoder->ref_pools[encoder->view_idx];
1570   GList *iter, *list_0_start = NULL, *list_1_start = NULL;
1571   guint count;
1572
1573   *reflist_0_count = 0;
1574   *reflist_1_count = 0;
1575   if (picture->type == GST_VAAPI_PICTURE_TYPE_I)
1576     return TRUE;
1577
1578   iter = g_queue_peek_tail_link (&ref_pool->ref_list);
1579   for (; iter; iter = g_list_previous (iter)) {
1580     tmp = (GstVaapiEncoderH264Ref *) iter->data;
1581     g_assert (tmp && tmp->poc != picture->poc);
1582     if (_poc_greater_than (picture->poc, tmp->poc, encoder->max_pic_order_cnt)) {
1583       list_0_start = iter;
1584       list_1_start = g_list_next (iter);
1585       break;
1586     }
1587   }
1588
1589   /* order reflist_0 */
1590   g_assert (list_0_start);
1591   iter = list_0_start;
1592   count = 0;
1593   for (; iter; iter = g_list_previous (iter)) {
1594     reflist_0[count] = (GstVaapiEncoderH264Ref *) iter->data;
1595     ++count;
1596   }
1597   *reflist_0_count = count;
1598
1599   if (picture->type != GST_VAAPI_PICTURE_TYPE_B)
1600     return TRUE;
1601
1602   /* order reflist_1 */
1603   count = 0;
1604   iter = list_1_start;
1605   for (; iter; iter = g_list_next (iter)) {
1606     reflist_1[count] = (GstVaapiEncoderH264Ref *) iter->data;
1607     ++count;
1608   }
1609   *reflist_1_count = count;
1610   return TRUE;
1611 }
1612
1613 /* Fills in VA sequence parameter buffer */
1614 static gboolean
1615 fill_sequence (GstVaapiEncoderH264 * encoder, GstVaapiEncSequence * sequence)
1616 {
1617   VAEncSequenceParameterBufferH264 *const seq_param = sequence->param;
1618   GstVaapiH264ViewRefPool *const ref_pool =
1619       &encoder->ref_pools[encoder->view_idx];
1620
1621   memset (seq_param, 0, sizeof (VAEncSequenceParameterBufferH264));
1622   seq_param->seq_parameter_set_id = encoder->view_idx;
1623   seq_param->level_idc = encoder->level_idc;
1624   seq_param->intra_period = GST_VAAPI_ENCODER_KEYFRAME_PERIOD (encoder);
1625   seq_param->ip_period = 1 + encoder->num_bframes;
1626   seq_param->bits_per_second = encoder->bitrate_bits;
1627
1628   seq_param->max_num_ref_frames = ref_pool->max_ref_frames;
1629   seq_param->picture_width_in_mbs = encoder->mb_width;
1630   seq_param->picture_height_in_mbs = encoder->mb_height;
1631
1632   /*sequence field values */
1633   seq_param->seq_fields.value = 0;
1634   seq_param->seq_fields.bits.chroma_format_idc = 1;
1635   seq_param->seq_fields.bits.frame_mbs_only_flag = 1;
1636   seq_param->seq_fields.bits.mb_adaptive_frame_field_flag = FALSE;
1637   seq_param->seq_fields.bits.seq_scaling_matrix_present_flag = FALSE;
1638   /* direct_8x8_inference_flag default false */
1639   seq_param->seq_fields.bits.direct_8x8_inference_flag = FALSE;
1640   g_assert (encoder->log2_max_frame_num >= 4);
1641   seq_param->seq_fields.bits.log2_max_frame_num_minus4 =
1642       encoder->log2_max_frame_num - 4;
1643   /* picture order count */
1644   encoder->pic_order_cnt_type = seq_param->seq_fields.bits.pic_order_cnt_type =
1645       0;
1646   g_assert (encoder->log2_max_pic_order_cnt >= 4);
1647   seq_param->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 =
1648       encoder->log2_max_pic_order_cnt - 4;
1649
1650   seq_param->bit_depth_luma_minus8 = 0;
1651   seq_param->bit_depth_chroma_minus8 = 0;
1652
1653   /* not used if pic_order_cnt_type == 0 */
1654   if (seq_param->seq_fields.bits.pic_order_cnt_type == 1) {
1655     encoder->delta_pic_order_always_zero_flag =
1656         seq_param->seq_fields.bits.delta_pic_order_always_zero_flag = TRUE;
1657     seq_param->num_ref_frames_in_pic_order_cnt_cycle = 0;
1658     seq_param->offset_for_non_ref_pic = 0;
1659     seq_param->offset_for_top_to_bottom_field = 0;
1660     memset (seq_param->offset_for_ref_frame, 0,
1661         sizeof (seq_param->offset_for_ref_frame));
1662   }
1663
1664   /* frame_cropping_flag */
1665   if ((GST_VAAPI_ENCODER_WIDTH (encoder) & 15) ||
1666       (GST_VAAPI_ENCODER_HEIGHT (encoder) & 15)) {
1667     static const guint SubWidthC[] = { 1, 2, 2, 1 };
1668     static const guint SubHeightC[] = { 1, 2, 1, 1 };
1669     const guint CropUnitX =
1670         SubWidthC[seq_param->seq_fields.bits.chroma_format_idc];
1671     const guint CropUnitY =
1672         SubHeightC[seq_param->seq_fields.bits.chroma_format_idc] *
1673         (2 - seq_param->seq_fields.bits.frame_mbs_only_flag);
1674
1675     seq_param->frame_cropping_flag = 1;
1676     seq_param->frame_crop_left_offset = 0;
1677     seq_param->frame_crop_right_offset =
1678         (16 * encoder->mb_width -
1679         GST_VAAPI_ENCODER_WIDTH (encoder)) / CropUnitX;
1680     seq_param->frame_crop_top_offset = 0;
1681     seq_param->frame_crop_bottom_offset =
1682         (16 * encoder->mb_height -
1683         GST_VAAPI_ENCODER_HEIGHT (encoder)) / CropUnitY;
1684   }
1685
1686   /* VUI parameters are always set, at least for timing_info (framerate) */
1687   seq_param->vui_parameters_present_flag = TRUE;
1688   if (seq_param->vui_parameters_present_flag) {
1689     seq_param->vui_fields.bits.aspect_ratio_info_present_flag = FALSE;
1690     seq_param->vui_fields.bits.bitstream_restriction_flag = FALSE;
1691     seq_param->vui_fields.bits.timing_info_present_flag = TRUE;
1692     if (seq_param->vui_fields.bits.timing_info_present_flag) {
1693       seq_param->num_units_in_tick = GST_VAAPI_ENCODER_FPS_D (encoder);
1694       seq_param->time_scale = GST_VAAPI_ENCODER_FPS_N (encoder) * 2;
1695     }
1696   }
1697   return TRUE;
1698 }
1699
1700 /* Fills in VA picture parameter buffer */
1701 static gboolean
1702 fill_picture (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture,
1703     GstVaapiCodedBuffer * codedbuf, GstVaapiSurfaceProxy * surface)
1704 {
1705   VAEncPictureParameterBufferH264 *const pic_param = picture->param;
1706   GstVaapiH264ViewRefPool *const ref_pool =
1707       &encoder->ref_pools[encoder->view_idx];
1708   GstVaapiEncoderH264Ref *ref_pic;
1709   GList *reflist;
1710   guint i;
1711
1712   memset (pic_param, 0, sizeof (VAEncPictureParameterBufferH264));
1713
1714   /* reference list,  */
1715   pic_param->CurrPic.picture_id = GST_VAAPI_SURFACE_PROXY_SURFACE_ID (surface);
1716   pic_param->CurrPic.TopFieldOrderCnt = picture->poc;
1717   i = 0;
1718   if (picture->type != GST_VAAPI_PICTURE_TYPE_I) {
1719     for (reflist = g_queue_peek_head_link (&ref_pool->ref_list);
1720         reflist; reflist = g_list_next (reflist)) {
1721       ref_pic = reflist->data;
1722       g_assert (ref_pic && ref_pic->pic &&
1723           GST_VAAPI_SURFACE_PROXY_SURFACE_ID (ref_pic->pic) != VA_INVALID_ID);
1724
1725       pic_param->ReferenceFrames[i].picture_id =
1726           GST_VAAPI_SURFACE_PROXY_SURFACE_ID (ref_pic->pic);
1727       ++i;
1728     }
1729     g_assert (i <= 16 && i <= ref_pool->max_ref_frames);
1730   }
1731   for (; i < 16; ++i) {
1732     pic_param->ReferenceFrames[i].picture_id = VA_INVALID_ID;
1733   }
1734   pic_param->coded_buf = GST_VAAPI_OBJECT_ID (codedbuf);
1735
1736   pic_param->pic_parameter_set_id = encoder->view_idx;
1737   pic_param->seq_parameter_set_id = encoder->view_idx;
1738   pic_param->last_picture = 0;  /* means last encoding picture */
1739   pic_param->frame_num = picture->frame_num;
1740   pic_param->pic_init_qp = encoder->init_qp;
1741   pic_param->num_ref_idx_l0_active_minus1 =
1742       (ref_pool->max_reflist0_count ? (ref_pool->max_reflist0_count - 1) : 0);
1743   pic_param->num_ref_idx_l1_active_minus1 =
1744       (ref_pool->max_reflist1_count ? (ref_pool->max_reflist1_count - 1) : 0);
1745   pic_param->chroma_qp_index_offset = 0;
1746   pic_param->second_chroma_qp_index_offset = 0;
1747
1748   /* set picture fields */
1749   pic_param->pic_fields.value = 0;
1750   pic_param->pic_fields.bits.idr_pic_flag =
1751       GST_VAAPI_ENC_PICTURE_IS_IDR (picture);
1752   pic_param->pic_fields.bits.reference_pic_flag =
1753       (picture->type != GST_VAAPI_PICTURE_TYPE_B);
1754   pic_param->pic_fields.bits.entropy_coding_mode_flag = encoder->use_cabac;
1755   pic_param->pic_fields.bits.weighted_pred_flag = FALSE;
1756   pic_param->pic_fields.bits.weighted_bipred_idc = 0;
1757   pic_param->pic_fields.bits.constrained_intra_pred_flag = 0;
1758   pic_param->pic_fields.bits.transform_8x8_mode_flag = encoder->use_dct8x8;
1759   /* enable debloking */
1760   pic_param->pic_fields.bits.deblocking_filter_control_present_flag = TRUE;
1761   pic_param->pic_fields.bits.redundant_pic_cnt_present_flag = FALSE;
1762   /* bottom_field_pic_order_in_frame_present_flag */
1763   pic_param->pic_fields.bits.pic_order_present_flag = FALSE;
1764   pic_param->pic_fields.bits.pic_scaling_matrix_present_flag = FALSE;
1765
1766   return TRUE;
1767 }
1768
1769 /* Adds slice headers to picture */
1770 static gboolean
1771 add_slice_headers (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture,
1772     GstVaapiEncoderH264Ref ** reflist_0, guint reflist_0_count,
1773     GstVaapiEncoderH264Ref ** reflist_1, guint reflist_1_count)
1774 {
1775   VAEncSliceParameterBufferH264 *slice_param;
1776   GstVaapiEncSlice *slice;
1777   guint slice_of_mbs, slice_mod_mbs, cur_slice_mbs;
1778   guint mb_size;
1779   guint last_mb_index;
1780   guint i_slice, i_ref;
1781
1782   g_assert (picture);
1783
1784   mb_size = encoder->mb_width * encoder->mb_height;
1785
1786   g_assert (encoder->num_slices && encoder->num_slices < mb_size);
1787   slice_of_mbs = mb_size / encoder->num_slices;
1788   slice_mod_mbs = mb_size % encoder->num_slices;
1789   last_mb_index = 0;
1790   for (i_slice = 0; i_slice < encoder->num_slices; ++i_slice) {
1791     cur_slice_mbs = slice_of_mbs;
1792     if (slice_mod_mbs) {
1793       ++cur_slice_mbs;
1794       --slice_mod_mbs;
1795     }
1796     slice = GST_VAAPI_ENC_SLICE_NEW (H264, encoder);
1797     g_assert (slice && slice->param_id != VA_INVALID_ID);
1798     slice_param = slice->param;
1799
1800     memset (slice_param, 0, sizeof (VAEncSliceParameterBufferH264));
1801     slice_param->macroblock_address = last_mb_index;
1802     slice_param->num_macroblocks = cur_slice_mbs;
1803     slice_param->macroblock_info = VA_INVALID_ID;
1804     slice_param->slice_type = h264_get_slice_type (picture->type);
1805     g_assert (slice_param->slice_type != -1);
1806     slice_param->pic_parameter_set_id = encoder->view_idx;
1807     slice_param->idr_pic_id = encoder->idr_num;
1808     slice_param->pic_order_cnt_lsb = picture->poc;
1809
1810     /* not used if pic_order_cnt_type = 0 */
1811     slice_param->delta_pic_order_cnt_bottom = 0;
1812     memset (slice_param->delta_pic_order_cnt, 0,
1813         sizeof (slice_param->delta_pic_order_cnt));
1814
1815     /* only works for B frames */
1816     slice_param->direct_spatial_mv_pred_flag = FALSE;
1817     /* default equal to picture parameters */
1818     slice_param->num_ref_idx_active_override_flag = FALSE;
1819     if (picture->type != GST_VAAPI_PICTURE_TYPE_I && reflist_0_count > 0)
1820       slice_param->num_ref_idx_l0_active_minus1 = reflist_0_count - 1;
1821     else
1822       slice_param->num_ref_idx_l0_active_minus1 = 0;
1823     if (picture->type == GST_VAAPI_PICTURE_TYPE_B && reflist_1_count > 0)
1824       slice_param->num_ref_idx_l1_active_minus1 = reflist_1_count - 1;
1825     else
1826       slice_param->num_ref_idx_l1_active_minus1 = 0;
1827     g_assert (slice_param->num_ref_idx_l0_active_minus1 == 0);
1828     g_assert (slice_param->num_ref_idx_l1_active_minus1 == 0);
1829
1830     i_ref = 0;
1831     if (picture->type != GST_VAAPI_PICTURE_TYPE_I) {
1832       for (; i_ref < reflist_0_count; ++i_ref) {
1833         slice_param->RefPicList0[i_ref].picture_id =
1834             GST_VAAPI_SURFACE_PROXY_SURFACE_ID (reflist_0[i_ref]->pic);
1835       }
1836       g_assert (i_ref == 1);
1837     }
1838     for (; i_ref < G_N_ELEMENTS (slice_param->RefPicList0); ++i_ref) {
1839       slice_param->RefPicList0[i_ref].picture_id = VA_INVALID_SURFACE;
1840     }
1841
1842     i_ref = 0;
1843     if (picture->type == GST_VAAPI_PICTURE_TYPE_B) {
1844       for (; i_ref < reflist_1_count; ++i_ref) {
1845         slice_param->RefPicList1[i_ref].picture_id =
1846             GST_VAAPI_SURFACE_PROXY_SURFACE_ID (reflist_1[i_ref]->pic);
1847       }
1848       g_assert (i_ref == 1);
1849     }
1850     for (; i_ref < G_N_ELEMENTS (slice_param->RefPicList1); ++i_ref) {
1851       slice_param->RefPicList1[i_ref].picture_id = VA_INVALID_SURFACE;
1852     }
1853
1854     /* not used if  pic_param.pic_fields.bits.weighted_pred_flag == FALSE */
1855     slice_param->luma_log2_weight_denom = 0;
1856     slice_param->chroma_log2_weight_denom = 0;
1857     slice_param->luma_weight_l0_flag = FALSE;
1858     memset (slice_param->luma_weight_l0, 0,
1859         sizeof (slice_param->luma_weight_l0));
1860     memset (slice_param->luma_offset_l0, 0,
1861         sizeof (slice_param->luma_offset_l0));
1862     slice_param->chroma_weight_l0_flag = FALSE;
1863     memset (slice_param->chroma_weight_l0, 0,
1864         sizeof (slice_param->chroma_weight_l0));
1865     memset (slice_param->chroma_offset_l0, 0,
1866         sizeof (slice_param->chroma_offset_l0));
1867     slice_param->luma_weight_l1_flag = FALSE;
1868     memset (slice_param->luma_weight_l1, 0,
1869         sizeof (slice_param->luma_weight_l1));
1870     memset (slice_param->luma_offset_l1, 0,
1871         sizeof (slice_param->luma_offset_l1));
1872     slice_param->chroma_weight_l1_flag = FALSE;
1873     memset (slice_param->chroma_weight_l1, 0,
1874         sizeof (slice_param->chroma_weight_l1));
1875     memset (slice_param->chroma_offset_l1, 0,
1876         sizeof (slice_param->chroma_offset_l1));
1877
1878     slice_param->cabac_init_idc = 0;
1879     slice_param->slice_qp_delta = encoder->init_qp - encoder->min_qp;
1880     if (slice_param->slice_qp_delta > 4)
1881       slice_param->slice_qp_delta = 4;
1882     slice_param->disable_deblocking_filter_idc = 0;
1883     slice_param->slice_alpha_c0_offset_div2 = 2;
1884     slice_param->slice_beta_offset_div2 = 2;
1885
1886     /* set calculation for next slice */
1887     last_mb_index += cur_slice_mbs;
1888
1889     if (encoder->is_mvc &&
1890         (GST_VAAPI_ENCODER_PACKED_HEADERS (encoder) & VA_ENC_PACKED_HEADER_RAW_DATA)
1891         && !add_packed_prefix_nal_header (encoder, picture, slice))
1892       goto error_create_packed_prefix_nal_hdr;
1893     if ((GST_VAAPI_ENCODER_PACKED_HEADERS (encoder) &
1894             VA_ENC_PACKED_HEADER_SLICE)
1895         && !add_packed_slice_header (encoder, picture, slice))
1896       goto error_create_packed_slice_hdr;
1897
1898     gst_vaapi_enc_picture_add_slice (picture, slice);
1899     gst_vaapi_codec_object_replace (&slice, NULL);
1900   }
1901   g_assert (last_mb_index == mb_size);
1902   return TRUE;
1903
1904 error_create_packed_slice_hdr:
1905   {
1906     GST_ERROR ("failed to create packed slice header buffer");
1907     gst_vaapi_codec_object_replace (&slice, NULL);
1908     return FALSE;
1909   }
1910 error_create_packed_prefix_nal_hdr:
1911   {
1912     GST_ERROR ("failed to create packed prefix nal header buffer");
1913     gst_vaapi_codec_object_replace (&slice, NULL);
1914     return FALSE;
1915   }
1916 }
1917
1918 /* Generates and submits SPS header accordingly into the bitstream */
1919 static gboolean
1920 ensure_sequence (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
1921 {
1922   GstVaapiEncSequence *sequence = NULL;
1923
1924   // Submit an SPS header before every new I-frame
1925   if (picture->type != GST_VAAPI_PICTURE_TYPE_I)
1926     return TRUE;
1927
1928   sequence = GST_VAAPI_ENC_SEQUENCE_NEW (H264, encoder);
1929   if (!sequence || !fill_sequence (encoder, sequence))
1930     goto error_create_seq_param;
1931
1932   /* add subset sps for non-base view and sps for base view */
1933   if (encoder->is_mvc && encoder->view_idx) {
1934     if ((GST_VAAPI_ENCODER_PACKED_HEADERS (encoder) & VAEncPackedHeaderH264_SPS)
1935         && !add_packed_sequence_header_mvc (encoder, picture, sequence))
1936       goto error_create_packed_seq_hdr;
1937   } else {
1938     if ((GST_VAAPI_ENCODER_PACKED_HEADERS (encoder) & VAEncPackedHeaderH264_SPS)
1939         && !add_packed_sequence_header (encoder, picture, sequence))
1940       goto error_create_packed_seq_hdr;
1941   }
1942
1943   if (sequence) {
1944     gst_vaapi_enc_picture_set_sequence (picture, sequence);
1945     gst_vaapi_codec_object_replace (&sequence, NULL);
1946   }
1947   return TRUE;
1948
1949   /* ERRORS */
1950 error_create_seq_param:
1951   {
1952     GST_ERROR ("failed to create sequence parameter buffer (SPS)");
1953     gst_vaapi_codec_object_replace (&sequence, NULL);
1954     return FALSE;
1955   }
1956 error_create_packed_seq_hdr:
1957   {
1958     GST_ERROR ("failed to create packed sequence header buffer");
1959     gst_vaapi_codec_object_replace (&sequence, NULL);
1960     return FALSE;
1961   }
1962 }
1963
1964 /* Generates additional control parameters */
1965 static gboolean
1966 ensure_misc_params (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
1967 {
1968   GstVaapiEncMiscParam *misc = NULL;
1969   VAEncMiscParameterRateControl *rate_control;
1970
1971   /* HRD params */
1972   misc = GST_VAAPI_ENC_MISC_PARAM_NEW (HRD, encoder);
1973   g_assert (misc);
1974   if (!misc)
1975     return FALSE;
1976   fill_hrd_params (encoder, misc->data);
1977   gst_vaapi_enc_picture_add_misc_param (picture, misc);
1978   gst_vaapi_codec_object_replace (&misc, NULL);
1979
1980   /* RateControl params */
1981   if (GST_VAAPI_ENCODER_RATE_CONTROL (encoder) == GST_VAAPI_RATECONTROL_CBR ||
1982       GST_VAAPI_ENCODER_RATE_CONTROL (encoder) == GST_VAAPI_RATECONTROL_VBR) {
1983     misc = GST_VAAPI_ENC_MISC_PARAM_NEW (RateControl, encoder);
1984     g_assert (misc);
1985     if (!misc)
1986       return FALSE;
1987     rate_control = misc->data;
1988     memset (rate_control, 0, sizeof (VAEncMiscParameterRateControl));
1989     rate_control->bits_per_second = encoder->bitrate_bits;
1990     rate_control->target_percentage = 70;
1991     rate_control->window_size = encoder->cpb_length;
1992     rate_control->initial_qp = encoder->init_qp;
1993     rate_control->min_qp = encoder->min_qp;
1994     rate_control->basic_unit_size = 0;
1995     gst_vaapi_enc_picture_add_misc_param (picture, misc);
1996     gst_vaapi_codec_object_replace (&misc, NULL);
1997   }
1998   return TRUE;
1999 }
2000
2001 /* Generates and submits PPS header accordingly into the bitstream */
2002 static gboolean
2003 ensure_picture (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture,
2004     GstVaapiCodedBufferProxy * codedbuf_proxy, GstVaapiSurfaceProxy * surface)
2005 {
2006   GstVaapiCodedBuffer *const codedbuf =
2007       GST_VAAPI_CODED_BUFFER_PROXY_BUFFER (codedbuf_proxy);
2008   gboolean res = FALSE;
2009
2010   res = fill_picture (encoder, picture, codedbuf, surface);
2011
2012   if (!res)
2013     return FALSE;
2014
2015   if (picture->type == GST_VAAPI_PICTURE_TYPE_I &&
2016       (GST_VAAPI_ENCODER_PACKED_HEADERS (encoder) & VAEncPackedHeaderH264_PPS)
2017       && !add_packed_picture_header (encoder, picture)) {
2018     GST_ERROR ("set picture packed header failed");
2019     return FALSE;
2020   }
2021   return TRUE;
2022 }
2023
2024 /* Generates slice headers */
2025 static gboolean
2026 ensure_slices (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
2027 {
2028   GstVaapiEncoderH264Ref *reflist_0[16];
2029   GstVaapiEncoderH264Ref *reflist_1[16];
2030   GstVaapiH264ViewRefPool *const ref_pool =
2031       &encoder->ref_pools[encoder->view_idx];
2032   guint reflist_0_count = 0, reflist_1_count = 0;
2033
2034   g_assert (picture);
2035
2036   if (picture->type != GST_VAAPI_PICTURE_TYPE_I &&
2037       !reference_list_init (encoder, picture,
2038           reflist_0, &reflist_0_count, reflist_1, &reflist_1_count)) {
2039     GST_ERROR ("reference list reorder failed");
2040     return FALSE;
2041   }
2042
2043   g_assert (reflist_0_count + reflist_1_count <= ref_pool->max_ref_frames);
2044   if (reflist_0_count > ref_pool->max_reflist0_count)
2045     reflist_0_count = ref_pool->max_reflist0_count;
2046   if (reflist_1_count > ref_pool->max_reflist1_count)
2047     reflist_1_count = ref_pool->max_reflist1_count;
2048
2049   if (!add_slice_headers (encoder, picture,
2050           reflist_0, reflist_0_count, reflist_1, reflist_1_count))
2051     return FALSE;
2052
2053   return TRUE;
2054 }
2055
2056 /* Normalizes bitrate (and CPB size) for HRD conformance */
2057 static void
2058 ensure_bitrate_hrd (GstVaapiEncoderH264 * encoder)
2059 {
2060   GstVaapiEncoder *const base_encoder = GST_VAAPI_ENCODER_CAST (encoder);
2061   guint bitrate, cpb_size;
2062
2063   if (!base_encoder->bitrate) {
2064     encoder->bitrate_bits = 0;
2065     return;
2066   }
2067
2068   /* Round down bitrate. This is a hard limit mandated by the user */
2069   g_assert (SX_BITRATE >= 6);
2070   bitrate = (base_encoder->bitrate * 1000) & ~((1U << SX_BITRATE) - 1);
2071   GST_DEBUG ("HRD bitrate: %u bits/sec", bitrate);
2072   encoder->bitrate_bits = bitrate;
2073
2074   /* Round up CPB size. This is an HRD compliance detail */
2075   g_assert (SX_CPB_SIZE >= 4);
2076   cpb_size = gst_util_uint64_scale (bitrate, encoder->cpb_length, 1000) &
2077       ~((1U << SX_CPB_SIZE) - 1);
2078   GST_DEBUG ("HRD CPB size: %u bits", cpb_size);
2079   encoder->cpb_length_bits = cpb_size;
2080 }
2081
2082 /* Estimates a good enough bitrate if none was supplied */
2083 static void
2084 ensure_bitrate (GstVaapiEncoderH264 * encoder)
2085 {
2086   GstVaapiEncoder *const base_encoder = GST_VAAPI_ENCODER_CAST (encoder);
2087
2088   /* Default compression: 48 bits per macroblock in "high-compression" mode */
2089   switch (GST_VAAPI_ENCODER_RATE_CONTROL (encoder)) {
2090     case GST_VAAPI_RATECONTROL_CBR:
2091     case GST_VAAPI_RATECONTROL_VBR:
2092     case GST_VAAPI_RATECONTROL_VBR_CONSTRAINED:
2093       if (!base_encoder->bitrate) {
2094         /* According to the literature and testing, CABAC entropy coding
2095            mode could provide for +10% to +18% improvement in general,
2096            thus estimating +15% here ; and using adaptive 8x8 transforms
2097            in I-frames could bring up to +10% improvement. */
2098         guint bits_per_mb = 48;
2099         if (!encoder->use_cabac)
2100           bits_per_mb += (bits_per_mb * 15) / 100;
2101         if (!encoder->use_dct8x8)
2102           bits_per_mb += (bits_per_mb * 10) / 100;
2103
2104         base_encoder->bitrate =
2105             encoder->mb_width * encoder->mb_height * bits_per_mb *
2106             GST_VAAPI_ENCODER_FPS_N (encoder) /
2107             GST_VAAPI_ENCODER_FPS_D (encoder) / 1000;
2108         GST_INFO ("target bitrate computed to %u kbps", base_encoder->bitrate);
2109       }
2110       break;
2111     default:
2112       base_encoder->bitrate = 0;
2113       break;
2114   }
2115   ensure_bitrate_hrd (encoder);
2116 }
2117
2118 /* Constructs profile and level information based on user-defined limits */
2119 static GstVaapiEncoderStatus
2120 ensure_profile_and_level (GstVaapiEncoderH264 * encoder)
2121 {
2122   ensure_tuning (encoder);
2123
2124   if (!ensure_profile (encoder) || !ensure_profile_limits (encoder))
2125     return GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
2126
2127   /* Check HW constraints */
2128   if (!ensure_hw_profile_limits (encoder))
2129     return GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
2130   if (encoder->profile_idc > encoder->hw_max_profile_idc)
2131     return GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
2132
2133   /* Ensure bitrate if not set already and derive the right level to use */
2134   ensure_bitrate (encoder);
2135   if (!ensure_level (encoder))
2136     return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
2137   return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2138 }
2139
2140 static void
2141 reset_properties (GstVaapiEncoderH264 * encoder)
2142 {
2143   GstVaapiEncoder *const base_encoder = GST_VAAPI_ENCODER_CAST (encoder);
2144   guint mb_size, i;
2145
2146   if (encoder->idr_period < base_encoder->keyframe_period)
2147     encoder->idr_period = base_encoder->keyframe_period;
2148   if (encoder->idr_period > MAX_IDR_PERIOD)
2149     encoder->idr_period = MAX_IDR_PERIOD;
2150
2151   if (encoder->min_qp > encoder->init_qp ||
2152       (GST_VAAPI_ENCODER_RATE_CONTROL (encoder) == GST_VAAPI_RATECONTROL_CQP &&
2153           encoder->min_qp < encoder->init_qp))
2154     encoder->min_qp = encoder->init_qp;
2155
2156   mb_size = encoder->mb_width * encoder->mb_height;
2157   if (encoder->num_slices > (mb_size + 1) / 2)
2158     encoder->num_slices = (mb_size + 1) / 2;
2159   g_assert (encoder->num_slices);
2160
2161   if (encoder->num_bframes > (base_encoder->keyframe_period + 1) / 2)
2162     encoder->num_bframes = (base_encoder->keyframe_period + 1) / 2;
2163
2164   if (encoder->num_bframes)
2165     encoder->cts_offset = GST_SECOND * GST_VAAPI_ENCODER_FPS_D (encoder) /
2166         GST_VAAPI_ENCODER_FPS_N (encoder);
2167   else
2168     encoder->cts_offset = 0;
2169
2170   /* init max_frame_num, max_poc */
2171   encoder->log2_max_frame_num =
2172       h264_get_log2_max_frame_num (encoder->idr_period);
2173   g_assert (encoder->log2_max_frame_num >= 4);
2174   encoder->max_frame_num = (1 << encoder->log2_max_frame_num);
2175   encoder->log2_max_pic_order_cnt = encoder->log2_max_frame_num + 1;
2176   encoder->max_pic_order_cnt = (1 << encoder->log2_max_pic_order_cnt);
2177   encoder->idr_num = 0;
2178
2179   encoder->is_mvc = encoder->num_views > 1;
2180   for (i = 0; i < encoder->num_views; i++) {
2181     GstVaapiH264ViewRefPool *const ref_pool = &encoder->ref_pools[i];
2182     ref_pool->max_reflist0_count = 1;
2183     ref_pool->max_reflist1_count = encoder->num_bframes > 0;
2184     ref_pool->max_ref_frames = ref_pool->max_reflist0_count
2185         + ref_pool->max_reflist1_count;
2186
2187     GstVaapiH264ViewReorderPool *const reorder_pool =
2188         &encoder->reorder_pools[i];
2189     reorder_pool->frame_index = 0;
2190   }
2191 }
2192
2193 static GstVaapiEncoderStatus
2194 gst_vaapi_encoder_h264_encode (GstVaapiEncoder * base_encoder,
2195     GstVaapiEncPicture * picture, GstVaapiCodedBufferProxy * codedbuf)
2196 {
2197   GstVaapiEncoderH264 *const encoder =
2198       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2199   GstVaapiEncoderStatus ret = GST_VAAPI_ENCODER_STATUS_ERROR_UNKNOWN;
2200   GstVaapiSurfaceProxy *reconstruct = NULL;
2201
2202   reconstruct = gst_vaapi_encoder_create_surface (base_encoder);
2203
2204   g_assert (GST_VAAPI_SURFACE_PROXY_SURFACE (reconstruct));
2205
2206   if (!ensure_sequence (encoder, picture))
2207     goto error;
2208   if (!ensure_misc_params (encoder, picture))
2209     goto error;
2210   if (!ensure_picture (encoder, picture, codedbuf, reconstruct))
2211     goto error;
2212   if (!ensure_slices (encoder, picture))
2213     goto error;
2214   if (!gst_vaapi_enc_picture_encode (picture))
2215     goto error;
2216
2217   if (!reference_list_update (encoder, picture, reconstruct))
2218     goto error;
2219
2220   return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2221 error:
2222   if (reconstruct)
2223     gst_vaapi_encoder_release_surface (GST_VAAPI_ENCODER (encoder),
2224         reconstruct);
2225   return ret;
2226 }
2227
2228 static GstVaapiEncoderStatus
2229 gst_vaapi_encoder_h264_flush (GstVaapiEncoder * base_encoder)
2230 {
2231   GstVaapiEncoderH264 *const encoder =
2232       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2233   GstVaapiH264ViewReorderPool *reorder_pool;
2234   GstVaapiEncPicture *pic;
2235   guint i;
2236
2237   for (i = 0; i < encoder->num_views; i++) {
2238     reorder_pool = &encoder->reorder_pools[i];
2239     reorder_pool->frame_index = 0;
2240     reorder_pool->cur_frame_num = 0;
2241     reorder_pool->cur_present_index = 0;
2242
2243     while (!g_queue_is_empty (&reorder_pool->reorder_frame_list)) {
2244       pic = (GstVaapiEncPicture *)
2245           g_queue_pop_head (&reorder_pool->reorder_frame_list);
2246       gst_vaapi_enc_picture_unref (pic);
2247     }
2248     g_queue_clear (&reorder_pool->reorder_frame_list);
2249   }
2250
2251   return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2252 }
2253
2254 /* Generate "codec-data" buffer */
2255 static GstVaapiEncoderStatus
2256 gst_vaapi_encoder_h264_get_codec_data (GstVaapiEncoder * base_encoder,
2257     GstBuffer ** out_buffer_ptr)
2258 {
2259   GstVaapiEncoderH264 *const encoder =
2260       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2261   const guint32 configuration_version = 0x01;
2262   const guint32 nal_length_size = 4;
2263   guint8 profile_idc, profile_comp, level_idc;
2264   GstMapInfo sps_info, pps_info;
2265   GstBitWriter bs;
2266   GstBuffer *buffer;
2267
2268   if (!encoder->sps_data || !encoder->pps_data)
2269     return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_HEADER;
2270   if (gst_buffer_get_size (encoder->sps_data) < 4)
2271     return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_HEADER;
2272
2273   if (!gst_buffer_map (encoder->sps_data, &sps_info, GST_MAP_READ))
2274     goto error_map_sps_buffer;
2275
2276   if (!gst_buffer_map (encoder->pps_data, &pps_info, GST_MAP_READ))
2277     goto error_map_pps_buffer;
2278
2279   /* skip sps_data[0], which is the nal_unit_type */
2280   profile_idc = sps_info.data[1];
2281   profile_comp = sps_info.data[2];
2282   level_idc = sps_info.data[3];
2283
2284   /* Header */
2285   gst_bit_writer_init (&bs, (sps_info.size + pps_info.size + 64) * 8);
2286   WRITE_UINT32 (&bs, configuration_version, 8);
2287   WRITE_UINT32 (&bs, profile_idc, 8);
2288   WRITE_UINT32 (&bs, profile_comp, 8);
2289   WRITE_UINT32 (&bs, level_idc, 8);
2290   WRITE_UINT32 (&bs, 0x3f, 6);  /* 111111 */
2291   WRITE_UINT32 (&bs, nal_length_size - 1, 2);
2292   WRITE_UINT32 (&bs, 0x07, 3);  /* 111 */
2293
2294   /* Write SPS */
2295   WRITE_UINT32 (&bs, 1, 5);     /* SPS count = 1 */
2296   g_assert (GST_BIT_WRITER_BIT_SIZE (&bs) % 8 == 0);
2297   WRITE_UINT32 (&bs, sps_info.size, 16);
2298   gst_bit_writer_put_bytes (&bs, sps_info.data, sps_info.size);
2299
2300   /* Write PPS */
2301   WRITE_UINT32 (&bs, 1, 8);     /* PPS count = 1 */
2302   WRITE_UINT32 (&bs, pps_info.size, 16);
2303   gst_bit_writer_put_bytes (&bs, pps_info.data, pps_info.size);
2304
2305   gst_buffer_unmap (encoder->pps_data, &pps_info);
2306   gst_buffer_unmap (encoder->sps_data, &sps_info);
2307
2308   buffer = gst_buffer_new_wrapped (GST_BIT_WRITER_DATA (&bs),
2309       GST_BIT_WRITER_BIT_SIZE (&bs) / 8);
2310   if (!buffer)
2311     goto error_alloc_buffer;
2312   *out_buffer_ptr = buffer;
2313
2314   gst_bit_writer_clear (&bs, FALSE);
2315   return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2316
2317   /* ERRORS */
2318 bs_error:
2319   {
2320     GST_ERROR ("failed to write codec-data");
2321     gst_buffer_unmap (encoder->sps_data, &sps_info);
2322     gst_buffer_unmap (encoder->pps_data, &pps_info);
2323     gst_bit_writer_clear (&bs, TRUE);
2324     return FALSE;
2325   }
2326 error_map_sps_buffer:
2327   {
2328     GST_ERROR ("failed to map SPS packed header");
2329     return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
2330   }
2331 error_map_pps_buffer:
2332   {
2333     GST_ERROR ("failed to map PPS packed header");
2334     gst_buffer_unmap (encoder->sps_data, &sps_info);
2335     return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
2336   }
2337 error_alloc_buffer:
2338   {
2339     GST_ERROR ("failed to allocate codec-data buffer");
2340     gst_bit_writer_clear (&bs, TRUE);
2341     return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
2342   }
2343 }
2344
2345 static GstVaapiEncoderStatus
2346 gst_vaapi_encoder_h264_reordering (GstVaapiEncoder * base_encoder,
2347     GstVideoCodecFrame * frame, GstVaapiEncPicture ** output)
2348 {
2349   GstVaapiEncoderH264 *const encoder =
2350       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2351   GstVaapiH264ViewReorderPool *reorder_pool = NULL;
2352   GstVaapiEncPicture *picture;
2353   gboolean is_idr = FALSE;
2354
2355   *output = NULL;
2356
2357   /* encoding views alternatively for MVC */
2358   if (encoder->is_mvc) {
2359     if (frame)
2360       encoder->view_idx = frame->system_frame_number % MAX_NUM_VIEWS;
2361     else
2362       encoder->view_idx = (encoder->view_idx + 1) % MAX_NUM_VIEWS;
2363   }
2364   reorder_pool = &encoder->reorder_pools[encoder->view_idx];
2365
2366   if (!frame) {
2367     if (reorder_pool->reorder_state != GST_VAAPI_ENC_H264_REORD_DUMP_FRAMES)
2368       return GST_VAAPI_ENCODER_STATUS_NO_SURFACE;
2369
2370     /* reorder_state = GST_VAAPI_ENC_H264_REORD_DUMP_FRAMES
2371        dump B frames from queue, sometime, there may also have P frame or I frame */
2372     g_assert (encoder->num_bframes > 0);
2373     g_return_val_if_fail (!g_queue_is_empty (&reorder_pool->reorder_frame_list),
2374         GST_VAAPI_ENCODER_STATUS_ERROR_UNKNOWN);
2375     picture = g_queue_pop_head (&reorder_pool->reorder_frame_list);
2376     g_assert (picture);
2377     if (g_queue_is_empty (&reorder_pool->reorder_frame_list)) {
2378       reorder_pool->reorder_state = GST_VAAPI_ENC_H264_REORD_WAIT_FRAMES;
2379     }
2380     goto end;
2381   }
2382
2383   /* new frame coming */
2384   picture = GST_VAAPI_ENC_PICTURE_NEW (H264, encoder, frame);
2385   if (!picture) {
2386     GST_WARNING ("create H264 picture failed, frame timestamp:%"
2387         GST_TIME_FORMAT, GST_TIME_ARGS (frame->pts));
2388     return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
2389   }
2390   ++reorder_pool->cur_present_index;
2391   picture->poc = ((reorder_pool->cur_present_index * 2) %
2392       encoder->max_pic_order_cnt);
2393
2394   is_idr = (reorder_pool->frame_index == 0 ||
2395       reorder_pool->frame_index >= encoder->idr_period);
2396
2397   /* check key frames */
2398   if (is_idr || GST_VIDEO_CODEC_FRAME_IS_FORCE_KEYFRAME (frame) ||
2399       (reorder_pool->frame_index %
2400           GST_VAAPI_ENCODER_KEYFRAME_PERIOD (encoder)) == 0) {
2401     ++reorder_pool->cur_frame_num;
2402     ++reorder_pool->frame_index;
2403
2404     /* b frame enabled,  check queue of reorder_frame_list */
2405     if (encoder->num_bframes
2406         && !g_queue_is_empty (&reorder_pool->reorder_frame_list)) {
2407       GstVaapiEncPicture *p_pic;
2408
2409       p_pic = g_queue_pop_tail (&reorder_pool->reorder_frame_list);
2410       set_p_frame (p_pic, encoder);
2411       g_queue_foreach (&reorder_pool->reorder_frame_list,
2412           (GFunc) set_b_frame, encoder);
2413       ++reorder_pool->cur_frame_num;
2414       set_key_frame (picture, encoder, is_idr);
2415       g_queue_push_tail (&reorder_pool->reorder_frame_list, picture);
2416       picture = p_pic;
2417       reorder_pool->reorder_state = GST_VAAPI_ENC_H264_REORD_DUMP_FRAMES;
2418     } else {                    /* no b frames in queue */
2419       set_key_frame (picture, encoder, is_idr);
2420       g_assert (g_queue_is_empty (&reorder_pool->reorder_frame_list));
2421       if (encoder->num_bframes)
2422         reorder_pool->reorder_state = GST_VAAPI_ENC_H264_REORD_WAIT_FRAMES;
2423     }
2424     goto end;
2425   }
2426
2427   /* new p/b frames coming */
2428   ++reorder_pool->frame_index;
2429   if (reorder_pool->reorder_state == GST_VAAPI_ENC_H264_REORD_WAIT_FRAMES &&
2430       g_queue_get_length (&reorder_pool->reorder_frame_list) <
2431       encoder->num_bframes) {
2432     g_queue_push_tail (&reorder_pool->reorder_frame_list, picture);
2433     return GST_VAAPI_ENCODER_STATUS_NO_SURFACE;
2434   }
2435
2436   ++reorder_pool->cur_frame_num;
2437   set_p_frame (picture, encoder);
2438
2439   if (reorder_pool->reorder_state == GST_VAAPI_ENC_H264_REORD_WAIT_FRAMES) {
2440     g_queue_foreach (&reorder_pool->reorder_frame_list, (GFunc) set_b_frame,
2441         encoder);
2442     reorder_pool->reorder_state = GST_VAAPI_ENC_H264_REORD_DUMP_FRAMES;
2443     g_assert (!g_queue_is_empty (&reorder_pool->reorder_frame_list));
2444   }
2445
2446 end:
2447   g_assert (picture);
2448   frame = picture->frame;
2449   if (GST_CLOCK_TIME_IS_VALID (frame->pts))
2450     frame->pts += encoder->cts_offset;
2451   *output = picture;
2452
2453   return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2454 }
2455
2456 static GstVaapiEncoderStatus
2457 set_context_info (GstVaapiEncoder * base_encoder)
2458 {
2459   GstVaapiEncoderH264 *const encoder =
2460       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2461   GstVideoInfo *const vip = GST_VAAPI_ENCODER_VIDEO_INFO (encoder);
2462   const guint DEFAULT_SURFACES_COUNT = 3;
2463
2464   /* Maximum sizes for common headers (in bits) */
2465   enum
2466   {
2467     MAX_SPS_HDR_SIZE = 16473,
2468     MAX_VUI_PARAMS_SIZE = 210,
2469     MAX_HRD_PARAMS_SIZE = 4103,
2470     MAX_PPS_HDR_SIZE = 101,
2471     MAX_SLICE_HDR_SIZE = 397 + 2572 + 6670 + 2402,
2472   };
2473
2474   if (!ensure_hw_profile (encoder))
2475     return GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
2476
2477   base_encoder->num_ref_frames =
2478       ((encoder->num_bframes ? 2 : 1) + DEFAULT_SURFACES_COUNT)
2479       * encoder->num_views;
2480
2481   /* Only YUV 4:2:0 formats are supported for now. This means that we
2482      have a limit of 3200 bits per macroblock. */
2483   /* XXX: check profile and compute RawMbBits */
2484   base_encoder->codedbuf_size = (GST_ROUND_UP_16 (vip->width) *
2485       GST_ROUND_UP_16 (vip->height) / 256) * 400;
2486
2487   /* Account for SPS header */
2488   /* XXX: exclude scaling lists, MVC/SVC extensions */
2489   base_encoder->codedbuf_size += 4 + GST_ROUND_UP_8 (MAX_SPS_HDR_SIZE +
2490       MAX_VUI_PARAMS_SIZE + 2 * MAX_HRD_PARAMS_SIZE) / 8;
2491
2492   /* Account for PPS header */
2493   /* XXX: exclude slice groups, scaling lists, MVC/SVC extensions */
2494   base_encoder->codedbuf_size += 4 + GST_ROUND_UP_8 (MAX_PPS_HDR_SIZE) / 8;
2495
2496   /* Account for slice header */
2497   base_encoder->codedbuf_size += encoder->num_slices * (4 +
2498       GST_ROUND_UP_8 (MAX_SLICE_HDR_SIZE) / 8);
2499
2500   return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2501 }
2502
2503 static GstVaapiEncoderStatus
2504 gst_vaapi_encoder_h264_reconfigure (GstVaapiEncoder * base_encoder)
2505 {
2506   GstVaapiEncoderH264 *const encoder =
2507       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2508   GstVaapiEncoderStatus status;
2509
2510   encoder->mb_width = (GST_VAAPI_ENCODER_WIDTH (encoder) + 15) / 16;
2511   encoder->mb_height = (GST_VAAPI_ENCODER_HEIGHT (encoder) + 15) / 16;
2512
2513   status = ensure_profile_and_level (encoder);
2514   if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
2515     return status;
2516
2517   reset_properties (encoder);
2518   return set_context_info (base_encoder);
2519 }
2520
2521 static gboolean
2522 gst_vaapi_encoder_h264_init (GstVaapiEncoder * base_encoder)
2523 {
2524   GstVaapiEncoderH264 *const encoder =
2525       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2526   guint32 i;
2527
2528   /* Multi-view coding information */
2529   encoder->is_mvc = FALSE;
2530   encoder->num_views = 1;
2531   encoder->view_idx = 0;
2532
2533   /* re-ordering  list initialize */
2534   for (i = 0; i < MAX_NUM_VIEWS; i++) {
2535     GstVaapiH264ViewReorderPool *const reorder_pool =
2536         &encoder->reorder_pools[i];
2537     g_queue_init (&reorder_pool->reorder_frame_list);
2538     reorder_pool->reorder_state = GST_VAAPI_ENC_H264_REORD_NONE;
2539     reorder_pool->frame_index = 0;
2540     reorder_pool->cur_frame_num = 0;
2541     reorder_pool->cur_present_index = 0;
2542   }
2543
2544   /* reference list info initialize */
2545   for (i = 0; i < MAX_NUM_VIEWS; i++) {
2546     GstVaapiH264ViewRefPool *const ref_pool = &encoder->ref_pools[i];
2547     g_queue_init (&ref_pool->ref_list);
2548     ref_pool->max_ref_frames = 0;
2549     ref_pool->max_reflist0_count = 1;
2550     ref_pool->max_reflist1_count = 1;
2551   }
2552
2553   return TRUE;
2554 }
2555
2556 static void
2557 gst_vaapi_encoder_h264_finalize (GstVaapiEncoder * base_encoder)
2558 {
2559   /*free private buffers */
2560   GstVaapiEncoderH264 *const encoder =
2561       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2562   GstVaapiEncPicture *pic;
2563   GstVaapiEncoderH264Ref *ref;
2564   guint32 i;
2565
2566   gst_buffer_replace (&encoder->sps_data, NULL);
2567   gst_buffer_replace (&encoder->subset_sps_data, NULL);
2568   gst_buffer_replace (&encoder->pps_data, NULL);
2569
2570   /* reference list info de-init */
2571   for (i = 0; i < MAX_NUM_VIEWS; i++) {
2572     GstVaapiH264ViewRefPool *const ref_pool = &encoder->ref_pools[i];
2573     while (!g_queue_is_empty (&ref_pool->ref_list)) {
2574       ref = (GstVaapiEncoderH264Ref *) g_queue_pop_head (&ref_pool->ref_list);
2575       reference_pic_free (encoder, ref);
2576     }
2577     g_queue_clear (&ref_pool->ref_list);
2578   }
2579
2580   /* re-ordering  list initialize */
2581   for (i = 0; i < MAX_NUM_VIEWS; i++) {
2582     GstVaapiH264ViewReorderPool *const reorder_pool =
2583         &encoder->reorder_pools[i];
2584     while (!g_queue_is_empty (&reorder_pool->reorder_frame_list)) {
2585       pic = (GstVaapiEncPicture *)
2586           g_queue_pop_head (&reorder_pool->reorder_frame_list);
2587       gst_vaapi_enc_picture_unref (pic);
2588     }
2589     g_queue_clear (&reorder_pool->reorder_frame_list);
2590   }
2591 }
2592
2593 static GstVaapiEncoderStatus
2594 gst_vaapi_encoder_h264_set_property (GstVaapiEncoder * base_encoder,
2595     gint prop_id, const GValue * value)
2596 {
2597   GstVaapiEncoderH264 *const encoder =
2598       GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2599
2600   switch (prop_id) {
2601     case GST_VAAPI_ENCODER_H264_PROP_MAX_BFRAMES:
2602       encoder->num_bframes = g_value_get_uint (value);
2603       break;
2604     case GST_VAAPI_ENCODER_H264_PROP_INIT_QP:
2605       encoder->init_qp = g_value_get_uint (value);
2606       break;
2607     case GST_VAAPI_ENCODER_H264_PROP_MIN_QP:
2608       encoder->min_qp = g_value_get_uint (value);
2609       break;
2610     case GST_VAAPI_ENCODER_H264_PROP_NUM_SLICES:
2611       encoder->num_slices = g_value_get_uint (value);
2612       break;
2613     case GST_VAAPI_ENCODER_H264_PROP_CABAC:
2614       encoder->use_cabac = g_value_get_boolean (value);
2615       break;
2616     case GST_VAAPI_ENCODER_H264_PROP_DCT8X8:
2617       encoder->use_dct8x8 = g_value_get_boolean (value);
2618       break;
2619     case GST_VAAPI_ENCODER_H264_PROP_CPB_LENGTH:
2620       encoder->cpb_length = g_value_get_uint (value);
2621       break;
2622     case GST_VAAPI_ENCODER_H264_PROP_NUM_VIEWS:
2623       encoder->num_views = g_value_get_uint (value);
2624       break;
2625     default:
2626       return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
2627   }
2628   return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2629 }
2630
2631 GST_VAAPI_ENCODER_DEFINE_CLASS_DATA (H264);
2632
2633 static inline const GstVaapiEncoderClass *
2634 gst_vaapi_encoder_h264_class (void)
2635 {
2636   static const GstVaapiEncoderClass GstVaapiEncoderH264Class = {
2637     GST_VAAPI_ENCODER_CLASS_INIT (H264, h264),
2638     .set_property = gst_vaapi_encoder_h264_set_property,
2639     .get_codec_data = gst_vaapi_encoder_h264_get_codec_data
2640   };
2641   return &GstVaapiEncoderH264Class;
2642 }
2643
2644 /**
2645  * gst_vaapi_encoder_h264_new:
2646  * @display: a #GstVaapiDisplay
2647  *
2648  * Creates a new #GstVaapiEncoder for H.264 encoding. Note that the
2649  * only supported output stream format is "byte-stream" format.
2650  *
2651  * Return value: the newly allocated #GstVaapiEncoder object
2652  */
2653 GstVaapiEncoder *
2654 gst_vaapi_encoder_h264_new (GstVaapiDisplay * display)
2655 {
2656   return gst_vaapi_encoder_new (gst_vaapi_encoder_h264_class (), display);
2657 }
2658
2659 /**
2660  * gst_vaapi_encoder_h264_get_default_properties:
2661  *
2662  * Determines the set of common and H.264 specific encoder properties.
2663  * The caller owns an extra reference to the resulting array of
2664  * #GstVaapiEncoderPropInfo elements, so it shall be released with
2665  * g_ptr_array_unref() after usage.
2666  *
2667  * Return value: the set of encoder properties for #GstVaapiEncoderH264,
2668  *   or %NULL if an error occurred.
2669  */
2670 GPtrArray *
2671 gst_vaapi_encoder_h264_get_default_properties (void)
2672 {
2673   const GstVaapiEncoderClass *const klass = gst_vaapi_encoder_h264_class ();
2674   GPtrArray *props;
2675
2676   props = gst_vaapi_encoder_properties_get_default (klass);
2677   if (!props)
2678     return NULL;
2679
2680   /**
2681    * GstVaapiEncoderH264:max-bframes:
2682    *
2683    * The number of B-frames between I and P.
2684    */
2685   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2686       GST_VAAPI_ENCODER_H264_PROP_MAX_BFRAMES,
2687       g_param_spec_uint ("max-bframes",
2688           "Max B-Frames", "Number of B-frames between I and P", 0, 10, 0,
2689           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2690
2691   /**
2692    * GstVaapiEncoderH264:init-qp:
2693    *
2694    * The initial quantizer value.
2695    */
2696   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2697       GST_VAAPI_ENCODER_H264_PROP_INIT_QP,
2698       g_param_spec_uint ("init-qp",
2699           "Initial QP", "Initial quantizer value", 1, 51, 26,
2700           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2701
2702   /**
2703    * GstVaapiEncoderH264:min-qp:
2704    *
2705    * The minimum quantizer value.
2706    */
2707   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2708       GST_VAAPI_ENCODER_H264_PROP_MIN_QP,
2709       g_param_spec_uint ("min-qp",
2710           "Minimum QP", "Minimum quantizer value", 1, 51, 1,
2711           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2712
2713   /**
2714    * GstVaapiEncoderH264:num-slices:
2715    *
2716    * The number of slices per frame.
2717    */
2718   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2719       GST_VAAPI_ENCODER_H264_PROP_NUM_SLICES,
2720       g_param_spec_uint ("num-slices",
2721           "Number of Slices",
2722           "Number of slices per frame",
2723           1, 200, 1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2724
2725   /**
2726    * GstVaapiEncoderH264:cabac:
2727    *
2728    * Enable CABAC entropy coding mode for improved compression ratio,
2729    * at the expense that the minimum target profile is Main. Default
2730    * is CAVLC entropy coding mode.
2731    */
2732   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2733       GST_VAAPI_ENCODER_H264_PROP_CABAC,
2734       g_param_spec_boolean ("cabac",
2735           "Enable CABAC",
2736           "Enable CABAC entropy coding mode",
2737           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2738
2739   /**
2740    * GstVaapiEncoderH264:dct8x8:
2741    *
2742    * Enable adaptive use of 8x8 transforms in I-frames. This improves
2743    * the compression ratio by the minimum target profile is High.
2744    * Default is to use 4x4 DCT only.
2745    */
2746   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2747       GST_VAAPI_ENCODER_H264_PROP_DCT8X8,
2748       g_param_spec_boolean ("dct8x8",
2749           "Enable 8x8 DCT",
2750           "Enable adaptive use of 8x8 transforms in I-frames",
2751           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2752
2753   /**
2754    * GstVaapiEncoderH264:cpb-length:
2755    *
2756    * The size of the CPB buffer in milliseconds.
2757    */
2758   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2759       GST_VAAPI_ENCODER_H264_PROP_CPB_LENGTH,
2760       g_param_spec_uint ("cpb-length",
2761           "CPB Length", "Length of the CPB buffer in milliseconds",
2762           1, 10000, DEFAULT_CPB_LENGTH,
2763           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2764
2765   /**
2766    * GstVaapiEncoderH264:num-views:
2767    *
2768    * The number of views for MVC encoding .
2769    */
2770   GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2771       GST_VAAPI_ENCODER_H264_PROP_NUM_VIEWS,
2772       g_param_spec_uint ("num-views",
2773           "Number of Views",
2774           "Number of Views for MVC encoding",
2775           1, MAX_NUM_VIEWS, 1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2776
2777   return props;
2778 }
2779
2780 /**
2781  * gst_vaapi_encoder_h264_set_max_profile:
2782  * @encoder: a #GstVaapiEncoderH264
2783  * @profile: an H.264 #GstVaapiProfile
2784  *
2785  * Notifies the @encoder to use coding tools from the supplied
2786  * @profile at most.
2787  *
2788  * This means that if the minimal profile derived to
2789  * support the specified coding tools is greater than this @profile,
2790  * then an error is returned when the @encoder is configured.
2791  *
2792  * Return value: %TRUE on success
2793  */
2794 gboolean
2795 gst_vaapi_encoder_h264_set_max_profile (GstVaapiEncoderH264 * encoder,
2796     GstVaapiProfile profile)
2797 {
2798   guint8 profile_idc;
2799
2800   g_return_val_if_fail (encoder != NULL, FALSE);
2801   g_return_val_if_fail (profile != GST_VAAPI_PROFILE_UNKNOWN, FALSE);
2802
2803   if (gst_vaapi_profile_get_codec (profile) != GST_VAAPI_CODEC_H264)
2804     return FALSE;
2805
2806   profile_idc = gst_vaapi_utils_h264_get_profile_idc (profile);
2807   if (!profile_idc)
2808     return FALSE;
2809
2810   encoder->max_profile_idc = profile_idc;
2811   return TRUE;
2812 }
2813
2814 /**
2815  * gst_vaapi_encoder_h264_get_profile_and_level:
2816  * @encoder: a #GstVaapiEncoderH264
2817  * @out_profile_ptr: return location for the #GstVaapiProfile
2818  * @out_level_ptr: return location for the #GstVaapiLevelH264
2819  *
2820  * Queries the H.264 @encoder for the active profile and level. That
2821  * information is only constructed and valid after the encoder is
2822  * configured, i.e. after the gst_vaapi_encoder_set_codec_state()
2823  * function is called.
2824  *
2825  * Return value: %TRUE on success
2826  */
2827 gboolean
2828 gst_vaapi_encoder_h264_get_profile_and_level (GstVaapiEncoderH264 * encoder,
2829     GstVaapiProfile * out_profile_ptr, GstVaapiLevelH264 * out_level_ptr)
2830 {
2831   g_return_val_if_fail (encoder != NULL, FALSE);
2832
2833   if (!encoder->profile || !encoder->level)
2834     return FALSE;
2835
2836   if (out_profile_ptr)
2837     *out_profile_ptr = encoder->profile;
2838   if (out_level_ptr)
2839     *out_level_ptr = encoder->level;
2840   return TRUE;
2841 }