2 * gstvaapiencoder_h264.c - H.264 encoder
4 * Copyright (C) 2012-2014 Intel Corporation
5 * Author: Wind Yuan <feng.yuan@intel.com>
6 * Author: Gwenole Beauchesne <gwenole.beauchesne@intel.com>
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.
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.
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
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"
38 #include "gstvaapidebug.h"
40 /* Define the maximum number of views supported */
41 #define MAX_NUM_VIEWS 2
43 /* Define the maximum IDR period */
44 #define MAX_IDR_PERIOD 512
46 /* Default CPB length (in milliseconds) */
47 #define DEFAULT_CPB_LENGTH 1500
49 /* Scale factor for CPB size (HRD cpb_size_scale: min = 4) */
52 /* Scale factor for bitrate (HRD bit_rate_scale: min = 6) */
55 /* Define default rate control mode ("constant-qp") */
56 #define DEFAULT_RATECONTROL GST_VAAPI_RATECONTROL_CQP
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))
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))
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)
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
84 GstVaapiSurfaceProxy *pic;
87 } GstVaapiEncoderH264Ref;
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;
96 typedef struct _GstVaapiH264ViewRefPool
100 guint max_reflist0_count;
101 guint max_reflist1_count;
102 } GstVaapiH264ViewRefPool;
104 typedef struct _GstVaapiH264ViewReorderPool
106 GQueue reorder_frame_list;
110 guint cur_present_index;
111 } GstVaapiH264ViewReorderPool;
113 static inline gboolean
114 _poc_greater_than (guint poc1, guint poc2, guint max_poc)
116 return (((poc1 - poc2) & (max_poc - 1)) < max_poc / 2);
119 /* Get slice_type value for H.264 specification */
121 h264_get_slice_type (GstVaapiPictureType 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;
136 /* Get log2_max_frame_num value for H.264 specification */
138 h264_get_log2_max_frame_num (guint num)
150 /* must be greater than 4 */
154 /* Determines the cpbBrNalFactor based on the supplied profile */
156 h264_get_cpb_nal_factor (GstVaapiProfile profile)
162 case GST_VAAPI_PROFILE_H264_HIGH:
165 case GST_VAAPI_PROFILE_H264_HIGH10:
168 case GST_VAAPI_PROFILE_H264_HIGH_422:
169 case GST_VAAPI_PROFILE_H264_HIGH_444:
179 /* ------------------------------------------------------------------------- */
180 /* --- H.264 Bitstream Writer --- */
181 /* ------------------------------------------------------------------------- */
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); \
190 #define WRITE_UE(bs, val) do { \
191 if (!bs_write_ue (bs, val)) { \
192 GST_WARNING ("failed to write ue(v)"); \
197 #define WRITE_SE(bs, val) do { \
198 if (!bs_write_se (bs, val)) { \
199 GST_WARNING ("failed to write se(v)"); \
204 /* Write an unsigned integer Exp-Golomb-coded syntax element. i.e. ue(v) */
206 bs_write_ue (GstBitWriter * bs, guint32 value)
208 guint32 size_in_bits = 0;
209 guint32 tmp_value = ++value;
216 && !gst_bit_writer_put_bits_uint32 (bs, 0, size_in_bits - 1))
218 if (!gst_bit_writer_put_bits_uint32 (bs, value, size_in_bits))
223 /* Write a signed integer Exp-Golomb-coded syntax element. i.e. se(v) */
225 bs_write_se (GstBitWriter * bs, gint32 value)
230 new_val = -(value << 1);
232 new_val = (value << 1) - 1;
234 if (!bs_write_ue (bs, new_val))
239 /* Write the NAL unit header */
241 bs_write_nal_header (GstBitWriter * bs, guint32 nal_ref_idc,
242 guint32 nal_unit_type)
244 WRITE_UINT32 (bs, 0, 1);
245 WRITE_UINT32 (bs, nal_ref_idc, 2);
246 WRITE_UINT32 (bs, nal_unit_type, 5);
252 GST_WARNING ("failed to write NAL unit header");
257 /* Write the MVC NAL unit header extension */
259 bs_write_nal_header_mvc_extension (GstBitWriter * bs,
260 GstVaapiEncPicture * picture, guint32 view_id)
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;
269 if (GST_VAAPI_ENC_PICTURE_IS_IDR (picture))
272 if (picture->type == GST_VAAPI_PICTURE_TYPE_I)
274 /* svc_extension_flag == 0 for mvc stream */
275 WRITE_UINT32 (bs, svc_extension_flag, 1);
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);
290 GST_WARNING ("failed to write NAL unit header");
295 /* Write the NAL unit trailing bits */
297 bs_write_trailing_bits (GstBitWriter * bs)
299 if (!gst_bit_writer_put_bits_uint32 (bs, 1, 1))
301 gst_bit_writer_align_bytes_unchecked (bs, 0);
307 GST_WARNING ("failed to write NAL unit trailing bits");
312 /* Write an SPS NAL unit */
314 bs_write_sps_data (GstBitWriter * bs,
315 const VAEncSequenceParameterBufferH264 * seq_param, GstVaapiProfile profile,
316 const VAEncMiscParameterHRD * hrd_params)
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;
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;
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;
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);
356 WRITE_UINT32 (bs, seq_param->level_idc, 8);
357 /* seq_parameter_set_id */
358 WRITE_UE (bs, seq_param->seq_parameter_set_id);
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);
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);
376 /* seq_scaling_matrix_present_flag */
377 g_assert (seq_param->seq_fields.bits.seq_scaling_matrix_present_flag == 0);
379 seq_param->seq_fields.bits.seq_scaling_matrix_present_flag, 1);
382 if (seq_param->seq_fields.bits.seq_scaling_matrix_present_flag) {
384 i < (seq_param->seq_fields.bits.chroma_format_idc != 3 ? 8 : 12);
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) {
390 /* FIXME, need write scaling list if seq_scaling_matrix_present_flag ==1 */
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);
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");
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]);
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);
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);
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);
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);
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);
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 */
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);
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);
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 */
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) {
487 WRITE_UINT32 (bs, SX_BITRATE - 6, 4); /* bit_rate_scale */
488 WRITE_UINT32 (bs, SX_CPB_SIZE - 4, 4); /* cpb_size_scale */
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);
496 WRITE_UINT32 (bs, 1, 1);
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);
508 /* vcl_hrd_parameters_present_flag */
509 WRITE_UINT32 (bs, 0, 1);
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);
516 /* pic_struct_present_flag */
517 WRITE_UINT32 (bs, 0, 1);
518 /* bs_restriction_flag */
519 WRITE_UINT32 (bs, 0, 1);
526 GST_WARNING ("failed to write SPS NAL unit");
532 bs_write_sps (GstBitWriter * bs,
533 const VAEncSequenceParameterBufferH264 * seq_param, GstVaapiProfile profile,
534 const VAEncMiscParameterHRD * hrd_params)
536 if (!bs_write_sps_data (bs, seq_param, profile, hrd_params))
539 /* rbsp_trailing_bits */
540 bs_write_trailing_bits (bs);
546 bs_write_subset_sps (GstBitWriter * bs,
547 const VAEncSequenceParameterBufferH264 * seq_param, GstVaapiProfile profile,
548 guint num_views, const VAEncMiscParameterHRD * hrd_params)
552 if (!bs_write_sps_data (bs, seq_param, profile, hrd_params))
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;
559 num_views_minus1 = num_views - 1;
560 g_assert (num_views_minus1 < 1024);
562 /* bit equal to one */
563 WRITE_UINT32 (bs, 1, 1);
565 WRITE_UE (bs, num_views_minus1);
567 for (i = 0; i <= num_views_minus1; i++)
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++)
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++)
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++)
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++)
594 /* num level values signalled minus1 */
595 num_level_values_signalled_minus1 = 0;
596 g_assert (num_level_values_signalled_minus1 < 64);
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);
602 WRITE_UINT32 (bs, seq_param->level_idc, 8);
603 WRITE_UE (bs, num_applicable_ops_minus1);
605 for (j = 0; j <= num_applicable_ops_minus1; j++) {
606 guint8 temporal_id = 0;
607 guint16 num_target_views_minus1 = 1;
609 WRITE_UINT32 (bs, temporal_id, 3);
610 WRITE_UE (bs, num_target_views_minus1);
612 for (k = 0; k <= num_target_views_minus1; k++)
615 WRITE_UE (bs, num_views_minus1);
619 /* mvc_vui_parameters_present_flag */
620 WRITE_UINT32 (bs, 0, 1);
623 /* additional_extension2_flag */
624 WRITE_UINT32 (bs, 0, 1);
626 /* rbsp_trailing_bits */
627 bs_write_trailing_bits (bs);
633 GST_WARNING ("failed to write subset SPS NAL unit");
639 /* Write a PPS NAL unit */
641 bs_write_pps (GstBitWriter * bs,
642 const VAEncPictureParameterBufferH264 * pic_param, GstVaapiProfile profile)
644 guint32 num_slice_groups_minus1 = 0;
645 guint32 pic_init_qs_minus26 = 0;
646 guint32 redundant_pic_cnt_present_flag = 0;
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);
657 WRITE_UE (bs, num_slice_groups_minus1);
659 if (num_slice_groups_minus1 > 0) {
660 /*FIXME*/ g_assert (0 && "unsupported arbitrary slice ordering (ASO)");
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);
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);
679 if (profile == GST_VAAPI_PROFILE_H264_HIGH) {
680 WRITE_UINT32 (bs, pic_param->pic_fields.bits.transform_8x8_mode_flag, 1);
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");
688 (6+(-( (chroma_format_idc ! = 3) ? 2 : 6) * -pic_param->pic_fields.bits.transform_8x8_mode_flag));
690 gst_bit_writer_put_bits_uint8(bs, pic_param->pic_fields.bits.pic_scaling_list_present_flag, 1);
694 WRITE_SE (bs, pic_param->second_chroma_qp_index_offset);
697 /* rbsp_trailing_bits */
698 bs_write_trailing_bits (bs);
704 GST_WARNING ("failed to write PPS NAL unit");
709 /* ------------------------------------------------------------------------- */
710 /* --- H.264 Encoder --- */
711 /* ------------------------------------------------------------------------- */
713 #define GST_VAAPI_ENCODER_H264_CAST(encoder) \
714 ((GstVaapiEncoderH264 *)(encoder))
716 struct _GstVaapiEncoderH264
718 GstVaapiEncoder parent_instance;
720 GstVaapiProfile profile;
721 GstVaapiLevelH264 level;
723 guint8 max_profile_idc;
724 guint8 hw_max_profile_idc;
735 GstClockTime cts_offset;
738 guint32 max_frame_num;
739 guint32 log2_max_frame_num;
740 guint32 max_pic_order_cnt;
741 guint32 log2_max_pic_order_cnt;
743 guint8 pic_order_cnt_type;
744 guint8 delta_pic_order_always_zero_flag;
747 GstBuffer *subset_sps_data;
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)
758 GstVaapiH264ViewRefPool ref_pools[MAX_NUM_VIEWS];
759 GstVaapiH264ViewReorderPool reorder_pools[MAX_NUM_VIEWS];
762 /* Write a Slice NAL unit */
764 bs_write_slice (GstBitWriter * bs,
765 const VAEncSliceParameterBufferH264 * slice_param,
766 GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
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;
776 /* first_mb_in_slice */
777 WRITE_UE (bs, slice_param->macroblock_address);
779 WRITE_UE (bs, slice_param->slice_type);
780 /* pic_parameter_set_id */
781 WRITE_UE (bs, slice_param->pic_parameter_set_id);
783 WRITE_UINT32 (bs, picture->frame_num, encoder->log2_max_frame_num);
785 /* XXX: only frames (i.e. non-interlaced) are supported for now */
786 /* frame_mbs_only_flag == 0 */
789 if (GST_VAAPI_ENC_PICTURE_IS_IDR (picture))
790 WRITE_UE (bs, slice_param->idr_pic_id);
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]);
805 /* redundant_pic_cnt_present_flag is FALSE, no redundant coded pictures */
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);
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);
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);
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() */
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);
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);
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);
854 WRITE_SE (bs, slice_param->slice_qp_delta);
856 /* XXX: only supporting I, P and B type slices */
857 /* no sp_for_switch_flag and no slice_qs_delta */
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);
868 /* XXX: unsupported arbitrary slice ordering (ASO) */
869 /* num_slic_groups_minus1 should be zero */
875 GST_WARNING ("failed to write Slice NAL unit");
881 _check_sps_pps_status (GstVaapiEncoderH264 * encoder,
882 const guint8 * nal, guint32 size)
886 gboolean has_subset_sps;
890 has_subset_sps = !encoder->is_mvc || (encoder->subset_sps_data != NULL);
891 if (encoder->sps_data && encoder->pps_data && has_subset_sps)
894 nal_type = nal[0] & 0x1F;
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);
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);
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);
916 /* Determines the largest supported profile by the underlying hardware */
918 ensure_hw_profile_limits (GstVaapiEncoderH264 * encoder)
920 GstVaapiDisplay *const display = GST_VAAPI_ENCODER_DISPLAY (encoder);
922 guint i, profile_idc, max_profile_idc;
924 if (encoder->hw_max_profile_idc)
927 profiles = gst_vaapi_display_get_encode_profiles (display);
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);
938 if (max_profile_idc < profile_idc)
939 max_profile_idc = profile_idc;
941 g_array_unref (profiles);
943 encoder->hw_max_profile_idc = max_profile_idc;
947 /* Derives the profile supported by the underlying hardware */
949 ensure_hw_profile (GstVaapiEncoderH264 * encoder)
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;
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;
962 case GST_VAAPI_PROFILE_H264_MAIN:
963 profiles[num_profiles++] = GST_VAAPI_PROFILE_H264_HIGH;
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];
976 if (profile == GST_VAAPI_PROFILE_UNKNOWN)
977 goto error_unsupported_profile;
979 GST_VAAPI_ENCODER_CAST (encoder)->profile = profile;
983 error_unsupported_profile:
985 GST_ERROR ("unsupported HW profile (0x%08x)", encoder->profile);
990 /* Check target decoder constraints */
992 ensure_profile_limits (GstVaapiEncoderH264 * encoder)
994 GstVaapiProfile profile;
996 if (!encoder->max_profile_idc
997 || encoder->profile_idc <= encoder->max_profile_idc)
1000 GST_WARNING ("lowering coding tools to meet target decoder constraints");
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;
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;
1015 encoder->profile = profile;
1016 encoder->profile_idc = encoder->max_profile_idc;
1020 /* Derives the minimum profile from the active coding tools */
1022 ensure_profile (GstVaapiEncoderH264 * encoder)
1024 GstVaapiProfile profile;
1026 /* Always start from "constrained-baseline" profile for maximum
1028 profile = GST_VAAPI_PROFILE_H264_CONSTRAINED_BASELINE;
1030 /* Main profile coding tools */
1031 if (encoder->num_bframes > 0 || encoder->use_cabac)
1032 profile = GST_VAAPI_PROFILE_H264_MAIN;
1034 /* High profile coding tools */
1035 if (encoder->use_dct8x8)
1036 profile = GST_VAAPI_PROFILE_H264_HIGH;
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;
1044 encoder->profile = profile;
1045 encoder->profile_idc = gst_vaapi_utils_h264_get_profile_idc (profile);
1049 /* Derives the level from the currently set limits */
1051 ensure_level (GstVaapiEncoderH264 * encoder)
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;
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));
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)))
1073 if (i == num_limits)
1074 goto error_unsupported_level;
1076 encoder->level = limits_table[i].level;
1077 encoder->level_idc = limits_table[i].level_idc;
1081 error_unsupported_level:
1083 GST_ERROR ("failed to find a suitable level matching codec config");
1088 /* Enable "high-compression" tuning options */
1090 ensure_tuning_high_compression (GstVaapiEncoderH264 * encoder)
1094 if (!ensure_hw_profile_limits (encoder))
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;
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;
1108 /* Tuning options to enable High profile */
1109 if (profile_idc >= 100) {
1110 encoder->use_dct8x8 = TRUE;
1115 /* Ensure tuning options */
1117 ensure_tuning (GstVaapiEncoderH264 * encoder)
1121 switch (GST_VAAPI_ENCODER_TUNE (encoder)) {
1122 case GST_VAAPI_ENCODER_TUNE_HIGH_COMPRESSION:
1123 success = ensure_tuning_high_compression (encoder);
1132 /* Handle new GOP starts */
1134 reset_gop_start (GstVaapiEncoderH264 * encoder)
1136 GstVaapiH264ViewReorderPool *const reorder_pool =
1137 &encoder->reorder_pools[encoder->view_idx];
1139 reorder_pool->frame_index = 1;
1140 reorder_pool->cur_frame_num = 0;
1141 reorder_pool->cur_present_index = 0;
1145 /* Marks the supplied picture as a B-frame */
1147 set_b_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1149 GstVaapiH264ViewReorderPool *const reorder_pool =
1150 &encoder->reorder_pools[encoder->view_idx];
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);
1158 /* Marks the supplied picture as a P-frame */
1160 set_p_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1162 GstVaapiH264ViewReorderPool *const reorder_pool =
1163 &encoder->reorder_pools[encoder->view_idx];
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);
1170 /* Marks the supplied picture as an I-frame */
1172 set_i_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1174 GstVaapiH264ViewReorderPool *const reorder_pool =
1175 &encoder->reorder_pools[encoder->view_idx];
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);
1181 g_assert (pic->frame);
1182 GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (pic->frame);
1185 /* Marks the supplied picture as an IDR frame */
1187 set_idr_frame (GstVaapiEncPicture * pic, GstVaapiEncoderH264 * encoder)
1189 g_return_if_fail (pic->type == GST_VAAPI_PICTURE_TYPE_NONE);
1190 pic->type = GST_VAAPI_PICTURE_TYPE_I;
1193 GST_VAAPI_ENC_PICTURE_FLAG_SET (pic, GST_VAAPI_ENC_PICTURE_FLAG_IDR);
1195 g_assert (pic->frame);
1196 GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (pic->frame);
1199 /* Marks the supplied picture a a key-frame */
1201 set_key_frame (GstVaapiEncPicture * picture,
1202 GstVaapiEncoderH264 * encoder, gboolean is_idr)
1205 reset_gop_start (encoder);
1206 set_idr_frame (picture, encoder);
1208 set_i_frame (picture, encoder);
1211 /* Fills in VA HRD parameters */
1213 fill_hrd_params (GstVaapiEncoderH264 * encoder, VAEncMiscParameterHRD * hrd)
1215 if (encoder->bitrate_bits > 0) {
1216 hrd->buffer_size = encoder->cpb_length_bits;
1217 hrd->initial_buffer_fullness = hrd->buffer_size / 2;
1219 hrd->buffer_size = 0;
1220 hrd->initial_buffer_fullness = 0;
1224 /* Adds the supplied sequence header (SPS) to the list of packed
1225 headers to pass down as-is to the encoder */
1227 add_packed_sequence_header (GstVaapiEncoderH264 * encoder,
1228 GstVaapiEncPicture * picture, GstVaapiEncSequence * sequence)
1230 GstVaapiEncPackedHeader *packed_seq;
1232 VAEncPackedHeaderParameterBuffer packed_seq_param = { 0 };
1233 const VAEncSequenceParameterBufferH264 *const seq_param = sequence->param;
1234 GstVaapiProfile profile = encoder->profile;
1236 VAEncMiscParameterHRD hrd_params;
1237 guint32 data_bit_size;
1240 fill_hrd_params (encoder, &hrd_params);
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);
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;
1253 bs_write_sps (&bs, seq_param, profile, &hrd_params);
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);
1259 packed_seq_param.type = VAEncPackedHeaderSequence;
1260 packed_seq_param.bit_length = data_bit_size;
1261 packed_seq_param.has_emulation_bytes = 0;
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);
1268 gst_vaapi_enc_picture_add_packed_header (picture, packed_seq);
1269 gst_vaapi_codec_object_replace (&packed_seq, NULL);
1271 /* store sps data */
1272 _check_sps_pps_status (encoder, data + 4, data_bit_size / 8 - 4);
1273 gst_bit_writer_clear (&bs, TRUE);
1279 GST_WARNING ("failed to write SPS NAL unit");
1280 gst_bit_writer_clear (&bs, TRUE);
1286 add_packed_sequence_header_mvc (GstVaapiEncoderH264 * encoder,
1287 GstVaapiEncPicture * picture, GstVaapiEncSequence * sequence)
1289 GstVaapiEncPackedHeader *packed_seq;
1291 VAEncPackedHeaderParameterBuffer packed_header_param_buffer = { 0 };
1292 const VAEncSequenceParameterBufferH264 *const seq_param = sequence->param;
1293 VAEncMiscParameterHRD hrd_params;
1294 guint32 data_bit_size;
1297 fill_hrd_params (encoder, &hrd_params);
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);
1304 bs_write_subset_sps (&bs, seq_param, encoder->profile, encoder->num_views,
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);
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;
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);
1320 gst_vaapi_enc_picture_add_packed_header (picture, packed_seq);
1321 gst_vaapi_mini_object_replace ((GstVaapiMiniObject **) & packed_seq, NULL);
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);
1331 GST_WARNING ("failed to write SPS NAL unit");
1332 gst_bit_writer_clear (&bs, TRUE);
1337 /* Adds the supplied picture header (PPS) to the list of packed
1338 headers to pass down as-is to the encoder */
1340 add_packed_picture_header (GstVaapiEncoderH264 * encoder,
1341 GstVaapiEncPicture * picture)
1343 GstVaapiEncPackedHeader *packed_pic;
1345 VAEncPackedHeaderParameterBuffer packed_pic_param = { 0 };
1346 const VAEncPictureParameterBufferH264 *const pic_param = picture->param;
1347 guint32 data_bit_size;
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);
1358 packed_pic_param.type = VAEncPackedHeaderPicture;
1359 packed_pic_param.bit_length = data_bit_size;
1360 packed_pic_param.has_emulation_bytes = 0;
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);
1367 gst_vaapi_enc_picture_add_packed_header (picture, packed_pic);
1368 gst_vaapi_codec_object_replace (&packed_pic, NULL);
1370 /* store pps data */
1371 _check_sps_pps_status (encoder, data + 4, data_bit_size / 8 - 4);
1372 gst_bit_writer_clear (&bs, TRUE);
1378 GST_WARNING ("failed to write PPS NAL unit");
1379 gst_bit_writer_clear (&bs, TRUE);
1385 get_nal_hdr_attributes (GstVaapiEncPicture * picture,
1386 guint8 * nal_ref_idc, guint8 * nal_unit_type)
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;
1394 *nal_unit_type = GST_H264_NAL_SLICE;
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;
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;
1410 /* Adds the supplied prefix nal header to the list of packed
1411 headers to pass down as-is to the encoder */
1413 add_packed_prefix_nal_header (GstVaapiEncoderH264 * encoder,
1414 GstVaapiEncPicture * picture, GstVaapiEncSlice * slice)
1416 GstVaapiEncPackedHeader *packed_prefix_nal;
1418 VAEncPackedHeaderParameterBuffer packed_prefix_nal_param = { 0 };
1419 guint32 data_bit_size;
1421 guint8 nal_ref_idc, nal_unit_type;
1423 gst_bit_writer_init (&bs, 128 * 8);
1424 WRITE_UINT32 (&bs, 0x00000001, 32); /* start code */
1426 if (!get_nal_hdr_attributes (picture, &nal_ref_idc, &nal_unit_type))
1428 nal_unit_type = GST_H264_NAL_PREFIX_UNIT;
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);
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;
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);
1446 gst_vaapi_enc_slice_add_packed_header (slice, packed_prefix_nal);
1447 gst_vaapi_codec_object_replace (&packed_prefix_nal, NULL);
1449 gst_bit_writer_clear (&bs, TRUE);
1456 GST_WARNING ("failed to write Prefix NAL unit header");
1457 gst_bit_writer_clear (&bs, TRUE);
1462 /* Adds the supplied slice header to the list of packed
1463 headers to pass down as-is to the encoder */
1465 add_packed_slice_header (GstVaapiEncoderH264 * encoder,
1466 GstVaapiEncPicture * picture, GstVaapiEncSlice * slice)
1468 GstVaapiEncPackedHeader *packed_slice;
1470 VAEncPackedHeaderParameterBuffer packed_slice_param = { 0 };
1471 const VAEncSliceParameterBufferH264 *const slice_param = slice->param;
1472 guint32 data_bit_size;
1474 guint8 nal_ref_idc, nal_unit_type;
1476 gst_bit_writer_init (&bs, 128 * 8);
1477 WRITE_UINT32 (&bs, 0x00000001, 32); /* start code */
1479 if (!get_nal_hdr_attributes (picture, &nal_ref_idc, &nal_unit_type))
1481 bs_write_nal_header (&bs, nal_ref_idc, nal_unit_type);
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);
1487 packed_slice_param.type = VAEncPackedHeaderSlice;
1488 packed_slice_param.bit_length = data_bit_size;
1489 packed_slice_param.has_emulation_bytes = 0;
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);
1496 gst_vaapi_enc_slice_add_packed_header (slice, packed_slice);
1497 gst_vaapi_codec_object_replace (&packed_slice, NULL);
1499 gst_bit_writer_clear (&bs, TRUE);
1505 GST_WARNING ("failed to write Slice NAL unit header");
1506 gst_bit_writer_clear (&bs, TRUE);
1511 /* Reference picture management */
1513 reference_pic_free (GstVaapiEncoderH264 * encoder, GstVaapiEncoderH264Ref * ref)
1518 gst_vaapi_encoder_release_surface (GST_VAAPI_ENCODER (encoder), ref->pic);
1519 g_slice_free (GstVaapiEncoderH264Ref, ref);
1522 static inline GstVaapiEncoderH264Ref *
1523 reference_pic_create (GstVaapiEncoderH264 * encoder,
1524 GstVaapiEncPicture * picture, GstVaapiSurfaceProxy * surface)
1526 GstVaapiEncoderH264Ref *const ref = g_slice_new0 (GstVaapiEncoderH264Ref);
1529 ref->frame_num = picture->frame_num;
1530 ref->poc = picture->poc;
1535 reference_list_update (GstVaapiEncoderH264 * encoder,
1536 GstVaapiEncPicture * picture, GstVaapiSurfaceProxy * surface)
1538 GstVaapiEncoderH264Ref *ref;
1539 GstVaapiH264ViewRefPool *const ref_pool =
1540 &encoder->ref_pools[encoder->view_idx];
1542 if (GST_VAAPI_PICTURE_TYPE_B == picture->type) {
1543 gst_vaapi_encoder_release_surface (GST_VAAPI_ENCODER (encoder), surface);
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));
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);
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)
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;
1573 *reflist_0_count = 0;
1574 *reflist_1_count = 0;
1575 if (picture->type == GST_VAAPI_PICTURE_TYPE_I)
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);
1589 /* order reflist_0 */
1590 g_assert (list_0_start);
1591 iter = list_0_start;
1593 for (; iter; iter = g_list_previous (iter)) {
1594 reflist_0[count] = (GstVaapiEncoderH264Ref *) iter->data;
1597 *reflist_0_count = count;
1599 if (picture->type != GST_VAAPI_PICTURE_TYPE_B)
1602 /* order reflist_1 */
1604 iter = list_1_start;
1605 for (; iter; iter = g_list_next (iter)) {
1606 reflist_1[count] = (GstVaapiEncoderH264Ref *) iter->data;
1609 *reflist_1_count = count;
1613 /* Fills in VA sequence parameter buffer */
1615 fill_sequence (GstVaapiEncoderH264 * encoder, GstVaapiEncSequence * sequence)
1617 VAEncSequenceParameterBufferH264 *const seq_param = sequence->param;
1618 GstVaapiH264ViewRefPool *const ref_pool =
1619 &encoder->ref_pools[encoder->view_idx];
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;
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;
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 =
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;
1650 seq_param->bit_depth_luma_minus8 = 0;
1651 seq_param->bit_depth_chroma_minus8 = 0;
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));
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);
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;
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;
1700 /* Fills in VA picture parameter buffer */
1702 fill_picture (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture,
1703 GstVaapiCodedBuffer * codedbuf, GstVaapiSurfaceProxy * surface)
1705 VAEncPictureParameterBufferH264 *const pic_param = picture->param;
1706 GstVaapiH264ViewRefPool *const ref_pool =
1707 &encoder->ref_pools[encoder->view_idx];
1708 GstVaapiEncoderH264Ref *ref_pic;
1712 memset (pic_param, 0, sizeof (VAEncPictureParameterBufferH264));
1714 /* reference list, */
1715 pic_param->CurrPic.picture_id = GST_VAAPI_SURFACE_PROXY_SURFACE_ID (surface);
1716 pic_param->CurrPic.TopFieldOrderCnt = picture->poc;
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);
1725 pic_param->ReferenceFrames[i].picture_id =
1726 GST_VAAPI_SURFACE_PROXY_SURFACE_ID (ref_pic->pic);
1729 g_assert (i <= 16 && i <= ref_pool->max_ref_frames);
1731 for (; i < 16; ++i) {
1732 pic_param->ReferenceFrames[i].picture_id = VA_INVALID_ID;
1734 pic_param->coded_buf = GST_VAAPI_OBJECT_ID (codedbuf);
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;
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;
1769 /* Adds slice headers to picture */
1771 add_slice_headers (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture,
1772 GstVaapiEncoderH264Ref ** reflist_0, guint reflist_0_count,
1773 GstVaapiEncoderH264Ref ** reflist_1, guint reflist_1_count)
1775 VAEncSliceParameterBufferH264 *slice_param;
1776 GstVaapiEncSlice *slice;
1777 guint slice_of_mbs, slice_mod_mbs, cur_slice_mbs;
1779 guint last_mb_index;
1780 guint i_slice, i_ref;
1784 mb_size = encoder->mb_width * encoder->mb_height;
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;
1790 for (i_slice = 0; i_slice < encoder->num_slices; ++i_slice) {
1791 cur_slice_mbs = slice_of_mbs;
1792 if (slice_mod_mbs) {
1796 slice = GST_VAAPI_ENC_SLICE_NEW (H264, encoder);
1797 g_assert (slice && slice->param_id != VA_INVALID_ID);
1798 slice_param = slice->param;
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;
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));
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;
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;
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);
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);
1836 g_assert (i_ref == 1);
1838 for (; i_ref < G_N_ELEMENTS (slice_param->RefPicList0); ++i_ref) {
1839 slice_param->RefPicList0[i_ref].picture_id = VA_INVALID_SURFACE;
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);
1848 g_assert (i_ref == 1);
1850 for (; i_ref < G_N_ELEMENTS (slice_param->RefPicList1); ++i_ref) {
1851 slice_param->RefPicList1[i_ref].picture_id = VA_INVALID_SURFACE;
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));
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;
1886 /* set calculation for next slice */
1887 last_mb_index += cur_slice_mbs;
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;
1898 gst_vaapi_enc_picture_add_slice (picture, slice);
1899 gst_vaapi_codec_object_replace (&slice, NULL);
1901 g_assert (last_mb_index == mb_size);
1904 error_create_packed_slice_hdr:
1906 GST_ERROR ("failed to create packed slice header buffer");
1907 gst_vaapi_codec_object_replace (&slice, NULL);
1910 error_create_packed_prefix_nal_hdr:
1912 GST_ERROR ("failed to create packed prefix nal header buffer");
1913 gst_vaapi_codec_object_replace (&slice, NULL);
1918 /* Generates and submits SPS header accordingly into the bitstream */
1920 ensure_sequence (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
1922 GstVaapiEncSequence *sequence = NULL;
1924 // Submit an SPS header before every new I-frame
1925 if (picture->type != GST_VAAPI_PICTURE_TYPE_I)
1928 sequence = GST_VAAPI_ENC_SEQUENCE_NEW (H264, encoder);
1929 if (!sequence || !fill_sequence (encoder, sequence))
1930 goto error_create_seq_param;
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;
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;
1944 gst_vaapi_enc_picture_set_sequence (picture, sequence);
1945 gst_vaapi_codec_object_replace (&sequence, NULL);
1950 error_create_seq_param:
1952 GST_ERROR ("failed to create sequence parameter buffer (SPS)");
1953 gst_vaapi_codec_object_replace (&sequence, NULL);
1956 error_create_packed_seq_hdr:
1958 GST_ERROR ("failed to create packed sequence header buffer");
1959 gst_vaapi_codec_object_replace (&sequence, NULL);
1964 /* Generates additional control parameters */
1966 ensure_misc_params (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
1968 GstVaapiEncMiscParam *misc = NULL;
1969 VAEncMiscParameterRateControl *rate_control;
1972 misc = GST_VAAPI_ENC_MISC_PARAM_NEW (HRD, encoder);
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);
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);
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);
2001 /* Generates and submits PPS header accordingly into the bitstream */
2003 ensure_picture (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture,
2004 GstVaapiCodedBufferProxy * codedbuf_proxy, GstVaapiSurfaceProxy * surface)
2006 GstVaapiCodedBuffer *const codedbuf =
2007 GST_VAAPI_CODED_BUFFER_PROXY_BUFFER (codedbuf_proxy);
2008 gboolean res = FALSE;
2010 res = fill_picture (encoder, picture, codedbuf, surface);
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");
2024 /* Generates slice headers */
2026 ensure_slices (GstVaapiEncoderH264 * encoder, GstVaapiEncPicture * picture)
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;
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");
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;
2049 if (!add_slice_headers (encoder, picture,
2050 reflist_0, reflist_0_count, reflist_1, reflist_1_count))
2056 /* Normalizes bitrate (and CPB size) for HRD conformance */
2058 ensure_bitrate_hrd (GstVaapiEncoderH264 * encoder)
2060 GstVaapiEncoder *const base_encoder = GST_VAAPI_ENCODER_CAST (encoder);
2061 guint bitrate, cpb_size;
2063 if (!base_encoder->bitrate) {
2064 encoder->bitrate_bits = 0;
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;
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;
2082 /* Estimates a good enough bitrate if none was supplied */
2084 ensure_bitrate (GstVaapiEncoderH264 * encoder)
2086 GstVaapiEncoder *const base_encoder = GST_VAAPI_ENCODER_CAST (encoder);
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;
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);
2112 base_encoder->bitrate = 0;
2115 ensure_bitrate_hrd (encoder);
2118 /* Constructs profile and level information based on user-defined limits */
2119 static GstVaapiEncoderStatus
2120 ensure_profile_and_level (GstVaapiEncoderH264 * encoder)
2122 ensure_tuning (encoder);
2124 if (!ensure_profile (encoder) || !ensure_profile_limits (encoder))
2125 return GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
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;
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;
2141 reset_properties (GstVaapiEncoderH264 * encoder)
2143 GstVaapiEncoder *const base_encoder = GST_VAAPI_ENCODER_CAST (encoder);
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;
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;
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);
2161 if (encoder->num_bframes > (base_encoder->keyframe_period + 1) / 2)
2162 encoder->num_bframes = (base_encoder->keyframe_period + 1) / 2;
2164 if (encoder->num_bframes)
2165 encoder->cts_offset = GST_SECOND * GST_VAAPI_ENCODER_FPS_D (encoder) /
2166 GST_VAAPI_ENCODER_FPS_N (encoder);
2168 encoder->cts_offset = 0;
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;
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;
2187 GstVaapiH264ViewReorderPool *const reorder_pool =
2188 &encoder->reorder_pools[i];
2189 reorder_pool->frame_index = 0;
2193 static GstVaapiEncoderStatus
2194 gst_vaapi_encoder_h264_encode (GstVaapiEncoder * base_encoder,
2195 GstVaapiEncPicture * picture, GstVaapiCodedBufferProxy * codedbuf)
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;
2202 reconstruct = gst_vaapi_encoder_create_surface (base_encoder);
2204 g_assert (GST_VAAPI_SURFACE_PROXY_SURFACE (reconstruct));
2206 if (!ensure_sequence (encoder, picture))
2208 if (!ensure_misc_params (encoder, picture))
2210 if (!ensure_picture (encoder, picture, codedbuf, reconstruct))
2212 if (!ensure_slices (encoder, picture))
2214 if (!gst_vaapi_enc_picture_encode (picture))
2217 if (!reference_list_update (encoder, picture, reconstruct))
2220 return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2223 gst_vaapi_encoder_release_surface (GST_VAAPI_ENCODER (encoder),
2228 static GstVaapiEncoderStatus
2229 gst_vaapi_encoder_h264_flush (GstVaapiEncoder * base_encoder)
2231 GstVaapiEncoderH264 *const encoder =
2232 GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2233 GstVaapiH264ViewReorderPool *reorder_pool;
2234 GstVaapiEncPicture *pic;
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;
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);
2248 g_queue_clear (&reorder_pool->reorder_frame_list);
2251 return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2254 /* Generate "codec-data" buffer */
2255 static GstVaapiEncoderStatus
2256 gst_vaapi_encoder_h264_get_codec_data (GstVaapiEncoder * base_encoder,
2257 GstBuffer ** out_buffer_ptr)
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;
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;
2273 if (!gst_buffer_map (encoder->sps_data, &sps_info, GST_MAP_READ))
2274 goto error_map_sps_buffer;
2276 if (!gst_buffer_map (encoder->pps_data, &pps_info, GST_MAP_READ))
2277 goto error_map_pps_buffer;
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];
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 */
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);
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);
2305 gst_buffer_unmap (encoder->pps_data, &pps_info);
2306 gst_buffer_unmap (encoder->sps_data, &sps_info);
2308 buffer = gst_buffer_new_wrapped (GST_BIT_WRITER_DATA (&bs),
2309 GST_BIT_WRITER_BIT_SIZE (&bs) / 8);
2311 goto error_alloc_buffer;
2312 *out_buffer_ptr = buffer;
2314 gst_bit_writer_clear (&bs, FALSE);
2315 return GST_VAAPI_ENCODER_STATUS_SUCCESS;
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);
2326 error_map_sps_buffer:
2328 GST_ERROR ("failed to map SPS packed header");
2329 return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
2331 error_map_pps_buffer:
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;
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;
2345 static GstVaapiEncoderStatus
2346 gst_vaapi_encoder_h264_reordering (GstVaapiEncoder * base_encoder,
2347 GstVideoCodecFrame * frame, GstVaapiEncPicture ** output)
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;
2357 /* encoding views alternatively for MVC */
2358 if (encoder->is_mvc) {
2360 encoder->view_idx = frame->system_frame_number % MAX_NUM_VIEWS;
2362 encoder->view_idx = (encoder->view_idx + 1) % MAX_NUM_VIEWS;
2364 reorder_pool = &encoder->reorder_pools[encoder->view_idx];
2367 if (reorder_pool->reorder_state != GST_VAAPI_ENC_H264_REORD_DUMP_FRAMES)
2368 return GST_VAAPI_ENCODER_STATUS_NO_SURFACE;
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);
2377 if (g_queue_is_empty (&reorder_pool->reorder_frame_list)) {
2378 reorder_pool->reorder_state = GST_VAAPI_ENC_H264_REORD_WAIT_FRAMES;
2383 /* new frame coming */
2384 picture = GST_VAAPI_ENC_PICTURE_NEW (H264, encoder, frame);
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;
2390 ++reorder_pool->cur_present_index;
2391 picture->poc = ((reorder_pool->cur_present_index * 2) %
2392 encoder->max_pic_order_cnt);
2394 is_idr = (reorder_pool->frame_index == 0 ||
2395 reorder_pool->frame_index >= encoder->idr_period);
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;
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;
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);
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;
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;
2436 ++reorder_pool->cur_frame_num;
2437 set_p_frame (picture, encoder);
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,
2442 reorder_pool->reorder_state = GST_VAAPI_ENC_H264_REORD_DUMP_FRAMES;
2443 g_assert (!g_queue_is_empty (&reorder_pool->reorder_frame_list));
2448 frame = picture->frame;
2449 if (GST_CLOCK_TIME_IS_VALID (frame->pts))
2450 frame->pts += encoder->cts_offset;
2453 return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2456 static GstVaapiEncoderStatus
2457 set_context_info (GstVaapiEncoder * base_encoder)
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;
2464 /* Maximum sizes for common headers (in bits) */
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,
2474 if (!ensure_hw_profile (encoder))
2475 return GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
2477 base_encoder->num_ref_frames =
2478 ((encoder->num_bframes ? 2 : 1) + DEFAULT_SURFACES_COUNT)
2479 * encoder->num_views;
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;
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;
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;
2496 /* Account for slice header */
2497 base_encoder->codedbuf_size += encoder->num_slices * (4 +
2498 GST_ROUND_UP_8 (MAX_SLICE_HDR_SIZE) / 8);
2500 return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2503 static GstVaapiEncoderStatus
2504 gst_vaapi_encoder_h264_reconfigure (GstVaapiEncoder * base_encoder)
2506 GstVaapiEncoderH264 *const encoder =
2507 GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2508 GstVaapiEncoderStatus status;
2510 encoder->mb_width = (GST_VAAPI_ENCODER_WIDTH (encoder) + 15) / 16;
2511 encoder->mb_height = (GST_VAAPI_ENCODER_HEIGHT (encoder) + 15) / 16;
2513 status = ensure_profile_and_level (encoder);
2514 if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
2517 reset_properties (encoder);
2518 return set_context_info (base_encoder);
2522 gst_vaapi_encoder_h264_init (GstVaapiEncoder * base_encoder)
2524 GstVaapiEncoderH264 *const encoder =
2525 GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2528 /* Multi-view coding information */
2529 encoder->is_mvc = FALSE;
2530 encoder->num_views = 1;
2531 encoder->view_idx = 0;
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;
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;
2557 gst_vaapi_encoder_h264_finalize (GstVaapiEncoder * base_encoder)
2559 /*free private buffers */
2560 GstVaapiEncoderH264 *const encoder =
2561 GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2562 GstVaapiEncPicture *pic;
2563 GstVaapiEncoderH264Ref *ref;
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);
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);
2577 g_queue_clear (&ref_pool->ref_list);
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);
2589 g_queue_clear (&reorder_pool->reorder_frame_list);
2593 static GstVaapiEncoderStatus
2594 gst_vaapi_encoder_h264_set_property (GstVaapiEncoder * base_encoder,
2595 gint prop_id, const GValue * value)
2597 GstVaapiEncoderH264 *const encoder =
2598 GST_VAAPI_ENCODER_H264_CAST (base_encoder);
2601 case GST_VAAPI_ENCODER_H264_PROP_MAX_BFRAMES:
2602 encoder->num_bframes = g_value_get_uint (value);
2604 case GST_VAAPI_ENCODER_H264_PROP_INIT_QP:
2605 encoder->init_qp = g_value_get_uint (value);
2607 case GST_VAAPI_ENCODER_H264_PROP_MIN_QP:
2608 encoder->min_qp = g_value_get_uint (value);
2610 case GST_VAAPI_ENCODER_H264_PROP_NUM_SLICES:
2611 encoder->num_slices = g_value_get_uint (value);
2613 case GST_VAAPI_ENCODER_H264_PROP_CABAC:
2614 encoder->use_cabac = g_value_get_boolean (value);
2616 case GST_VAAPI_ENCODER_H264_PROP_DCT8X8:
2617 encoder->use_dct8x8 = g_value_get_boolean (value);
2619 case GST_VAAPI_ENCODER_H264_PROP_CPB_LENGTH:
2620 encoder->cpb_length = g_value_get_uint (value);
2622 case GST_VAAPI_ENCODER_H264_PROP_NUM_VIEWS:
2623 encoder->num_views = g_value_get_uint (value);
2626 return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
2628 return GST_VAAPI_ENCODER_STATUS_SUCCESS;
2631 GST_VAAPI_ENCODER_DEFINE_CLASS_DATA (H264);
2633 static inline const GstVaapiEncoderClass *
2634 gst_vaapi_encoder_h264_class (void)
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
2641 return &GstVaapiEncoderH264Class;
2645 * gst_vaapi_encoder_h264_new:
2646 * @display: a #GstVaapiDisplay
2648 * Creates a new #GstVaapiEncoder for H.264 encoding. Note that the
2649 * only supported output stream format is "byte-stream" format.
2651 * Return value: the newly allocated #GstVaapiEncoder object
2654 gst_vaapi_encoder_h264_new (GstVaapiDisplay * display)
2656 return gst_vaapi_encoder_new (gst_vaapi_encoder_h264_class (), display);
2660 * gst_vaapi_encoder_h264_get_default_properties:
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.
2667 * Return value: the set of encoder properties for #GstVaapiEncoderH264,
2668 * or %NULL if an error occurred.
2671 gst_vaapi_encoder_h264_get_default_properties (void)
2673 const GstVaapiEncoderClass *const klass = gst_vaapi_encoder_h264_class ();
2676 props = gst_vaapi_encoder_properties_get_default (klass);
2681 * GstVaapiEncoderH264:max-bframes:
2683 * The number of B-frames between I and P.
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));
2692 * GstVaapiEncoderH264:init-qp:
2694 * The initial quantizer value.
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));
2703 * GstVaapiEncoderH264:min-qp:
2705 * The minimum quantizer value.
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));
2714 * GstVaapiEncoderH264:num-slices:
2716 * The number of slices per frame.
2718 GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2719 GST_VAAPI_ENCODER_H264_PROP_NUM_SLICES,
2720 g_param_spec_uint ("num-slices",
2722 "Number of slices per frame",
2723 1, 200, 1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2726 * GstVaapiEncoderH264:cabac:
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.
2732 GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2733 GST_VAAPI_ENCODER_H264_PROP_CABAC,
2734 g_param_spec_boolean ("cabac",
2736 "Enable CABAC entropy coding mode",
2737 FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2740 * GstVaapiEncoderH264:dct8x8:
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.
2746 GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2747 GST_VAAPI_ENCODER_H264_PROP_DCT8X8,
2748 g_param_spec_boolean ("dct8x8",
2750 "Enable adaptive use of 8x8 transforms in I-frames",
2751 FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2754 * GstVaapiEncoderH264:cpb-length:
2756 * The size of the CPB buffer in milliseconds.
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));
2766 * GstVaapiEncoderH264:num-views:
2768 * The number of views for MVC encoding .
2770 GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
2771 GST_VAAPI_ENCODER_H264_PROP_NUM_VIEWS,
2772 g_param_spec_uint ("num-views",
2774 "Number of Views for MVC encoding",
2775 1, MAX_NUM_VIEWS, 1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2781 * gst_vaapi_encoder_h264_set_max_profile:
2782 * @encoder: a #GstVaapiEncoderH264
2783 * @profile: an H.264 #GstVaapiProfile
2785 * Notifies the @encoder to use coding tools from the supplied
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.
2792 * Return value: %TRUE on success
2795 gst_vaapi_encoder_h264_set_max_profile (GstVaapiEncoderH264 * encoder,
2796 GstVaapiProfile profile)
2800 g_return_val_if_fail (encoder != NULL, FALSE);
2801 g_return_val_if_fail (profile != GST_VAAPI_PROFILE_UNKNOWN, FALSE);
2803 if (gst_vaapi_profile_get_codec (profile) != GST_VAAPI_CODEC_H264)
2806 profile_idc = gst_vaapi_utils_h264_get_profile_idc (profile);
2810 encoder->max_profile_idc = profile_idc;
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
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.
2825 * Return value: %TRUE on success
2828 gst_vaapi_encoder_h264_get_profile_and_level (GstVaapiEncoderH264 * encoder,
2829 GstVaapiProfile * out_profile_ptr, GstVaapiLevelH264 * out_level_ptr)
2831 g_return_val_if_fail (encoder != NULL, FALSE);
2833 if (!encoder->profile || !encoder->level)
2836 if (out_profile_ptr)
2837 *out_profile_ptr = encoder->profile;
2839 *out_level_ptr = encoder->level;