/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
 * Copyright (c) 2020 MediaTek Inc.
 */
//NALU type H264
#include "mtk_mvd_framing.h"
#ifdef ENABLE_REE_PARSE_HEADER
#define PAS_DEBUG_LOG(_dbgLevel_, _fmt, _args...) { \
	if ((_dbgLevel_ & pas_log_level) != 0) { \
		if (_dbgLevel_ & PAS_LOG_LEVEL_ERROR) { \
			pr_err("<mdbgerr_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_WARN) { \
			pr_err("<mdbgwrn_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_INFO) { \
			pr_err("<mdbginfo_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_DEBUG) { \
			pr_err("<mdbgdbg_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_FRAMING) { \
			pr_err("<mdbgfrm_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_STATIC) { \
			pr_err("<mdbgst_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_PTS) { \
			pr_err("<mdbgpts_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_BUF) { \
			pr_err("<mdbgbuf_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
		else if (_dbgLevel_ & PAS_LOG_LEVEL_VERBOSE) { \
			pr_err("<mdbgver_vpas> %s,%u "_fmt, __func__, __LINE__, ##_args); \
		} \
	} \
}

#define YUV400 0
#define YUV420 1
#define YUV422 2
#define YUV444 3

// H264 PROFILE IDC
#define CAVLC444_INTRA    44
#define BASELINE          66
#define MAIN_PROFILE      77
#define SCALABLE_BASELINE 83
#define SCALABLE_HIGH     86
#define EXT_PROFILE       88
#define FREXT_HP          100      //!< YUV 4:2:0/8 "High"
#define FREXT_Hi10P       110      //!< YUV 4:2:0/10 "High 10"
#define MVC_HIGH          118
#define FREXT_Hi422       122      //!< YUV 4:2:2/10 "High 4:2:2"
#define FREXT_Hi444       144      //!< YUV 4:4:4/12 "High 4:4:4"
#define MVC_STEREO        128
#define Hi444_PREDICTIVE  244


#define NON_IDR_SLICE 0x01
#define IDR_SLICE 0x05
#define SEI 0x06
#define SPS 0x07
#define PPS 0x08
#define AUD 0x09

#define CODED_SLICE_EXT 0x14    // 20
#define VDEC_HAL_RET_OK 0
#define VDEC_HAL_RET_FAIL 1
#define CACHE_SIZE 128 // origin 32

// Slice_type
#define P_Slice 0
#define B_Slice 1
#define I_Slice 2
#define SP_Slice 3
#define SI_Slice 4
#define P_Slice_ALL 5
#define B_Slice_ALL 6
#define I_Slice_ALL 7
#define SP_Slice_ALL 8
#define SI_Slice_ALL 9

#define IS_SLICE(btype) ((btype == I_Slice) || (btype == SI_Slice) \
		|| (btype == I_Slice_ALL) || (btype == SI_Slice_ALL))
#define IS_P_SLICE(btype) ((btype == P_Slice) || (btype == SP_Slice) \
		|| (btype == P_Slice_ALL) || (btype == SP_Slice_ALL))
#define IS_B_SLICE(btype) ((btype == B_Slice) || (btype == B_Slice_ALL))
/* invalid param */
#define VDEC_HAL_RET_H264_INVALID_PARAM		0x05000001

#define SYNTAX_OK                               (0)
#define SYNTAX_ERROR                            (0xf000)
#define SYNTAX_PARSE_BEGIN                      (0xf001)
#define SYNTAX_ERROR_NAL_TYPE                   (0xf002)
#define SYNTAX_ERROR_LAYER_ID                   (0xf003)

// VPS syntax
#define VPS_OK                                  (SYNTAX_OK)
#define VPS_MAX_SUB_LAYER                       (0xfc02)
#define VPS_PTL                                 (0xfc03)

//SPS syntax error
#define SPS_OK                              (SYNTAX_OK)
#define SPS_LAYER_CONFLICT                  (0xff02)
#define SPS_ID_INVLID                       (0xff03)
#define SPS_BITDEPTH_NOT_SUPPORT            (0xff04)
#define SPS_SL_SYNTAX_ERROR                 (0xff05)
#define SPS_RPS_SYNTAX_ERROR                (0xff06)
#define SPS_MAX_SUB_LAYER                   (0xff07)
#define SPS_PTL                             (0xff08)
#define SPS_CHROMA_FORMAT_IDC_NOT_SUPPORT   (0xff09)
#define SPS_RESOLUTION                      (0xff0a)
#define SPS_MAX_POC_LSB_M4                  (0xff0b)

//PPS syntax error
#define PPS_OK                                  (SYNTAX_OK)
#define PPS_ID_SYNTAX_ERROR                     (0xfe02)
#define PPS_NO_SPS_INFO_ERROR                   (0xfe03)
#define PPS_REF_NUM_ERROR                       (0xfe04)
#define PPS_QP_ERROR                            (0xfe05)
#define PPS_SCL_ERROR                           (0xfe06)
#define PPS_TILE_NUM_ERROR                      (0xfe07)

//Slice syntax error
#define SLICE_OK                                (SYNTAX_OK)
#define SLICE_PPS_ID_ERROR                      (0xfd02)
#define SLICE_ST_RPS_NULL                       (0xfd03)
#define SLICE_ST_DROP                           (0xfd04)
#define GET_FB_TIMEOUT                          (0xfd05)
//#define ALLOC_FBG_FAIL                          (0xfd06)
//#define SLICE_RES_CHG                           (0xfd07)
#define SLICE_RES_NOT_SUPPORT                   (0xfd08)

#define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
#define MAX_TLAYER                  8           ///< max number of temporal layer

#define SCALING_LIST_NUM 6         ///< list number for quantization matrix
#define SCALING_LIST_NUM_32x32 2   ///< list number for quantization matrix 32x32
#define SCALING_LIST_REM_NUM 6     ///< remainder of QP/6
#define SCALING_LIST_START_VALUE 8 ///< start value for dpcm mode
#define MAX_MATRIX_COEF_NUM 64     ///< max coefficient number for quantization matrix
#define MAX_MATRIX_SIZE_NUM 8      ///< max size number for quantization matrix
#define SCALING_LIST_DC 16         ///< default DC value
#define SCALING_LIST_UNIT_SIZE  4096

#define H264_MAX_SPS_NUM 32
#define H264_MAX_PPS_NUM 256

#define H265_MAX_VPS_NUM 16
#define H265_MAX_SPS_NUM 16
#define H265_MAX_PPS_NUM 64
#define H265_MAX_RPS_NUM 64

#define H265_MAX_LONG_TERM_REF_PIC_NUM 33

#define MAX_USER_DATA_PAYLOAD_SIZE (128)
#define MAX_LAST_SCAN_SIZE      (0x3FFF0)

#define MRG_MAX_NUM_CANDS 5
#define H265_SLICE_TYPE_MAX 3


#define MAX_VPS_NUM_LAYER_SETS 3  // max number of layer sets
#define MAX_VPS_NUM_ADD_LAYER_SETS 1024
#define MAX_VPS_NUM_SCALABILITY_TYPES 16
#define MAX_VPS_NUM_PROFILE_TIER_LEVEL 64
#define MAX_VPS_NUM_ADD_OLSS 1024
#define MAX_VPS_NUM_REP_FORMATS 256
#define MAX_VPS_NON_VUI_EXTENSION_LENGTH 4096
#define MAX_NUM_LAYER_IDS 64 // max number of layer id

#define H265_Main_Profile 1
#define H265_Main10_Profile 2
#define H265_Main_StillPic_Profile 3
#define H265_Format_Range_Extensions_Profiles 4
#define H265_High_Throughput_Profiles 5
#define H265_Screen_Content_Coding_Extensions_Profiles 9

#define MAX_LAYERS    (2)
#define MAX_LAYER_ID  (64)

#define SEI_OK  0

#define SEI_BUFFERING_PERIOD  0
#define SEI_PIC_TIMING  1
#define SEI_PAN_SCAN_RECT   2
#define SEI_FILLER_PAYLOAD  3
#define SEI_USER_DATA_REGISTERED_ITU_T_T35  4
#define SEI_USER_DATA_UNREGISTERED  5
#define SEI_RECOVERY_POINT  6
#define SEI_DEC_REF_PIC_MARKING_REPETITION  7
#define SEI_SPARE_PIC   8
#define SEI_SCENE_INFO  9
#define SEI_SUB_SEQ_INFO    10
#define SEI_SUB_SEQ_LAYER_CHARACTERISTICS   11
#define SEI_SUB_SEQ_CHARACTERISTICS 12
#define SEI_FULL_FRAME_FREEZE   13
#define SEI_FULL_FRAME_FREEZE_RELEASE   14
#define SEI_FULL_FRAME_SNAPSHOT 15
#define SEI_PROG_REFINEMENT_SEGMENT_START   16
#define SEI_PROG_REFINEMENT_SEGMENT_END 17
#define SEI_MOTION_CONSTRAINED_SLICE_GROUP_SET  18
#define SEI_FILM_GRAIN_CHARACTERISTICS  19
#define SEI_DEBLOCKING_FILTER_DISPLAY_PREFERENCE    20
#define SEI_STEREO_VIDEO_INFO   21

#define SEI_POST_FILTER_HINT    22
#define SEI_TONE_MAPPING_INFO    23
#define SEI_FRAME_PACKING    45
#define SEI_FRAME_PACKING_ARRANGE  45
#define SEI_DISPLAY_ORIENTATION    47
#define SEI_SOP_DESCRIPTION    128
#define SEI_ACTIVE_PARAMETER_SETS    129
#define SEI_DECODING_UNIT_INFO    130
#define SEI_TEMPORAL_LEVEL0_INDEX    131
#define SEI_DECODED_PICTURE_HASH    132
#define SEI_SCALABLE_NESTING    133
#define SEI_REGION_REFRESH_INFO    134
#define SEI_MASTERING_DISPLAY_COLOUR_VOLUME    137
#define SEI_SEGM_RECT_FRAME_PACKING    138
#define SEI_TEMP_MOTION_CONSTRAINED_TILE_SETS    139
#define SEI_CHROMA_SAMPLING_FILTER_HINT    140
#define SEI_CONTENT_LIGHT_LEVEL_INFO    144
#define SEI_ALTERNATIVE_TRANSFER_CHARACTERISTICS    147
#define SEI_FRAME_FIELD_INFO 168

#define VALID_MIN_SEI_SIZE  2
#define HEVC_SEI_FRAME_ONLY 0xFFFFFFFF

#ifdef SEI_MAX_ELEMENTS
#undef SEI_MAX_ELEMENTS
#endif
#define SEI_MAX_ELEMENTS    138
#define SEI_AFD_UNKONWN     0xFF

#define VDEC_VSD_CRC_SIZE 16
#define VDEC_MAX_CUVA_SIZE 256
#define VDEC_MAX_TCH_SIZE 256

#define MAX_USER_DATA 288
#define MAX_DV_DM_DATA  (256)
#define MAX_DV_RPU_DATA  (1024)
#define MAX_HDR10PLUS_DATA (128)

#define DV_COMP_SIZE (2048)
#define DV_DM_SIZE (1024)

#define INT_BYTE_SIZE 32
#define BYTE_SIZE 8
#define BYTE_SHIFT 3
#define EMULATION_PREVENTION_VALUE 0x03
#define VALUE_0   0
#define VALUE_1   1
#define VALUE_2   2
#define VALUE_3   3
#define VALUE_4   4
#define VALUE_5   5
#define VALUE_6   6
#define VALUE_7   7
#define VALUE_8   8
#define VALUE_9   9
#define VALUE_10   10
#define VALUE_11   11
#define VALUE_12   12
#define VALUE_13   13
#define VALUE_14   14
#define VALUE_15   15
#define VALUE_16   16
#define VALUE_17   17
#define VALUE_18   18
#define VALUE_19   19
#define VALUE_20   20
#define VALUE_21   21
#define VALUE_22   22
#define VALUE_23   23
#define VALUE_24   24
#define VALUE_25   25
#define VALUE_26   26
#define VALUE_27   27
#define VALUE_28   28
#define VALUE_29   29
#define VALUE_30   30
#define VALUE_31   31
#define VALUE_32   32
#define VALUE_33   33
#define VALUE_64   64
#define VALUE_255 255
#define VALUE_256 256

#define SHIFT_0                                                      0
#define SHIFT_1                                                      1
#define SHIFT_2                                                      2
#define SHIFT_3                                                      3
#define SHIFT_4                                                      4
#define SHIFT_5                                                      5
#define SHIFT_6                                                      6
#define SHIFT_7                                                      7
#define SHIFT_8                                                      8
#define SHIFT_9                                                      9
#define SHIFT_10                                                     10
#define SHIFT_11                                                     11
#define SHIFT_12                                                     12
#define SHIFT_13                                                     13
#define SHIFT_14                                                     14
#define SHIFT_15                                                     15

// HEVC
#define     NAL_UNIT_CODED_SLICE_TRAIL_N  0   // 0
#define     NAL_UNIT_CODED_SLICE_TRAIL_R 1 // 1
#define     NAL_UNIT_CODED_SLICE_TSA_N      2
#define     NAL_UNIT_CODED_SLICE_TLA        3 // Current name in the spec: TSA_R
#define     NAL_UNIT_CODED_SLICE_STSA_N 4  // 4
#define     NAL_UNIT_CODED_SLICE_STSA_R 5

#define     NAL_UNIT_CODED_SLICE_RADL_N 6
#define     NAL_UNIT_CODED_SLICE_DLP        7
#define     NAL_UNIT_CODED_SLICE_RASL_N  8
#define     NAL_UNIT_CODED_SLICE_TFD         9// Current name in the spec: RASL_R
#define     NAL_UNIT_RESERVED_VCL_N10 10
#define     NAL_UNIT_RESERVED_VCL_R11 11
#define     NAL_UNIT_RESERVED_VCL_N12 12
#define     NAL_UNIT_RESERVED_VCL_R13 13
#define     NAL_UNIT_RESERVED_VCL_N14 14
#define     NAL_UNIT_RESERVED_VCL_R15 15

#define     NAL_UNIT_CODED_SLICE_BLA            16   // Current name in the spec: BLA_W_LP
#define     NAL_UNIT_CODED_SLICE_BLANT              17 // Current name in the spec: BLA_W_DLP
#define     NAL_UNIT_CODED_SLICE_BLA_N_LP   18
#define     NAL_UNIT_CODED_SLICE_IDR                19 // Current name in the spec: IDR_W_DLP
#define     NAL_UNIT_CODED_SLICE_IDR_N_LP   20
#define     NAL_UNIT_CODED_SLICE_CRA            21
#define     NAL_UNIT_RESERVED_IRAP_VCL22 22
#define     NAL_UNIT_RESERVED_IRAP_VCL23 23

#define     NAL_UNIT_RESERVED_VCL24 24
#define     NAL_UNIT_RESERVED_VCL25 25
#define     NAL_UNIT_RESERVED_VCL26 26
#define     NAL_UNIT_RESERVED_VCL27 27
#define     NAL_UNIT_RESERVED_VCL28 28
#define     NAL_UNIT_RESERVED_VCL29 29
#define     NAL_UNIT_RESERVED_VCL30 30
#define     NAL_UNIT_RESERVED_VCL31 31

#define     NAL_UNIT_VPS        32
#define     NAL_UNIT_SPS        33
#define     NAL_UNIT_PPS        34
#define     NAL_UNIT_ACCESS_UNIT_DELIMITER  35
#define     NAL_UNIT_EOS        36
#define     NAL_UNIT_EOB        37
#define     NAL_UNIT_FILLER_DATA     38
#define     NAL_UNIT_SEI            39
#define     NAL_UNIT_SEI_SUFFIX         40

#define     NAL_UNIT_RESERVED_NVCL41 41
#define     NAL_UNIT_RESERVED_NVCL42 43
#define     NAL_UNIT_RESERVED_NVCL43 43
#define     NAL_UNIT_RESERVED_NVCL44 44
#define     NAL_UNIT_RESERVED_NVCL45 45
#define     NAL_UNIT_RESERVED_NVCL46 46
#define     NAL_UNIT_RESERVED_NVCL47 47
#define     NAL_UNIT_UNSPECIFIED_48 48
#define     NAL_UNIT_UNSPECIFIED_49 49
#define     NAL_UNIT_UNSPECIFIED_50 50
#define     NAL_UNIT_UNSPECIFIED_51 51
#define     NAL_UNIT_UNSPECIFIED_52 52
#define     NAL_UNIT_UNSPECIFIED_53 53
#define     NAL_UNIT_UNSPECIFIED_54 54
#define     NAL_UNIT_UNSPECIFIED_55 55
#define     NAL_UNIT_UNSPECIFIED_56 56
#define     NAL_UNIT_UNSPECIFIED_57 57
#define     NAL_UNIT_UNSPECIFIED_58 58
#define     NAL_UNIT_UNSPECIFIED_59 59
#define     NAL_UNIT_UNSPECIFIED_60 60
#define     NAL_UNIT_UNSPECIFIED_61 61
#define     NAL_UNIT_DV_RPU 62
#define     NAL_UNIT_UNSPECIFIED_63 63
#define     NAL_UNIT_INVALID 64

// start where to start get bit, bits: the number of bit we want to extract
#define GET_BITS(value, start, bits) \
(((value) >> (start)) & ((1 << (bits)) - 1))
enum ScalingListSize {
	SCALING_LIST_4x4 = 0,
	SCALING_LIST_8x8,
	SCALING_LIST_16x16,
	SCALING_LIST_32x32,
	SCALING_LIST_SIZE_NUM
};

enum COEFF_SCAN_TYPE {
	SCAN_DIAG = 0,         ///< up-right diagonal scan
	SCAN_HOR,              ///< horizontal first scan
	SCAN_VER               ///< vertical first scan
};

//const unsigned char start_code_3byte[3] = { 0, 0, 1 };
#define START_CODE_LEN 3


#define H265_MAX_FB_NUM 16

#define MAX_NUM_REF_PICS 32

#define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
#define MAX_TLAYER                  8           ///< max number of temporal layer
#define FALSE           (0 != 0)

/* Picture Externsion header*/
struct mpeg2_pic_ext_hdr_field {
	/* 32 Bit */
	unsigned int            chroma_420                :    1;
	unsigned int            rff                       :    1;
	unsigned int            alternate_scan            :    1;
	unsigned int            intra_vlc                 :    1;
	unsigned int            q_scale                   :    1;
	unsigned int            concealment_mv            :    1;
	unsigned int            frame_pred                :    1;
	unsigned int            tff                       :    1;
	// pic_structure: 0, reserved
	// pic_structure: 1, top field
	// pic_structure: 2, bottom field
	// pic_structure: 3, frame picture
	unsigned int            pic_structure             :    2;
	unsigned int            intra_dc_precision        :    2;
	unsigned int            fcode11                   :    4;
	unsigned int            fcode10                   :    4;
	unsigned int            fcode01                   :    4;
	unsigned int            fcode00                   :    4;
	unsigned int            ext_id                    :    4;

	/* 22 Bit */
	unsigned int                                      :    10;
	unsigned int            sub_carrier_phase         :    8;
	unsigned int            burst_amplitude           :    7;
	unsigned int            sub_carrier               :    1;
	unsigned int            field_sequence            :    3;
	unsigned int            v_axis                    :    1;
	unsigned int            composite_disp            :    1;
	unsigned int            prgs_frame                :    1;
};

union mpeg2_pic_ext_hdr {
	unsigned int                      reg[2];
	struct mpeg2_pic_ext_hdr_field    field;
};

#define MAX_VIEW_NUM 2
#define MAXNUM_REFFRAME_IN_POC_CYCLE  256
struct h264_sps_data {
	unsigned char   valid;                  // indicates the parameter set is valid

	unsigned int profile_idc;                                             // u(8)
	bool  constrained_set0_flag;                                          // u(1)
	bool  constrained_set1_flag;                                          // u(1)
	bool  constrained_set2_flag;                                          // u(1)
	bool  constrained_set3_flag;                                          // u(1)
	bool  constrained_set4_flag;                                          // u(1)
	bool  constrained_set5_flag;                                          // u(1)
	unsigned int level_idc;                                               // u(8)

	unsigned int seq_parameter_set_id;                                      // ue(v)
	unsigned int chroma_format_idc;                                         // ue(v)
	bool  residual_colortransform_flag;
	unsigned int bitdepth_luma_minus8;                                  // ue(v)
	unsigned int bitdepth_chroma_minus8;                              // ue(v)
	bool  qpprime_yzerotransform_bypass_flag;

	bool  seqscaling_matrix_present_flag;                     // u(1)
	bool  seqscalinglist_present_flag[8];                      // u(1)

	unsigned int log2_max_framenum_minus4;                       // ue(v)
	unsigned int max_framenum;
	unsigned int picordercnt_type;
	// if( pic_order_cnt_type == 0 )
	unsigned int log2_max_picordercnt_lsb_minus4;              // ue(v)
	// else if( pic_order_cnt_type == 1 )
	bool delta_picorder_alwayszero_flag;                   // u(1)
	signed int offset_for_non_refpic;                                     // se(v)
	signed int offset_for_top_to_bottom_field;                       // se(v)
	unsigned int numref_frames_in_picordercnt_cycle;       // ue(v)
	// for( i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++ )
	signed int offset_for_ref_frame[MAXNUM_REFFRAME_IN_POC_CYCLE];   // se(v)
	unsigned int num_refframes;                                      // ue(v)
	bool   gaps_in_framenum_value_allowed_flag;      // u(1)
	unsigned int pic_width_in_mbs_minus1;                              // ue(v)
	unsigned int pic_height_in_mapunits_minus1;                  // ue(v)
	bool   frame_mbs_Only_flag;                                     // u(1)
};

struct h264_pps_data {
	unsigned char   valid;

	unsigned int    pic_params_set_id;                                     // ue(v)
	unsigned int    seq_params_set_id;                                     // ue(v)
};

struct h264_slice_data {
	unsigned int first_mb_in_slice;
	unsigned int slice_type;
	unsigned int pic_params_set_id;
	unsigned int seq_params_set_id;
	unsigned int field_pic_flag;
	unsigned int bottom_field_flag;
	unsigned int frame_num;
	unsigned int is_ref;
};

struct h265_pic_tim_data {
	unsigned int    pic_struct;
	unsigned int    source_scan_type;
	bool            duplicate_flag;

	unsigned int    cpb_removal_delay_minus1;
	unsigned int    pic_dpb_output_delay;
	unsigned int    pic_dpb_output_du_delay;
	unsigned int    num_decoding_units_minus1;
	bool            du_com_cpb_removal_delay_flag;
	unsigned int    du_com_cpb_removal_delay_increment_minus1;

	//unsigned long long dpb_output_time;
	unsigned long long  removal_time;
	unsigned long long  removal_time_of_first_pic_info_bp;
	unsigned long long  removal_time_of_previous_pic;

	//unsigned int *pNumNalusInDuMinus1;
	//unsigned int *pDuCpbRemovalDelayIncrementMinus1;
};
#define MAX_CPB_CNT 32

//xvYCC
struct sei_xvycc_t {
	unsigned char   format_flag;
	unsigned char   ged_colour_precision;
	unsigned char   ged_colour_space;
	unsigned int    red_data;
	unsigned int    green_data;
	unsigned int    blue_data;
};

struct h265_buffering_period_t {
	unsigned short  seq_param_set_id;
	bool            rap_cpb_params_present_flag;
	bool            concaenation_flag;
	unsigned int    cpb_delay_offset;
	unsigned int    dpb_delay_offset;

	unsigned short  initial_cpb_removal_delay[MAX_CPB_CNT][VALUE_2];
	unsigned short  initial_cpb_removal_delay_offset[MAX_CPB_CNT][VALUE_2];
	unsigned short  initial_alt_cpb_removal_delay[MAX_CPB_CNT][VALUE_2];
	unsigned short  initial_alt_cpb_removal_delay_offset[MAX_CPB_CNT][VALUE_2];
};

struct h265_content_light_level {
	unsigned int    max_content_light_level;
	unsigned int    max_pic_average_light_level;
};

struct h265_master_display_color_volume {
	unsigned int    display_primarite_x[VALUE_3];
	unsigned int    display_primarite_y[VALUE_3];
	unsigned int    white_point_x;
	unsigned int    white_point_y;
	unsigned int    max_display_mastering_luminance;
	unsigned int    min_display_mastering_luminance;
};

struct h265_alternative_transfer_characteristics {
	unsigned int prefer_transfer_characteristics;
};

//struct for hdr10+ metadata
struct h265_user_data_registered_itu_t_t35_st_2094_40 {
	unsigned char   country_code;
	unsigned short  provider_code;
	unsigned short  oriented_code;
	unsigned char   identifier;
	unsigned char   version;
	unsigned char   num_windows;
	unsigned short  windows_upper_left_corner_x[VALUE_3];
	unsigned short  windows_upper_left_corner_y[VALUE_3];
	unsigned short  windows_lower_right_corner_x[VALUE_3];
	unsigned short  windows_lower_right_corner_y[VALUE_3];
	unsigned short  center_of_ellipse_x[VALUE_3];
	unsigned short  center_of_ellipse_y[VALUE_3];
	unsigned char   rotation_angle[VALUE_3];
	unsigned short  semi_major_axis_internal_ellipse[VALUE_3];
	unsigned short  semi_major_axis_external_ellipse[VALUE_3];
	unsigned short  semi_minor_axis_external_ellipse[VALUE_3];
	unsigned char   overlap_process_option[VALUE_3];

	unsigned int    target_system_display_maximum_luminance;
	bool            target_system_display_actual_peal_luminance_flag;

	unsigned char   num_rows_targeted_system_display_actual_peak_luminance;
	unsigned char   num_cols_targeted_system_display_actual_peak_luminance;
	unsigned char   targeted_system_display_actual_peak_luminance[VALUE_25][VALUE_25];

	unsigned int    max_scl[VALUE_3][VALUE_3];
	unsigned int    average_max_rgb[VALUE_3];
	unsigned char   num_distribution_max_rgb_percentiles[VALUE_3];
	unsigned char   distribution_max_rgb_percentages[VALUE_3][VALUE_15];
	unsigned int    distribution_max_rgb_percentiles[VALUE_3][VALUE_15];
	unsigned short  fraction_bright_pixels[VALUE_3];

	bool            mastering_display_actual_peak_luminance_flag;

	unsigned char   num_rows_mastering_display_actual_peak_luminance;
	unsigned char   num_cols_mastering_display_actual_peak_luminance;
	unsigned char   mastering_display_actual_peak_luminance[VALUE_25][VALUE_25];

	bool            tone_mapping_flag[VALUE_3];
	unsigned short  knee_point_x[VALUE_3];
	unsigned short  knee_point_y[VALUE_3];
	unsigned char   num_bezier_curve_anchors[VALUE_3];
	unsigned short  bezier_curve_anchors[VALUE_3][VALUE_15];
	bool            color_saturation_mapping_flag[VALUE_3];
	unsigned char   color_saturation_weight[VALUE_3];
};

struct h265_user_data_registered_itu_t_t35_cuva_hdr {
	unsigned char   country_code;
	unsigned short  provider_code;
	unsigned short  oriented_code;
	unsigned char   cuva_hdr_metadata[VDEC_MAX_CUVA_SIZE];
	unsigned int    cuva_hdr_metadata_len;
};

struct h265_user_data_registered_itu_t_t35_tch_1_3 {
	unsigned char   ts_103_433_spec_version;
	unsigned char   ts_103_433_payload_mode;
	unsigned char   cv_rev_id;
	bool            cv_rev_cancel_flag;
	bool            cv_rec_persistence_flag;
	bool            cv_rec_target_info_flag;
	unsigned char   cv_rec_primaries;
	unsigned char   cv_rec_matrix_coefficients;
	unsigned char   tone_mapping_input_signal_black_level_offset;
	unsigned char   tone_mapping_input_signal_white_level_offset;
	unsigned char   shadow_gain_control;
	unsigned char   highlight_gain_control;
	unsigned char   mid_tone_width_adjustment_factor;
	unsigned char   tone_mapping_output_fine_tuning_num_val;
	unsigned char   tone_mapping_output_fine_tuning_x[VALUE_16];
	unsigned char   tone_mapping_output_fine_tuning_y[VALUE_16];
	unsigned char   saturation_gain_num_val;
	unsigned char   saturation_gain_x[VALUE_16];
	unsigned char   saturation_gain_y[VALUE_16];
};

struct h265_user_data_registered_itu_t_t35_sl_hdr {
	unsigned char   country_code;
	unsigned short  provider_code;
	unsigned short  oriented_code;
	unsigned char   sl_hdr_metadata[VDEC_MAX_TCH_SIZE];
	unsigned int    sl_hdr_metadata_len;
};

struct sl_hdr_metadata_variables {
	int     tm_input_signal_black_level_offset;
	int     tm_input_signal_white_level_offset;
	int     shadow_gain;
	int     highlight_gain;
	int     mid_tone_width_adj_factor;
	int     tm_output_fine_tuning_num_val;
	int     tm_output_fine_tuning_x[VALUE_10];
	int     tm_output_fine_tuning_y[VALUE_10];
	int     saturation_gain_num_val;
	int     saturation_gain_x[VALUE_6];
	int     saturation_gain_y[VALUE_6];
};
#define VALUE_65 65
struct sl_hdr_metadata_tables {
	int     luminance_mapping_num_val;
	int     luminance_mapping_x[VALUE_65];
	int     luminance_mapping_y[VALUE_65];
	int     colour_correction_num_val;
	int     colour_correction_x[VALUE_65];
	int     colour_correction_y[VALUE_65];
};

struct sl_hdr_metadata {
	int     part_id;
	int     major_spec_version_id;
	int     minor_spec_version_id;
	int     payload_mode;
	int     hdr_pic_colour_space;
	int     hdr_display_colour_space;
	int     hdr_display_max_luminance;
	int     hdr_display_min_luminance;
	int     sdr_pic_colour_space;
	int     sdr_display_colour_space;
	int     sdr_display_max_luminance;
	int     sdr_display_min_luminance;
	int     matrix_coeffcient[VALUE_4];
	int     chroma_to_luma_injection[VALUE_2];
	int     k_coeffcient[VALUE_3];
	union {
		struct sl_hdr_metadata_variables  metadata_variables;
		struct sl_hdr_metadata_tables     metadata_tables;
	};
};

enum ENUM_VDEC_DOLBYRPU_TYPE {
	VDEC_DOLBY_NONE = 0,
	VDEC_DOLBY_RPU = 1,
	VDEC_DOLBY_SMPTE2094 = 2,
};

struct h265_sei_data {
	bool    active;

	struct sei_xvycc_t    xvycc_info;
	unsigned int    payload_size;
	// CC info
	unsigned char   user_data[MAX_USER_DATA];
	unsigned int    cc_data_len;

	union {
		unsigned char ucDolbyData2094[MAX_DV_DM_DATA];
		unsigned char ucDolbyDataRPU[MAX_DV_RPU_DATA];
	};
	enum ENUM_VDEC_DOLBYRPU_TYPE eRPUType;
	unsigned int u4RPUDataLen;

	unsigned char ucHDR10PlusRaw[MAX_HDR10PLUS_DATA];
	unsigned int u4HDR10PlusRawLen;

	bool            new_bp_start_flag;

	unsigned int    delta_to_divisor;
	unsigned int    buffering_period_num;
	unsigned int    last_gop_size;
	unsigned int    sei_timing_num;
	unsigned int    sei_timing_num_sub;

	// calculated from the SEI information
	unsigned long long  dpb_output_time;

	// Picture timing info
	struct h265_pic_tim_data        pic_tim_data;
	struct h265_buffering_period_t  buffering_period;

	bool        recovery_point;
	int         recovery_poc_cnt;
	bool        exact_match_flag;
	bool        broken_link_flag;

	// Mastering Display Colour Volume info
	bool        master_display_color_vol_flag;
	struct h265_master_display_color_volume master_display_color_volume;
	// Content Light Level info
	bool        content_light_level_flag;
	struct h265_content_light_level content_light_level;
	// Hdr Compatibility info
	bool        compatiblity_flag;
	struct h265_alternative_transfer_characteristics alt_transfer_characteristics;
	//HDR 10+ metadata
	bool        hdr10_plus_flag;
	struct h265_user_data_registered_itu_t_t35_st_2094_40
		user_data_registered_itu_t_t35_st_2094_40;
	//Cuva Hdr
	bool        cuva_hdr_flag;
	struct h265_user_data_registered_itu_t_t35_cuva_hdr
		user_data_registered_itu_t_t35_st_cuva_hdr;
	//SL HDR
	bool        sl_hdr_flag;
	struct h265_user_data_registered_itu_t_t35_sl_hdr
		user_data_registered_itu_t_t35_sl_hdr;
	//TCH 1.3
	struct h265_user_data_registered_itu_t_t35_tch_1_3
		user_data_registered_itu_t_t35_tch_1_3;

	struct sl_hdr_metadata hdr_meta_data;
	bool   tech_hdr_flag;
	bool   smpte2094_flag;
	unsigned char u1AFD;
	bool bFilmMaker;
	unsigned char ucDolbyDMData[DV_DM_SIZE];
	unsigned int u4DMSize;
	unsigned char ucDolbyCOMPData[DV_COMP_SIZE];
	unsigned int u4COMPSize;
	unsigned char ecosystem_ide;
};

struct h265_sub_hrd_data { //HRD Sub Layer Info
	unsigned char   fixed_pic_rate_flag;
	unsigned char   fixed_pic_rate_within_cvs_flag;
	unsigned int    elemental_duration_in_tc_minus1;
	unsigned char   low_delay_hrd_flag;
	unsigned int    cpb_cnt_minus1;
	unsigned int    bit_rate_value_minus1[MAX_CPB_CNT][VALUE_2];
	unsigned int    cpb_size_value_minus1[MAX_CPB_CNT][VALUE_2];
	unsigned int    du_cpb_size_value_minus1[MAX_CPB_CNT][VALUE_2];
	unsigned int    du_bit_rate_value_minus1[MAX_CPB_CNT][VALUE_2];
	unsigned char   cbr_flag[MAX_CPB_CNT][VALUE_2];
};

struct h265_hrd_data { //HRD Sub Layer Info
	unsigned char   nal_hrd_params_present_flag;
	unsigned char   vcl_hrd_params_present_flag;
	unsigned char   sub_pic_cpb_params_present_flag;
	unsigned int    tick_divisor_minus2;
	unsigned int    du_cpb_removal_delay_length_minus1;
	unsigned char   sub_pic_cpb_params_in_pic_timing_sei_flag;
	unsigned int    dpb_output_delay_du_length_minus1;

	unsigned int    bitrate_scale;
	unsigned int    cpb_size_scale;
	unsigned int    du_cpb_size_scale;
	unsigned int    initial_cpb_removal_delay_length_minus1;
	unsigned int    au_cpb_removel_delay_length_minus1;
	unsigned int    dpb_output_delay_length_minus1;

	struct h265_sub_hrd_data sub_layer_hrd[MAX_TLAYER];
};

struct h265_sl_data {
	unsigned char
	scaling_list_dc[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
	//!< the DC value of the matrix coefficient for 16x16
	unsigned char
	scaling_list_delta_coef[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][MAX_MATRIX_COEF_NUM];
	bool            use_transform_skip;
};

struct h265_rps_data {
	unsigned int    num_of_pics;
	unsigned int    num_of_negative_pics;
	unsigned int    num_of_positive_pics;
	unsigned int    num_of_long_term_pics;
	unsigned int    num_ref_idc;
	unsigned int    ref_idc[MAX_NUM_REF_PICS+1];
	int     delta_poc[MAX_NUM_REF_PICS+1];
	int     poc[MAX_NUM_REF_PICS];
	bool    used[MAX_NUM_REF_PICS+1];
	bool    inter_rps_prediction;
	bool    check_lt_msb[MAX_NUM_REF_PICS];
};
struct h265_ptl_flag_data {
	unsigned int      profile_space;
	unsigned char     tier_flag;
	unsigned int      profile_idc;
	unsigned char     profile_compatibility_flag[VALUE_32];
	unsigned int      level_idc;

	unsigned char     progressive_source_flag;
	unsigned char     interlaced_source_flag;
	unsigned char     non_packed_constraint_flag;
	unsigned char     frame_only_constraint_flag;
	unsigned char     general_max_14bit_constraint_flag;
	unsigned char     general_max_12bit_constraint_flag;
	unsigned char     general_max_10bit_constraint_flag;
	unsigned char     general_max_8bit_constraint_flag;
	unsigned char     general_max_422_chroma_constraint_flag;
	unsigned char     general_max_420_chroma_constraint_flag;
	unsigned char     general_max_mono_chroma_constraint_flag;
	unsigned char     general_intra_constraint_flag;
	unsigned char     general_one_picture_only_constraint_flag;
	unsigned char     general_lower_bit_rate_constraint_flag;
};

struct h265_ptl_data {
	unsigned char                 profile_present_flag;
	struct h265_ptl_flag_data      general_PTL;
	struct h265_ptl_flag_data      sub_layer_PTL[VALUE_6];
	unsigned char         sub_layer_profile_present_flag[VALUE_6];
	unsigned char         sub_layer_level_present_flag[VALUE_6];
};

#define vdec_address_type			unsigned long long /* 64bit */

#define abs_hevc(x) (((x) >= 0) ? (x) : -(x))
#define min_hevc(x, y) (((x) < (y)) ? (x) : (y))
#define max_hevc(x, y) (((x) > (y)) ? (x) : (y))
#define align64_hevc(val) ((((val) + 0x3F) >> 6) << 6)
#define align32_hevc(val) ((((val) + 0x1F) >> 5) << 5)
#define align16_hevc(val) ((((val) + 0xF) >> 4) << 4)

// scanning order table
#define     MAX_CU_DEPTH            7                           // log2(LCUSize)
#define     MAX_CU_SIZE             (1<<(MAX_CU_DEPTH))         // maximum allowable size of CU
#define     MAX_LAST_SCAN_SIZE      (0x3FFF0)

static unsigned int *h265_aui_sig_last_scan[3][MAX_CU_DEPTH];

static const unsigned int h265_scaling_list_size[4] = { 16, 64, 256, 1024 };
static const unsigned int h265_scaling_list_num[SCALING_LIST_SIZE_NUM] = { 6, 6, 6, 2 };

static unsigned int h265_sig_last_scan_cg32x32[64];

static unsigned char h265_quant_ts_default_4x4[16] = {
	16, 16, 16, 16,
	16, 16, 16, 16,
	16, 16, 16, 16,
	16, 16, 16, 16,
};

static unsigned char h265_quant_intra_default_8x8[64] = {
	16, 16, 16, 16, 17, 18, 21, 24,
	16, 16, 16, 16, 17, 19, 22, 25,
	16, 16, 17, 18, 20, 22, 25, 29,
	16, 16, 18, 21, 24, 27, 31, 36,
	17, 17, 20, 24, 30, 35, 41, 47,
	18, 19, 22, 27, 35, 44, 54, 65,
	21, 22, 25, 31, 41, 54, 70, 88,
	24, 25, 29, 36, 47, 65, 88, 115
};

static unsigned char h265_quant_inter_default_8x8[64] = {
	16, 16, 16, 16, 17, 18, 20, 24,
	16, 16, 16, 17, 18, 20, 24, 25,
	16, 16, 17, 18, 20, 24, 25, 28,
	16, 17, 18, 20, 24, 25, 28, 33,
	17, 18, 20, 24, 25, 28, 33, 41,
	18, 20, 24, 25, 28, 33, 41, 54,
	20, 24, 25, 28, 33, 41, 54, 71,
	24, 25, 28, 33, 41, 54, 71, 91
};

enum SliceType {
	HEVC_B_SLICE,
	HEVC_P_SLICE,
	HEVC_I_SLICE
};

struct h265_vui_data {
	unsigned char   aspect_ratio_present_flag;
	int             aspect_ratio_idc;
	int             sar_width;
	int             sar_height;
	unsigned char   overscan_info_present_flag;
	unsigned char   overscan_appropriate_flag;
	unsigned char   video_signal_type_present_flag;
	int             video_format;
	unsigned char   video_full_range_flag;
	unsigned char   colour_description_present_flag;
	int             colour_primaries;
	int             transfer_characteristics;
	int             sei_alt_transfer_characteristics;
	int             matrix_coeffcients;
	unsigned char   chroma_loc_info_present_flag;
	int             chroma_sample_loc_type_top_field;
	int             chroma_sample_loc_type_bottom_field;
	unsigned char   neutral_chroma_indication_flag;
	unsigned char   field_seq_flag;

	//DefaultDisplayWindow
	unsigned char   default_display_window_enable_flag;
	int             default_display_window_left_offset;
	int             default_display_window_right_offset;
	int             default_display_window_top_offset;
	int             default_display_window_bottom_offset;

	unsigned char   frame_field_info_present_flag;
	unsigned char   hrd_params_present_flag;
	struct h265_hrd_data    hdr_params;

	unsigned char   bitstream_restriction_flag;
	unsigned char   tiles_fixed_structure_flag;
	unsigned char   motion_vectors_over_pic_boundaried_flag;
	unsigned char   restricted_ref_pic_lists_flag;
	int             min_spatial_segmentation_idc;
	int             max_bytes_per_pic_denom;
	int             max_bits_per_min_cu_denom;
	int             log2_max_mv_length_horizontal;
	int             log2_max_mv_length_vertical;

	//TimingInfo
	unsigned char   timing_info_present_flag;
	unsigned int    num_units_in_tick;
	unsigned int    time_scale;
	unsigned char   proc_proportional_to_timing_flag;
	int             num_ticks_poc_diff_one_minus1;
};

struct h265_sps_data {
	unsigned char   valid;
	unsigned int    sps_id;
	unsigned int    vps_id;                         // u(4)
	unsigned int    layer_id;
	unsigned int    layer_idx;
	union {
		unsigned int    max_t_layers_minus1;  // u(3)
		unsigned int    sps_ext_or_max_sub_layers_minus1;
	};
	bool multi_layer_ext_sps_flag;
	unsigned char   temporal_id_nesting_flag;                   // u(1)
	struct h265_ptl_data   sps_PTL;                    // ProfileTierLevel

	bool            update_rep_format_flag;  // u(1)
	unsigned int    sps_rep_format_idx;  // u(8)
	unsigned int    chroma_format_idc;    // ue(v)
	unsigned char   separate_colour_plane_flag;
	unsigned int    pic_width_in_luma_samples;    // ue(v)
	unsigned int    pic_height_in_luma_samples;    // ue(v)

	unsigned char   conformance_window_flag;              // u(1)
	unsigned int    conformance_win_left_offset;           // ue(v)
	unsigned int    conformance_win_right_offset;         // ue(v)
	unsigned int    conformance_win_top_offset;           // ue(v)
	unsigned int    conformance_win_bottom_offset;     // ue(v)

	unsigned int    sub_width_c;
	unsigned int    sub_height_c;
	unsigned int    frame_crop_left_offset;
	unsigned int    frame_crop_right_offset;
	unsigned int    frame_crop_top_offset;
	unsigned int    frame_crop_bottom_offset;

	unsigned int    bit_depth_luma_minus8;             // ue(v)
	unsigned int    bit_depth_chroma_minus8;        // ue(v)
	unsigned int    qpbd_offset_y;
	unsigned int    qpbd_offset_c;                   // ue(v)

	unsigned int    log2_max_pic_order_cnt_lsb_minus4;              // ue(v)

	//[notice] spec conflict u4MaxDecPicBufferingMinux1? u4MaxLatencyIncreasePlus1?
	unsigned int    max_dec_pic_buffering[8];        // ue(v)
	unsigned int    num_reorder_pics[8];             // ue(v)
	unsigned int    max_latency_increase[8];       // ue(v)

	unsigned int    log2_min_coding_block_size_minus3;     // ue(v)
	unsigned int    log2_diff_max_min_coding_block_size;    // ue(v)
	unsigned int    max_cu_width;
	unsigned int    max_cu_height;

	unsigned int    log2_min_transform_blcok_size_minus2;      // ue(v)
	unsigned int    log2_diff_max_min_t_transform_block_size;     // ue(v)
	unsigned int    quad_tree_tu_max_depth_inter;      // ue(v)
	unsigned int    quad_tree_tu_max_depth_intra;     // ue(v)
	unsigned int    u4MaxTrSize;
	unsigned int    u4MaxCUDepth;

	bool            sps_infer_scaling_list_flag;  // u(1)
	unsigned int    sps_scaling_list_ref_layer_id;  // u(1)

	unsigned char   scaling_list_flag;                                 // u(1)
	unsigned char   scaling_list_present_flag;                   // u(1)
	unsigned char   sl_init;
	struct h265_sl_data
		sps_scaling_list;                               //ScalingList

	unsigned char   use_amp;                                           // u(1)
	unsigned char   use_sao;                                           // u(1)
	unsigned char   use_pcm;                                            // u(1)

	unsigned int    pcm_bit_depth_luma_minus1;          // u(4)
	unsigned int    pcm_bit_depth_chroma_minus1;     // u(4)
	unsigned int    pcm_log2_luma_min_size_minus3;      // ue(v)
	unsigned int    pcm_log2_luma_max_size;                  // ue(v)
	unsigned char   pcm_filter_disable_flag;                      // u(1)

	unsigned int    num_short_term_ref_pic_sets;            // ue(v)
	struct h265_rps_data
		short_term_ref_pic_sets[H265_MAX_RPS_NUM];            //RPS pointer array

	unsigned char   long_term_refs_present;                // u(1)
	unsigned int    num_long_term_ref_pic_sps;        // ue(v)
	unsigned int	long_term_ref_pic_poc_lsb_sps[VALUE_33];      // u(BitsForPOC)
	unsigned char   used_by_curr_pic_lt_sps_flag[VALUE_33];       // u(1)
	//unsigned int     u4NumRefFrames;

	int             str_num_delta_pocs;
	int             max_str_num_negtive_pos_pics;
	int             str_num_negtive_pos_pics;
	int             num_long_term;
	int             num_long_term_sps;

	unsigned char   tmvp_flags_present;                      // u(1)
	unsigned char   use_strong_intra_smoothing;            // u(1)
	unsigned char   vui_params_present_flag;         // u(1)
	struct h265_vui_data    vui;                  // vui_seq_parameters_t
	unsigned char   sps_extension_flag;                      // u(1)
	// read sps_extension_data_flag
};

struct h265_pps_data {
	unsigned char   valid;

	unsigned int    pic_params_set_id;                                     // ue(v)
	unsigned int    seq_params_set_id;                                       // ue(v)

	unsigned char   dependent_slice_segments_enable_flag;   // u(1)
	unsigned char   output_flag_present_flag;                             // u(1)
	unsigned int    num_extra_slice_header_bits;                       // u(3)
};

struct h265_slice_hdr_data {
	unsigned char   first_slice_segment_in_pic;
	bool no_output_of_prior_pics_flag;
	unsigned int    pps_id;
	unsigned char   dependent_slice_segment_flag;
	unsigned int    slice_segment_address;
	bool discard_able_flag;
	bool cross_layer_bla_flag;
	unsigned int    slice_type;
};

struct h265_nal_unit_header {
	bool            forbidden_zero_bit;
	unsigned char   nal_unit_type;
	unsigned char   nuh_layer_id;
	unsigned char   nuh_temporal_id_plus1;
};

struct rbsp_bitstream {
	union {
		unsigned char *p_vstart;
		unsigned long long p_vstart_padding;
	};
	union {
		unsigned char *p_vend;
		unsigned long long p_vend_padding;
	};
	union {
		unsigned char *p_rstart;
		unsigned long long p_rstart_padding;
	};
	union {
		unsigned char *p_rend;
		unsigned long long p_rend_padding;
	};

	unsigned int bits_read;
	unsigned int bits_write;

	unsigned int remove_03;
	signed int cont0;

	bool disable_emulation_prevention;


	unsigned char cache[CACHE_SIZE];
	unsigned int stored_cache_size;
};
void init_h264_seq_header(void);
void init_h265_seq_header(void);
void init_h265_sei_pic_struct(void);
#define fgIsRefPic(nal_ref_idc) ((nal_ref_idc > 0))

// init rbsp's location
signed int vdec_rbsp_parser_init(
	struct rbsp_bitstream *p_rbsp_bitstream,
	unsigned char *p_vstart, // read nal start
	unsigned char *p_vend,   // read nal end (cannot read)
	unsigned char *p_rstart, // read start pointer move in byte
	unsigned char *p_rend,   // read end (cannot read)
	unsigned int codec,
	bool disable_emulation_prevention); // check emulation_prevention 03 or not


// load data into cyclic buffer p_rbsp_bitstream->cache
// keep cache has two bytes that are not used
unsigned int vdec_rbsp_parser_load(
	 struct rbsp_bitstream *p_rbsp_bitstream);

// parse mpeg i/p/b pic ext header
signed int vdec_com_mpeg_sw_pic_ext(
	struct rbsp_bitstream *rbsp_bitstream_inst,
	struct MPEG_ES_UNIT *curCachedUnit);

// parse h264 i/p/b slice type
signed int vdec_com_h264_sw_parsenal(
	struct rbsp_bitstream *rbsp_bitstream_inst,
	struct AVC_ES_UNIT *curCachedUnit);

// parse h264 i/p/b slice type
unsigned int vdec_sw_psr_h264_slice_type(
	unsigned char nal_unit_type,
	unsigned char nal_ref_idc,
	struct rbsp_bitstream *rbsp_bitstream_inst,
	struct AVC_ES_UNIT *curCachedUnit);

// read bits from es
unsigned int vpas_readbits(
	struct rbsp_bitstream *p_rbsp_bitstream,
	unsigned int bits);

// do ue(v)
unsigned int vpas_uecodenum(
	struct rbsp_bitstream *p_rbsp_bitstream);

// do se(v)
signed int vpas_secodenum(
	struct rbsp_bitstream *rbsp_bitstream_inst);

signed int vpas_rawnextbits(
	 struct rbsp_bitstream *p_rbsp_bitstream,
	 unsigned int bits,
	 unsigned int *p_value,
	 unsigned int *p_bits_read,
	 signed int *p_cont0);

// parse h265 pps & i/p/b slice type
signed int vdec_com_h265_sw_parsenal(
	struct rbsp_bitstream *rbsp_bitstream_inst,
	struct HEVC_ES_UNIT *curCachedUnit);
#endif
