hevc_nal.c 54.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*****************************************************************************
 * Copyright © 2010-2014 VideoLAN
 *
 * Authors: Thomas Guillem <thomas.guillem@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/
20 21 22
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
23 24

#include "hevc_nal.h"
25
#include "hxxx_nal.h"
26
#include "hxxx_ep3b.h"
27
#include "iso_color_tables.h"
28

29
#include <vlc_common.h>
30 31
#include <vlc_bits.h>

32 33
#include <limits.h>

34 35
//#define HEVC_POC_DEBUG

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
typedef uint8_t  nal_u1_t;
typedef uint8_t  nal_u2_t;
typedef uint8_t  nal_u3_t;
typedef uint8_t  nal_u4_t;
typedef uint8_t  nal_u5_t;
typedef uint8_t  nal_u6_t;
typedef uint8_t  nal_u7_t;
typedef uint8_t  nal_u8_t;
typedef int32_t  nal_se_t;
typedef uint32_t nal_ue_t;

typedef struct
{
    nal_u2_t profile_space;
    nal_u1_t tier_flag;
    nal_u5_t profile_idc;
    uint32_t profile_compatibility_flag; /* nal_u1_t * 32 */
    nal_u1_t progressive_source_flag;
    nal_u1_t interlaced_source_flag;
    nal_u1_t non_packed_constraint_flag;
    nal_u1_t frame_only_constraint_flag;
    struct
    {
        nal_u1_t max_12bit_constraint_flag;
        nal_u1_t max_10bit_constraint_flag;
        nal_u1_t max_8bit_constraint_flag;
        nal_u1_t max_422chroma_constraint_flag;
        nal_u1_t max_420chroma_constraint_flag;
        nal_u1_t max_monochrome_constraint_flag;
        nal_u1_t intra_constraint_flag;
        nal_u1_t one_picture_only_constraint_flag;
        nal_u1_t lower_bit_rate_constraint_flag;
    } idc4to7;
    struct
    {
        nal_u1_t inbld_flag;
    } idc1to5;
} hevc_inner_profile_tier_level_t;

#define HEVC_MAX_SUBLAYERS 8
typedef struct
{
    hevc_inner_profile_tier_level_t general;
    nal_u8_t general_level_idc;
    uint8_t  sublayer_profile_present_flag;  /* nal_u1_t * 8 */
    uint8_t  sublayer_level_present_flag;    /* nal_u1_t * 8 */
    hevc_inner_profile_tier_level_t sub_layer[HEVC_MAX_SUBLAYERS];
    nal_u8_t sub_layer_level_idc[HEVC_MAX_SUBLAYERS];
} hevc_profile_tier_level_t;

86 87 88 89 90 91 92 93
#define HEVC_MAX_SHORT_TERM_REF_PIC_SET 65
#define HEVC_MAX_LONG_TERM_REF_PIC_SET 33

typedef struct
{
    unsigned num_delta_pocs;
} hevc_short_term_ref_pic_set_t;

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
typedef struct
{
    nal_u1_t aspect_ratio_info_present_flag;
    struct
    {
        nal_u8_t aspect_ratio_idc;
        uint16_t sar_width;
        uint16_t sar_height;
    } ar;
    nal_u1_t overscan_info_present_flag;
    nal_u1_t overscan_appropriate_flag;

    nal_u1_t video_signal_type_present_flag;
    struct
    {
        nal_u3_t video_format;
        nal_u1_t video_full_range_flag;
        nal_u1_t colour_description_present_flag;
        struct
        {
            nal_u8_t colour_primaries;
            nal_u8_t transfer_characteristics;
            nal_u8_t matrix_coeffs;
        } colour;
    } vs;

    nal_u1_t chroma_loc_info_present_flag;
    struct
    {
        nal_ue_t sample_loc_type_top_field;
        nal_ue_t sample_loc_type_bottom_field;
    } chroma;

    nal_u1_t neutral_chroma_indication_flag;
    nal_u1_t field_seq_flag;
    nal_u1_t frame_field_info_present_flag;

    nal_u1_t default_display_window_flag;
    struct
    {
        nal_ue_t win_left_offset;
        nal_ue_t win_right_offset;
        nal_ue_t win_top_offset;
        nal_ue_t win_bottom_offset;
    } def_disp;

    nal_u1_t vui_timing_info_present_flag;
    struct
    {
        uint32_t vui_num_units_in_tick;
        uint32_t vui_time_scale;
        /* incomplete */
    } timing;

    /* incomplete */
} hevc_vui_parameters_t;

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
struct hevc_video_parameter_set_t
{
    nal_u4_t vps_video_parameter_set_id;
    nal_u1_t vps_base_layer_internal_flag;
    nal_u1_t vps_base_layer_available_flag;
    nal_u6_t vps_max_layers_minus1;
    nal_u3_t vps_max_sub_layers_minus1;
    nal_u1_t vps_temporal_id_nesting_flag;

    hevc_profile_tier_level_t profile_tier_level;

    nal_u1_t vps_sub_layer_ordering_info_present_flag;
    struct
    {
        nal_ue_t dec_pic_buffering_minus1;
        nal_ue_t num_reorder_pics;
        nal_ue_t max_latency_increase_plus1;
    } vps_max[1 + HEVC_MAX_SUBLAYERS];

    nal_u6_t vps_max_layer_id;
    nal_ue_t vps_num_layer_set_minus1;
    // layer_id_included_flag; read but discarded

    nal_u1_t vps_timing_info_present_flag;
    uint32_t vps_num_units_in_tick;
    uint32_t vps_time_scale;

    /* incomplete */
};

181
struct hevc_sequence_parameter_set_t
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
{
    nal_u4_t sps_video_parameter_set_id;
    nal_u3_t sps_max_sub_layers_minus1;
    nal_u1_t sps_temporal_id_nesting_flag;

    hevc_profile_tier_level_t profile_tier_level;

    nal_ue_t sps_seq_parameter_set_id;
    nal_ue_t chroma_format_idc;
    nal_u1_t separate_colour_plane_flag;

    nal_ue_t pic_width_in_luma_samples;
    nal_ue_t pic_height_in_luma_samples;

    nal_u1_t conformance_window_flag;
    struct
    {
    nal_ue_t left_offset;
    nal_ue_t right_offset;
    nal_ue_t top_offset;
    nal_ue_t bottom_offset;
    } conf_win;

    nal_ue_t bit_depth_luma_minus8;
    nal_ue_t bit_depth_chroma_minus8;
    nal_ue_t log2_max_pic_order_cnt_lsb_minus4;

    nal_u1_t sps_sub_layer_ordering_info_present_flag;
    struct
    {
    nal_ue_t dec_pic_buffering_minus1;
    nal_ue_t num_reorder_pics;
    nal_ue_t latency_increase_plus1;
    } sps_max[1 + HEVC_MAX_SUBLAYERS];

    nal_ue_t log2_min_luma_coding_block_size_minus3;
    nal_ue_t log2_diff_max_min_luma_coding_block_size;
    nal_ue_t log2_min_luma_transform_block_size_minus2;
    nal_ue_t log2_diff_max_min_luma_transform_block_size;

    /* incomplete */
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    nal_ue_t max_transform_hierarchy_depth_inter;
    nal_ue_t max_transform_hierarchy_depth_intra;
    nal_u1_t scaling_list_enabled;
    nal_u1_t sps_scaling_list_data_present_flag;
    // scaling_list_data; read but discarded

    nal_u1_t amp_enabled_flag;
    nal_u1_t sample_adaptive_offset_enabled_flag;

    nal_u1_t pcm_enabled_flag;
    nal_u4_t pcm_sample_bit_depth_luma_minus1;
    nal_u4_t pcm_sample_bit_depth_chroma_minus1;
    nal_ue_t log2_min_pcm_luma_coding_block_size_minus3;
    nal_ue_t log2_diff_max_min_pcm_luma_coding_block_size;
    nal_u1_t pcm_loop_filter_disabled_flag;

    nal_ue_t num_short_term_ref_pic_sets;
    // st_ref_pic_set

    nal_u1_t long_term_ref_pics_present_flag;
    nal_ue_t num_long_term_ref_pics_sps;
    //

    nal_u1_t sps_temporal_mvp_enabled_flag;
    nal_u1_t strong_intra_smoothing_enabled_flag;

    nal_u1_t vui_parameters_present_flag;
    hevc_vui_parameters_t vui;
    /* incomplete */
252
};
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
struct hevc_picture_parameter_set_t
{
    nal_ue_t pps_pic_parameter_set_id;
    nal_ue_t pps_seq_parameter_set_id;
    nal_u1_t dependent_slice_segments_enabled_flag;
    nal_u1_t output_flag_present_flag;
    nal_u3_t num_extra_slice_header_bits;
    nal_u1_t sign_data_hiding_enabled_flag;
    nal_u1_t cabac_init_present_flag;
    nal_ue_t num_ref_idx_l0_default_active_minus1;
    nal_ue_t num_ref_idx_l1_default_active_minus1;
    nal_se_t init_qp_minus26;
    nal_u1_t constrained_intra_pred_flag;
    nal_u1_t transform_skip_enabled_flag;

    nal_u1_t cu_qp_delta_enabled_flag;
    nal_ue_t diff_cu_qp_delta_depth;

    nal_se_t pps_cb_qp_offset;
    nal_se_t pps_cr_qp_offset;
    nal_u1_t pic_slice_level_chroma_qp_offsets_present_flag;
    nal_u1_t weighted_pred_flag;
    nal_u1_t weighted_bipred_flag;
    nal_u1_t transquant_bypass_enable_flag;

    nal_u1_t tiles_enabled_flag;
    nal_u1_t entropy_coding_sync_enabled_flag;
    nal_ue_t num_tile_columns_minus1;
    nal_ue_t num_tile_rows_minus1;
    nal_u1_t uniform_spacing_flag;
    // nal_ue_t *p_column_width_minus1; read but discarded
    // nal_ue_t *p_row_height_minus1; read but discarded
    nal_u1_t loop_filter_across_tiles_enabled_flag;

    nal_u1_t pps_loop_filter_across_slices_enabled_flag;

    nal_u1_t deblocking_filter_control_present_flag;
    nal_u1_t deblocking_filter_override_enabled_flag;
    nal_u1_t pps_deblocking_filter_disabled_flag;
    nal_se_t pps_beta_offset_div2;
    nal_se_t pps_tc_offset_div2;

    nal_u1_t scaling_list_data_present_flag;
    // scaling_list_data; read but discarded

    nal_u1_t lists_modification_present_flag;
    nal_ue_t log2_parallel_merge_level_minus2;
    nal_u1_t slice_header_extension_present_flag;

    nal_u1_t pps_extension_present_flag;
    nal_u1_t pps_range_extension_flag;
    nal_u1_t pps_multilayer_extension_flag;
    nal_u1_t pps_3d_extension_flag;
    nal_u5_t pps_extension_5bits;
    /* incomplete */

};

312 313
struct hevc_slice_segment_header_t
{
314 315
    nal_u6_t nal_type;
    nal_u6_t nuh_layer_id;
316
    nal_u3_t temporal_id_plus1;
317 318 319 320 321 322 323
    nal_u1_t first_slice_segment_in_pic_flag;
    nal_u1_t no_output_of_prior_pics_flag;
    nal_ue_t slice_pic_parameter_set_id;
    nal_u1_t dependent_slice_segment_flag;
    // slice_segment_address; read but discarded
    nal_ue_t slice_type;
    nal_u1_t pic_output_flag;
324 325

    uint32_t pic_order_cnt_lsb;
326 327 328 329
    /* incomplete */

};

330 331
/* Computes size and does check the whole struct integrity */
static size_t get_hvcC_to_AnnexB_NAL_size( const uint8_t *p_buf, size_t i_buf )
332
{
333
    size_t i_total = 0;
334

335 336
    if( i_buf < HEVC_MIN_HVCC_SIZE )
        return 0;
337

338 339 340 341 342 343 344 345
    const uint8_t i_nal_length_size = (p_buf[21] & 0x03) + 1;
    if(i_nal_length_size == 3)
        return 0;

    const uint8_t i_num_array = p_buf[22];
    p_buf += 23; i_buf -= 23;

    for( uint8_t i = 0; i < i_num_array; i++ )
346
    {
347 348 349 350 351 352 353 354 355 356 357 358
        if(i_buf < 3)
            return 0;

        const uint16_t i_num_nalu = p_buf[1] << 8 | p_buf[2];
        p_buf += 3; i_buf -= 3;

        for( uint16_t j = 0; j < i_num_nalu; j++ )
        {
            if(i_buf < 2)
                return 0;

            const uint16_t i_nalu_length = p_buf[0] << 8 | p_buf[1];
359
            if(i_buf < (size_t)i_nalu_length + 2)
360 361 362 363 364 365
                return 0;

            i_total += i_nalu_length + i_nal_length_size;
            p_buf += i_nalu_length + 2;
            i_buf -= i_nalu_length + 2;
        }
366 367
    }

368 369 370 371 372 373 374 375 376 377 378
    return i_total;
}

uint8_t * hevc_hvcC_to_AnnexB_NAL( const uint8_t *p_buf, size_t i_buf,
                                   size_t *pi_result, uint8_t *pi_nal_length_size )
{
    *pi_result = get_hvcC_to_AnnexB_NAL_size( p_buf, i_buf ); /* Does all checks */
    if( *pi_result == 0 )
        return NULL;

    if( pi_nal_length_size )
379
        *pi_nal_length_size = hevc_getNALLengthSize( p_buf );
380

381 382 383
    uint8_t *p_ret;
    uint8_t *p_out_buf = p_ret = malloc( *pi_result );
    if( !p_out_buf )
384 385
    {
        *pi_result = 0;
386
        return NULL;
387
    }
388

389 390
    const uint8_t i_num_array = p_buf[22];
    p_buf += 23;
391

392
    for( uint8_t i = 0; i < i_num_array; i++ )
393
    {
394 395
        const uint16_t i_num_nalu = p_buf[1] << 8 | p_buf[2];
        p_buf += 3;
396

397
        for( uint16_t j = 0; j < i_num_nalu; j++ )
398
        {
399
            const uint16_t i_nalu_length = p_buf[0] << 8 | p_buf[1];
400

401 402
            memcpy( p_out_buf, annexb_startcode4, 4 );
            memcpy( &p_out_buf[4], &p_buf[2], i_nalu_length );
403

404 405
            p_out_buf += 4 + i_nalu_length;
            p_buf += 2 + i_nalu_length;
406 407 408
        }
    }

409
    return p_ret;
410
}
411

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
static bool hevc_parse_scaling_list_rbsp( bs_t *p_bs )
{
    if( bs_remain( p_bs ) < 16 )
        return false;

    for( int i=0; i<4; i++ )
    {
        for( int j=0; j<6; j += (i == 3) ? 3 : 1 )
        {
            if( bs_read1( p_bs ) == 0 )
                bs_read_ue( p_bs );
            else
            {
                unsigned nextCoef = 8;
                unsigned coefNum = __MIN( 64, (1 << (4 + (i << 1))));
                if( i > 1 )
                {
                    nextCoef = bs_read_se( p_bs ) + 8;
                }
                for( unsigned k=0; k<coefNum; k++ )
                {
                    nextCoef = ( nextCoef + bs_read_se( p_bs ) + 256 ) % 256;
                }
            }
        }
    }

    return true;
}

442 443
static bool hevc_parse_vui_parameters_rbsp( bs_t *p_bs, hevc_vui_parameters_t *p_vui,
                                            bool b_broken )
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
{
    if( bs_remain( p_bs ) < 10 )
        return false;

    p_vui->aspect_ratio_info_present_flag = bs_read1( p_bs );
    if( p_vui->aspect_ratio_info_present_flag )
    {
        p_vui->ar.aspect_ratio_idc = bs_read( p_bs, 8 );
        if( p_vui->ar.aspect_ratio_idc == 0xFF ) //HEVC_SAR__IDC_EXTENDED_SAR )
        {
            p_vui->ar.sar_width = bs_read( p_bs, 16 );
            p_vui->ar.sar_height = bs_read( p_bs, 16 );
        }
    }

    p_vui->overscan_info_present_flag = bs_read1( p_bs );
    if( p_vui->overscan_info_present_flag )
        p_vui->overscan_appropriate_flag = bs_read1( p_bs );

    p_vui->video_signal_type_present_flag = bs_read1( p_bs );
    if( p_vui->video_signal_type_present_flag )
    {
        p_vui->vs.video_format = bs_read( p_bs, 3 );
        p_vui->vs.video_full_range_flag = bs_read1( p_bs );
        p_vui->vs.colour_description_present_flag = bs_read1( p_bs );
        if( p_vui->vs.colour_description_present_flag )
        {
            p_vui->vs.colour.colour_primaries = bs_read( p_bs, 8 );
            p_vui->vs.colour.transfer_characteristics = bs_read( p_bs, 8 );
            p_vui->vs.colour.matrix_coeffs = bs_read( p_bs, 8 );
        }
475 476
        else
        {
477 478 479
            p_vui->vs.colour.colour_primaries = ISO_23001_8_CP_UNSPECIFIED;
            p_vui->vs.colour.transfer_characteristics = ISO_23001_8_TC_UNSPECIFIED;
            p_vui->vs.colour.matrix_coeffs = ISO_23001_8_MC_UNSPECIFIED;
480
        }
481 482 483 484 485 486 487 488 489 490 491 492 493
    }

    p_vui->chroma_loc_info_present_flag = bs_read1( p_bs );
    if( p_vui->chroma_loc_info_present_flag )
    {
        p_vui->chroma.sample_loc_type_top_field = bs_read_ue( p_bs );
        p_vui->chroma.sample_loc_type_bottom_field = bs_read_ue( p_bs );
    }

    p_vui->neutral_chroma_indication_flag = bs_read1( p_bs );
    p_vui->field_seq_flag = bs_read1( p_bs );
    p_vui->frame_field_info_present_flag = bs_read1( p_bs );

494
    p_vui->default_display_window_flag = !b_broken && bs_read1( p_bs );
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
    if( p_vui->default_display_window_flag )
    {
        p_vui->def_disp.win_left_offset = bs_read_ue( p_bs );
        p_vui->def_disp.win_right_offset = bs_read_ue( p_bs );
        p_vui->def_disp.win_top_offset = bs_read_ue( p_bs );
        p_vui->def_disp.win_bottom_offset = bs_read_ue( p_bs );
    }

    p_vui->vui_timing_info_present_flag = bs_read1( p_bs );
    if( p_vui->vui_timing_info_present_flag )
    {
        p_vui->timing.vui_num_units_in_tick =  bs_read( p_bs, 32 );
        p_vui->timing.vui_time_scale =  bs_read( p_bs, 32 );

        if( bs_remain( p_bs ) < 3 )
            return false;
    }
    /* incomplete */

    if( bs_remain( p_bs ) < 1 ) /* late fail */
        return false;

    return true;
}

520 521 522
/* Shortcut for retrieving vps/sps/pps id */
bool hevc_get_xps_id(const uint8_t *p_buf, size_t i_buf, uint8_t *pi_id)
{
523
    if(i_buf < 3)
524 525
        return false;
    /* No need to lookup convert from emulation for that data */
526
    uint8_t i_nal_type = hevc_getNALType(p_buf);
527 528 529
    bs_t bs;
    bs_init(&bs, &p_buf[2], i_buf - 2);
    if(i_nal_type == HEVC_NAL_PPS)
530
    {
531
        *pi_id = bs_read_ue( &bs );
532 533 534
        if(*pi_id > HEVC_PPS_ID_MAX)
            return false;
    }
535
    else
536
    {
537
        *pi_id = bs_read( &bs, 4 );
538 539 540 541 542 543 544 545
        if(i_nal_type == HEVC_NAL_SPS)
        {
            if(*pi_id > HEVC_SPS_ID_MAX)
                return false;
        }
        else if(*pi_id > HEVC_VPS_ID_MAX)
            return false;
    }
546 547 548
    return true;
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
static bool hevc_parse_inner_profile_tier_level_rbsp( bs_t *p_bs,
                                                      hevc_inner_profile_tier_level_t *p_in )
{
    if( bs_remain( p_bs ) < 88 )
        return false;

    p_in->profile_space = bs_read( p_bs, 2 );
    p_in->tier_flag = bs_read1( p_bs );
    p_in->profile_idc = bs_read( p_bs, 5 );
    p_in->profile_compatibility_flag = bs_read( p_bs, 32 );
    p_in->progressive_source_flag = bs_read1( p_bs );
    p_in->interlaced_source_flag = bs_read1( p_bs );
    p_in->non_packed_constraint_flag = bs_read1( p_bs );
    p_in->frame_only_constraint_flag = bs_read1( p_bs );

    if( ( p_in->profile_idc >= 4 && p_in->profile_idc <= 7 ) ||
        ( p_in->profile_compatibility_flag & 0x0F000000 ) )
    {
        p_in->idc4to7.max_12bit_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.max_10bit_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.max_8bit_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.max_422chroma_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.max_420chroma_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.max_monochrome_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.intra_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.one_picture_only_constraint_flag = bs_read1( p_bs );
        p_in->idc4to7.lower_bit_rate_constraint_flag = bs_read1( p_bs );
        (void) bs_read( p_bs, 2 );
    }
    else
    {
        (void) bs_read( p_bs, 11 );
    }
    (void) bs_read( p_bs, 32 );

    if( ( p_in->profile_idc >= 1 && p_in->profile_idc <= 5 ) ||
        ( p_in->profile_compatibility_flag & 0x7C000000 ) )
        p_in->idc1to5.inbld_flag = bs_read1( p_bs );
    else
        (void) bs_read1( p_bs );

    return true;
}

static bool hevc_parse_profile_tier_level_rbsp( bs_t *p_bs, bool profile_present,
                                                uint8_t max_num_sub_layers_minus1,
                                                hevc_profile_tier_level_t *p_ptl )
{
    if( profile_present && !hevc_parse_inner_profile_tier_level_rbsp( p_bs, &p_ptl->general ) )
        return false;

    if( bs_remain( p_bs ) < 8)
        return false;

    p_ptl->general_level_idc = bs_read( p_bs, 8 );

    if( max_num_sub_layers_minus1 > 0 )
    {
        if( bs_remain( p_bs ) < 16 )
            return false;

        for( uint8_t i=0; i< 8; i++ )
        {
            if( i < max_num_sub_layers_minus1 )
            {
                if( bs_read1( p_bs ) )
                    p_ptl->sublayer_profile_present_flag |= (0x80 >> i);
                if( bs_read1( p_bs ) )
                    p_ptl->sublayer_level_present_flag |= (0x80 >> i);
            }
            else
                bs_read( p_bs, 2 );
        }

        for( uint8_t i=0; i < max_num_sub_layers_minus1; i++ )
        {
            if( ( p_ptl->sublayer_profile_present_flag & (0x80 >> i) ) &&
                ! hevc_parse_inner_profile_tier_level_rbsp( p_bs, &p_ptl->sub_layer[i] ) )
                return false;

            if( p_ptl->sublayer_profile_present_flag & (0x80 >> i) )
            {
                if( bs_remain( p_bs ) < 8 )
                    return false;
                p_ptl->sub_layer_level_idc[i] = bs_read( p_bs, 8 );
            }
        }
    }

    return true;
}
640

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
static bool hevc_parse_video_parameter_set_rbsp( bs_t *p_bs,
                                                 hevc_video_parameter_set_t *p_vps )
{
    if( bs_remain( p_bs ) < 134 )
        return false;

    p_vps->vps_video_parameter_set_id = bs_read( p_bs, 4 );
    p_vps->vps_base_layer_internal_flag = bs_read1( p_bs );
    p_vps->vps_base_layer_available_flag = bs_read1( p_bs );
    p_vps->vps_max_layers_minus1 = bs_read( p_bs, 6 );
    p_vps->vps_max_sub_layers_minus1 = bs_read( p_bs, 3 );
    p_vps->vps_temporal_id_nesting_flag = bs_read1( p_bs );
    bs_skip( p_bs, 16 );

    if( !hevc_parse_profile_tier_level_rbsp( p_bs, true, p_vps->vps_max_sub_layers_minus1,
                                            &p_vps->profile_tier_level ) )
        return false;

    p_vps->vps_sub_layer_ordering_info_present_flag = bs_read1( p_bs );
    for( unsigned i= (p_vps->vps_sub_layer_ordering_info_present_flag ?
                      0 : p_vps->vps_max_sub_layers_minus1);
         i<= p_vps->vps_max_sub_layers_minus1; i++ )
    {
664 665 666
        p_vps->vps_max[i].dec_pic_buffering_minus1 = bs_read_ue( p_bs );
        p_vps->vps_max[i].num_reorder_pics = bs_read_ue( p_bs );
        p_vps->vps_max[i].max_latency_increase_plus1 = bs_read_ue( p_bs );
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    }
    if( bs_remain( p_bs ) < 10 )
        return false;

    p_vps->vps_max_layer_id = bs_read( p_bs, 6 );
    p_vps->vps_num_layer_set_minus1 = bs_read_ue( p_bs );
    // layer_id_included_flag; read but discarded
    bs_skip( p_bs, p_vps->vps_num_layer_set_minus1 * (p_vps->vps_max_layer_id + 1) );
    if( bs_remain( p_bs ) < 2 )
        return false;

    p_vps->vps_timing_info_present_flag = bs_read1( p_bs );
    if( p_vps->vps_timing_info_present_flag )
    {
        p_vps->vps_num_units_in_tick = bs_read( p_bs, 32 );
        p_vps->vps_time_scale = bs_read( p_bs, 32 );
    }
    /* parsing incomplete */

    if( bs_remain( p_bs ) < 1 )
        return false;

    return true;
}

void hevc_rbsp_release_vps( hevc_video_parameter_set_t *p_vps )
{
    free( p_vps );
}

697 698 699 700 701 702 703
#define IMPL_hevc_generic_decode( name, hevctype, decode, release ) \
    hevctype * name( const uint8_t *p_buf, size_t i_buf, bool b_escaped ) \
    { \
        hevctype *p_hevctype = calloc(1, sizeof(hevctype)); \
        if(likely(p_hevctype)) \
        { \
            bs_t bs; \
704
            struct hxxx_bsfw_ep3b_ctx_s bsctx; \
705 706
            if( b_escaped ) \
            { \
707 708
                hxxx_bsfw_ep3b_ctx_init( &bsctx ); \
                bs_init_custom( &bs, p_buf, i_buf, &hxxx_bsfw_ep3b_callbacks, &bsctx );\
709
            } \
710
            else bs_init( &bs, p_buf, i_buf ); \
711 712 713 714
            bs_skip( &bs, 7 ); /* nal_unit_header */ \
            uint8_t i_nuh_layer_id = bs_read( &bs, 6 ); \
            bs_skip( &bs, 3 ); /* !nal_unit_header */ \
            if( i_nuh_layer_id > 62 || !decode( &bs, p_hevctype ) ) \
715 716 717 718 719 720
            { \
                release( p_hevctype ); \
                p_hevctype = NULL; \
            } \
        } \
        return p_hevctype; \
721
    }
722 723 724

IMPL_hevc_generic_decode( hevc_decode_vps, hevc_video_parameter_set_t,
                          hevc_parse_video_parameter_set_rbsp, hevc_rbsp_release_vps )
725

726
static bool hevc_parse_st_ref_pic_set( bs_t *p_bs, unsigned stRpsIdx,
727 728 729
                                       unsigned num_short_term_ref_pic_sets,
                                       hevc_short_term_ref_pic_set_t *p_sets )
{
730
    if( stRpsIdx && bs_read1( p_bs ) ) /* Interref pic set prediction flag */
731 732
    {
        nal_ue_t delta_idx_minus_1 = 0;
733
        if( stRpsIdx == num_short_term_ref_pic_sets )
734 735
        {
            delta_idx_minus_1 = bs_read_ue( p_bs );
736
            if( delta_idx_minus_1 >= stRpsIdx )
737 738
                return false;
        }
739
        if(delta_idx_minus_1 == stRpsIdx)
740 741 742 743
            return false;

        nal_u1_t delta_rps_sign = bs_read1( p_bs );
        nal_ue_t abs_delta_rps_minus1 = bs_read_ue( p_bs );
744
        unsigned RefRpsIdx = stRpsIdx - delta_idx_minus_1 - 1;
745 746 747 748
        int deltaRps = ( 1 - ( delta_rps_sign << 1 ) ) * ( abs_delta_rps_minus1 + 1 );
        VLC_UNUSED(deltaRps);

        unsigned numDeltaPocs = p_sets[RefRpsIdx].num_delta_pocs;
749
        p_sets[stRpsIdx].num_delta_pocs = 0;
750 751
        for( unsigned j=0; j<= numDeltaPocs; j++ )
        {
752 753 754 755 756 757 758
            if( ! bs_read1( p_bs ) ) /* used_by_curr_pic_flag */
            {
                if( bs_read1( p_bs ) ) /* use_delta_flag */
                    p_sets[stRpsIdx].num_delta_pocs++;
            }
            else
                p_sets[stRpsIdx].num_delta_pocs++;
759 760 761 762 763 764
        }
    }
    else
    {
        nal_ue_t num_negative_pics = bs_read_ue( p_bs );
        nal_ue_t num_positive_pics = bs_read_ue( p_bs );
765
        if( bs_remain( p_bs ) < (num_negative_pics + num_positive_pics) * 2 )
766
            return false;
767 768 769 770 771 772 773 774 775 776
        for(unsigned int i=0; i<num_negative_pics; i++)
        {
            (void) bs_read_ue( p_bs ); /* delta_poc_s0_minus1 */
            (void) bs_read1( p_bs ); /* used_by_current_pic_s0_flag */
        }
        for(unsigned int i=0; i<num_positive_pics; i++)
        {
            (void) bs_read_ue( p_bs ); /* delta_poc_s1_minus1 */
            (void) bs_read1( p_bs ); /* used_by_current_pic_s1_flag */
        }
777
        p_sets[stRpsIdx].num_delta_pocs = num_positive_pics + num_negative_pics;
778 779 780 781 782
    }

    return true;
}

783 784 785 786 787 788 789 790 791 792 793 794 795 796
static bool hevc_parse_sequence_parameter_set_rbsp( bs_t *p_bs,
                                                    hevc_sequence_parameter_set_t *p_sps )
{
    p_sps->sps_video_parameter_set_id = bs_read( p_bs, 4 );
    p_sps->sps_max_sub_layers_minus1 = bs_read( p_bs, 3 );
    p_sps->sps_temporal_id_nesting_flag = bs_read1( p_bs );
    if( !hevc_parse_profile_tier_level_rbsp( p_bs, true, p_sps->sps_max_sub_layers_minus1,
                                            &p_sps->profile_tier_level ) )
        return false;

    if( bs_remain( p_bs ) < 1 )
        return false;

    p_sps->sps_seq_parameter_set_id = bs_read_ue( p_bs );
797
    if( p_sps->sps_seq_parameter_set_id > HEVC_SPS_ID_MAX )
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
        return false;

    p_sps->chroma_format_idc = bs_read_ue( p_bs );
    if( p_sps->chroma_format_idc == 3 )
        p_sps->separate_colour_plane_flag = bs_read1( p_bs );
    p_sps->pic_width_in_luma_samples = bs_read_ue( p_bs );
    p_sps->pic_height_in_luma_samples = bs_read_ue( p_bs );
    if( !p_sps->pic_width_in_luma_samples || !p_sps->pic_height_in_luma_samples )
        return false;

    p_sps->conformance_window_flag = bs_read1( p_bs );
    if( p_sps->conformance_window_flag )
    {
        p_sps->conf_win.left_offset = bs_read_ue( p_bs );
        p_sps->conf_win.right_offset = bs_read_ue( p_bs );
        p_sps->conf_win.top_offset = bs_read_ue( p_bs );
        p_sps->conf_win.bottom_offset = bs_read_ue( p_bs );
    }

    p_sps->bit_depth_luma_minus8 = bs_read_ue( p_bs );
    p_sps->bit_depth_chroma_minus8 = bs_read_ue( p_bs );
    p_sps->log2_max_pic_order_cnt_lsb_minus4 = bs_read_ue( p_bs );

    p_sps->sps_sub_layer_ordering_info_present_flag = bs_read1( p_bs );
    for( uint8_t i=(p_sps->sps_sub_layer_ordering_info_present_flag ? 0 : p_sps->sps_max_sub_layers_minus1);
         i <= p_sps->sps_max_sub_layers_minus1; i++ )
    {
        p_sps->sps_max[i].dec_pic_buffering_minus1 = bs_read_ue( p_bs );
        p_sps->sps_max[i].num_reorder_pics = bs_read_ue( p_bs );
        p_sps->sps_max[i].latency_increase_plus1 = bs_read_ue( p_bs );
    }

    if( bs_remain( p_bs ) < 4 )
        return false;

    p_sps->log2_min_luma_coding_block_size_minus3 = bs_read_ue( p_bs );
    p_sps->log2_diff_max_min_luma_coding_block_size = bs_read_ue( p_bs );
    p_sps->log2_min_luma_transform_block_size_minus2 = bs_read_ue( p_bs );
    if( bs_remain( p_bs ) < 1 ) /* last late fail check */
        return false;
    p_sps->log2_diff_max_min_luma_transform_block_size = bs_read_ue( p_bs );

    /* parsing incomplete */
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901

    p_sps->max_transform_hierarchy_depth_inter = bs_read_ue( p_bs );
    p_sps->max_transform_hierarchy_depth_intra = bs_read_ue( p_bs );
    p_sps->scaling_list_enabled = bs_read1( p_bs );
    if( p_sps->scaling_list_enabled )
    {
        p_sps->sps_scaling_list_data_present_flag = bs_read1( p_bs );
        if( p_sps->sps_scaling_list_data_present_flag &&
            ! hevc_parse_scaling_list_rbsp( p_bs ) )
        {
            return false;
        }
    }

    p_sps->amp_enabled_flag = bs_read1( p_bs );
    p_sps->sample_adaptive_offset_enabled_flag = bs_read1( p_bs );

    p_sps->pcm_enabled_flag = bs_read1( p_bs );
    if( p_sps->pcm_enabled_flag )
    {
        p_sps->pcm_sample_bit_depth_luma_minus1 = bs_read( p_bs, 4 );
        p_sps->pcm_sample_bit_depth_chroma_minus1 = bs_read( p_bs, 4 );
        p_sps->log2_min_pcm_luma_coding_block_size_minus3 = bs_read_ue( p_bs );
        p_sps->log2_diff_max_min_pcm_luma_coding_block_size = bs_read_ue( p_bs );
        p_sps->pcm_loop_filter_disabled_flag = bs_read1( p_bs );
    }

    p_sps->num_short_term_ref_pic_sets = bs_read_ue( p_bs );
    if( p_sps->num_short_term_ref_pic_sets > HEVC_MAX_SHORT_TERM_REF_PIC_SET )
        return false;

    hevc_short_term_ref_pic_set_t sets[HEVC_MAX_SHORT_TERM_REF_PIC_SET];
    memset(&sets, 0, sizeof(hevc_short_term_ref_pic_set_t) * HEVC_MAX_SHORT_TERM_REF_PIC_SET);
    for( unsigned int i=0; i<p_sps->num_short_term_ref_pic_sets; i++ )
    {
        if( !hevc_parse_st_ref_pic_set( p_bs, i, p_sps->num_short_term_ref_pic_sets, sets ) )
            return false;
    }

    p_sps->long_term_ref_pics_present_flag = bs_read1( p_bs );
    if( p_sps->long_term_ref_pics_present_flag )
    {
        p_sps->num_long_term_ref_pics_sps = bs_read_ue( p_bs );
        if( p_sps->num_long_term_ref_pics_sps > HEVC_MAX_LONG_TERM_REF_PIC_SET )
            return false;
        for( unsigned int i=0; i< p_sps->num_long_term_ref_pics_sps; i++ )
        {
             /* lt_ref_pic_poc_lsb_sps */
            bs_skip( p_bs, p_sps->log2_max_pic_order_cnt_lsb_minus4 + 4 );
             /* used_by_curr_pic_lt_sps_flag */
            bs_skip( p_bs, 1 );
        }
    }

    p_sps->sps_temporal_mvp_enabled_flag = bs_read1( p_bs );
    p_sps->strong_intra_smoothing_enabled_flag = bs_read1( p_bs );

    if( bs_remain( p_bs ) < 1 ) /* late fail */
        return false;

    p_sps->vui_parameters_present_flag = bs_read1( p_bs );
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
    if( p_sps->vui_parameters_present_flag )
    {
        bs_t rollbackpoint = *p_bs;
        if( !hevc_parse_vui_parameters_rbsp( p_bs, &p_sps->vui, false ) &&
            p_sps->vui.default_display_window_flag &&
            bs_remain( p_bs ) < 66 )
        {
            /* Broken MKV SPS vui bitstreams with missing display_window bits.
             * Forced to accept it since some decided to accept it...
             * see https://trac.ffmpeg.org/ticket/6644
             * Might break decoders since cropping & clock rate have totally
             * funky values when decoded properly */
            *p_bs = rollbackpoint;
            memset( &p_sps->vui, 0, sizeof(p_sps->vui) );
            if( !hevc_parse_vui_parameters_rbsp( p_bs, &p_sps->vui, true ) )
                return false;
        }
    }
920 921 922

    /* incomplete */

923 924 925 926 927 928 929 930
    return true;
}

void hevc_rbsp_release_sps( hevc_sequence_parameter_set_t *p_sps )
{
    free( p_sps );
}

931 932
IMPL_hevc_generic_decode( hevc_decode_sps, hevc_sequence_parameter_set_t,
                          hevc_parse_sequence_parameter_set_rbsp, hevc_rbsp_release_sps )
933 934 935 936 937 938 939

static bool hevc_parse_pic_parameter_set_rbsp( bs_t *p_bs,
                                               hevc_picture_parameter_set_t *p_pps )
{
    if( bs_remain( p_bs ) < 1 )
        return false;
    p_pps->pps_pic_parameter_set_id = bs_read_ue( p_bs );
940
    if( p_pps->pps_pic_parameter_set_id > HEVC_PPS_ID_MAX || bs_remain( p_bs ) < 1 )
941 942
        return false;
    p_pps->pps_seq_parameter_set_id = bs_read_ue( p_bs );
943
    if( p_pps->pps_seq_parameter_set_id > HEVC_SPS_ID_MAX )
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
        return false;
    p_pps->dependent_slice_segments_enabled_flag = bs_read1( p_bs );
    p_pps->output_flag_present_flag = bs_read1( p_bs );
    p_pps->num_extra_slice_header_bits = bs_read( p_bs, 3 );
    p_pps->sign_data_hiding_enabled_flag = bs_read1( p_bs );
    p_pps->cabac_init_present_flag = bs_read1( p_bs );

    p_pps->num_ref_idx_l0_default_active_minus1 = bs_read_ue( p_bs );
    p_pps->num_ref_idx_l1_default_active_minus1 = bs_read_ue( p_bs );

    p_pps->init_qp_minus26 = bs_read_se( p_bs );
    p_pps->constrained_intra_pred_flag = bs_read1( p_bs );
    p_pps->transform_skip_enabled_flag = bs_read1( p_bs );
    p_pps->cu_qp_delta_enabled_flag = bs_read1( p_bs );
    if( p_pps->cu_qp_delta_enabled_flag )
        p_pps->diff_cu_qp_delta_depth = bs_read_ue( p_bs );

    if( bs_remain( p_bs ) < 1 )
        return false;

    p_pps->pps_cb_qp_offset = bs_read_se( p_bs );
    p_pps->pps_cr_qp_offset = bs_read_se( p_bs );
    p_pps->pic_slice_level_chroma_qp_offsets_present_flag = bs_read1( p_bs );
    p_pps->weighted_pred_flag = bs_read1( p_bs );
    p_pps->weighted_bipred_flag = bs_read1( p_bs );
    p_pps->transquant_bypass_enable_flag = bs_read1( p_bs );
    p_pps->tiles_enabled_flag = bs_read1( p_bs );
    p_pps->entropy_coding_sync_enabled_flag = bs_read1( p_bs );

    if( p_pps->tiles_enabled_flag )
    {
        p_pps->num_tile_columns_minus1 = bs_read_ue( p_bs ); /* TODO: validate max col/row values */
        p_pps->num_tile_rows_minus1 = bs_read_ue( p_bs );    /*       against sps PicWidthInCtbsY */
        p_pps->uniform_spacing_flag = bs_read1( p_bs );
        if( !p_pps->uniform_spacing_flag )
        {
980 981
            if( bs_remain( p_bs ) < p_pps->num_tile_columns_minus1 +
                                    p_pps->num_tile_rows_minus1 + 1 )
982
                return false;
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
            for( unsigned i=0; i< p_pps->num_tile_columns_minus1; i++ )
                (void) bs_read_ue( p_bs );
            for( unsigned i=0; i< p_pps->num_tile_rows_minus1; i++ )
                (void) bs_read_ue( p_bs );
        }
        p_pps->loop_filter_across_tiles_enabled_flag = bs_read1( p_bs );
    }

    p_pps->pps_loop_filter_across_slices_enabled_flag = bs_read1( p_bs );
    p_pps->deblocking_filter_control_present_flag = bs_read1( p_bs );
    if( p_pps->deblocking_filter_control_present_flag )
    {
        p_pps->deblocking_filter_override_enabled_flag = bs_read1( p_bs );
        p_pps->pps_deblocking_filter_disabled_flag = bs_read1( p_bs );
        if( !p_pps->pps_deblocking_filter_disabled_flag )
        {
            p_pps->pps_beta_offset_div2 = bs_read_se( p_bs );
            p_pps->pps_tc_offset_div2 = bs_read_se( p_bs );
        }
    }

    p_pps->scaling_list_data_present_flag = bs_read1( p_bs );
    if( p_pps->scaling_list_data_present_flag && !hevc_parse_scaling_list_rbsp( p_bs ) )
        return false;

    p_pps->lists_modification_present_flag = bs_read1( p_bs );
    p_pps->log2_parallel_merge_level_minus2 = bs_read_ue( p_bs );
    p_pps->slice_header_extension_present_flag = bs_read1( p_bs );

    if( bs_remain( p_bs ) < 1 )
        return false;

    p_pps->pps_extension_present_flag = bs_read1( p_bs );
    if( p_pps->pps_extension_present_flag )
    {
        p_pps->pps_range_extension_flag = bs_read1( p_bs );
        p_pps->pps_multilayer_extension_flag = bs_read1( p_bs );
        p_pps->pps_3d_extension_flag = bs_read1( p_bs );
        if( bs_remain( p_bs ) < 5 )
            return false;
        p_pps->pps_extension_5bits = bs_read( p_bs, 5 );
    }

    return true;
}

void hevc_rbsp_release_pps( hevc_picture_parameter_set_t *p_pps )
{
    free( p_pps );
}

1034 1035
IMPL_hevc_generic_decode( hevc_decode_pps, hevc_picture_parameter_set_t,
                          hevc_parse_pic_parameter_set_rbsp, hevc_rbsp_release_pps )
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
uint8_t hevc_get_sps_vps_id( const hevc_sequence_parameter_set_t *p_sps )
{
    return p_sps->sps_video_parameter_set_id;
}

uint8_t hevc_get_pps_sps_id( const hevc_picture_parameter_set_t *p_pps )
{
    return p_pps->pps_seq_parameter_set_id;
}

1047 1048 1049 1050 1051
uint8_t hevc_get_slice_pps_id( const hevc_slice_segment_header_t *p_slice )
{
    return p_slice->slice_pic_parameter_set_id;
}

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
bool hevc_get_sps_profile_tier_level( const hevc_sequence_parameter_set_t *p_sps,
                                      uint8_t *pi_profile, uint8_t *pi_level)
{
    if(p_sps->profile_tier_level.general.profile_idc)
    {
        *pi_profile = p_sps->profile_tier_level.general.profile_idc;
        *pi_level = p_sps->profile_tier_level.general_level_idc;
        return true;
    }
    return false;
}

1064 1065 1066 1067 1068 1069 1070
bool hevc_get_picture_size( const hevc_sequence_parameter_set_t *p_sps,
                            unsigned *p_w, unsigned *p_h, unsigned *p_vw, unsigned *p_vh )
{
    *p_w = *p_vw = p_sps->pic_width_in_luma_samples;
    *p_h = *p_vh = p_sps->pic_height_in_luma_samples;
    if( p_sps->conformance_window_flag )
    {
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
        unsigned sub_width_c, sub_height_c;

        if( p_sps->chroma_format_idc == 1 )
        {
            sub_width_c = 2;
            sub_height_c = 2;
        }
        else if( p_sps->chroma_format_idc == 2 )
        {
            sub_width_c = 2;
            sub_height_c = 1;
        }
        else
        {
            sub_width_c = 1;
            sub_height_c = 1;
        }

        *p_vh -= (p_sps->conf_win.bottom_offset + p_sps->conf_win.top_offset) * sub_height_c;
        *p_vw -= (p_sps->conf_win.left_offset +  p_sps->conf_win.right_offset) * sub_width_c;
1091 1092 1093 1094
    }
    return true;
}

1095 1096
uint8_t hevc_get_max_num_reorder( const hevc_video_parameter_set_t *p_vps )
{
1097
    return p_vps->vps_max[p_vps->vps_max_sub_layers_minus1/* HighestTid */].num_reorder_pics;
1098 1099
}

1100 1101 1102 1103 1104 1105 1106 1107
static inline uint8_t vlc_ceil_log2( uint32_t val )
{
    uint8_t n = 31 - clz(val);
    if (((unsigned)1 << n) != val)
        n++;
    return n;
}

1108 1109 1110 1111
static bool hevc_get_picture_CtbsYsize( const hevc_sequence_parameter_set_t *p_sps, unsigned *p_w, unsigned *p_h )
{
    const unsigned int MinCbLog2SizeY = p_sps->log2_min_luma_coding_block_size_minus3 + 3;
    const unsigned int CtbLog2SizeY = MinCbLog2SizeY + p_sps->log2_diff_max_min_luma_coding_block_size;
1112
    if( CtbLog2SizeY > 31 )
1113 1114 1115 1116 1117 1118 1119
        return false;
    const unsigned int CtbSizeY = 1 << CtbLog2SizeY;
    *p_w = (p_sps->pic_width_in_luma_samples - 1) / CtbSizeY + 1;
    *p_h = (p_sps->pic_height_in_luma_samples - 1) / CtbSizeY + 1;
    return true;
}

1120
bool hevc_get_frame_rate( const hevc_sequence_parameter_set_t *p_sps,
1121
                          const hevc_video_parameter_set_t *p_vps,
1122 1123 1124 1125 1126 1127
                          unsigned *pi_num, unsigned *pi_den )
{
    if( p_sps->vui_parameters_present_flag && p_sps->vui.vui_timing_info_present_flag )
    {
        *pi_den = p_sps->vui.timing.vui_num_units_in_tick;
        *pi_num = p_sps->vui.timing.vui_time_scale;
1128
        return (*pi_den && *pi_num);
1129
    }
1130
    else if( p_vps && p_vps->vps_timing_info_present_flag )
1131
    {
1132 1133
        *pi_den = p_vps->vps_num_units_in_tick;
        *pi_num = p_vps->vps_time_scale;
1134
        return (*pi_den && *pi_num);
1135 1136 1137 1138
    }
    return false;
}

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
bool hevc_get_aspect_ratio( const hevc_sequence_parameter_set_t *p_sps,
                            unsigned *num, unsigned *den )
{
    if( p_sps->vui_parameters_present_flag )
    {
        if( p_sps->vui.ar.aspect_ratio_idc != 255 )
        {
            static const uint8_t ar_table[16][2] =
            {
                {    1,      1 },
                {   12,     11 },
                {   10,     11 },
                {   16,     11 },
                {   40,     33 },
                {   24,     11 },
                {   20,     11 },
                {   32,     11 },
                {   80,     33 },
                {   18,     11 },
                {   15,     11 },
                {   64,     33 },
                {  160,     99 },
                {    4,      3 },
                {    3,      2 },
                {    2,      1 },
            };
            if( p_sps->vui.ar.aspect_ratio_idc > 0 &&
                p_sps->vui.ar.aspect_ratio_idc < 17 )
            {
                *num = ar_table[p_sps->vui.ar.aspect_ratio_idc - 1][0];
                *den = ar_table[p_sps->vui.ar.aspect_ratio_idc - 1][1];
                return true;
            }
        }
        else
        {
            *num = p_sps->vui.ar.sar_width;
            *den = p_sps->vui.ar.sar_height;
            return true;
        }
    }
    return false;
}

1183 1184 1185 1186 1187 1188 1189 1190 1191
bool hevc_get_chroma_luma( const hevc_sequence_parameter_set_t *p_sps, uint8_t *pi_chroma_format,
                           uint8_t *pi_depth_luma, uint8_t *pi_depth_chroma )
{
    *pi_chroma_format = p_sps->chroma_format_idc;
    *pi_depth_luma = p_sps->bit_depth_chroma_minus8 + 8;
    *pi_depth_chroma = p_sps->bit_depth_chroma_minus8 + 8;
    return true;
}

1192 1193 1194 1195 1196 1197 1198 1199 1200
bool hevc_get_colorimetry( const hevc_sequence_parameter_set_t *p_sps,
                           video_color_primaries_t *p_primaries,
                           video_transfer_func_t *p_transfer,
                           video_color_space_t *p_colorspace,
                           bool *p_full_range )
{
    if( !p_sps->vui_parameters_present_flag )
        return false;
    *p_primaries =
1201
        iso_23001_8_cp_to_vlc_primaries( p_sps->vui.vs.colour.colour_primaries );
1202
    *p_transfer =
1203
        iso_23001_8_tc_to_vlc_xfer( p_sps->vui.vs.colour.transfer_characteristics );
1204
    *p_colorspace =
1205
        iso_23001_8_mc_to_vlc_coeffs( p_sps->vui.vs.colour.matrix_coeffs );
1206 1207 1208 1209
    *p_full_range = p_sps->vui.vs.video_full_range_flag;
    return true;
}

1210
static bool hevc_parse_slice_segment_header_rbsp( bs_t *p_bs,
1211 1212
                                                  pf_get_matchedxps get_matchedxps,
                                                  void *priv,
1213 1214
                                                  hevc_slice_segment_header_t *p_sl )
{
1215 1216 1217 1218
    hevc_sequence_parameter_set_t *p_sps;
    hevc_picture_parameter_set_t *p_pps;
    hevc_video_parameter_set_t *p_vps;

1219 1220 1221 1222
    if( bs_remain( p_bs ) < 3 )
        return false;

    p_sl->first_slice_segment_in_pic_flag = bs_read1( p_bs );
1223
    if( p_sl->nal_type >= HEVC_NAL_BLA_W_LP && p_sl->nal_type <= HEVC_NAL_IRAP_VCL23 )
1224
        p_sl->no_output_of_prior_pics_flag = bs_read1( p_bs );
1225
    p_sl->slice_pic_parameter_set_id = bs_read_ue( p_bs );
1226
    if( p_sl->slice_pic_parameter_set_id > HEVC_PPS_ID_MAX || bs_remain( p_bs ) < 1 )
1227 1228
        return false;

1229 1230
    get_matchedxps( p_sl->slice_pic_parameter_set_id, priv, &p_pps, &p_sps, &p_vps );
    if(!p_sps || !p_pps)
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
        return false;

    if( !p_sl->first_slice_segment_in_pic_flag )
    {
        if( p_pps->dependent_slice_segments_enabled_flag )
            p_sl->dependent_slice_segment_flag = bs_read1( p_bs );

        unsigned w, h;
        if( !hevc_get_picture_CtbsYsize( p_sps, &w, &h ) )
            return false;

        (void) bs_read( p_bs, vlc_ceil_log2( w * h ) ); /* slice_segment_address */
    }

    if( !p_sl->dependent_slice_segment_flag )
    {
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        unsigned i=0;
        if( p_pps->num_extra_slice_header_bits > i )
        {
            i++;
            bs_skip( p_bs, 1 ); /* discardable_flag */
        }

        if( p_pps->num_extra_slice_header_bits > i )
        {
            i++;
            bs_skip( p_bs, 1 ); /* cross_layer_bla_flag */
        }

        if( i < p_pps->num_extra_slice_header_bits )
           bs_skip( p_bs, p_pps->num_extra_slice_header_bits - i );
1262 1263 1264 1265 1266 1267 1268

        p_sl->slice_type = bs_read_ue( p_bs );
        if( p_sl->slice_type > HEVC_SLICE_TYPE_I )
            return false;

        if( p_pps->output_flag_present_flag )
            p_sl->pic_output_flag = bs_read1( p_bs );
1269 1270
        else
            p_sl->pic_output_flag = 1;
1271 1272
    }

1273 1274 1275 1276 1277 1278 1279 1280
    if( p_sps->separate_colour_plane_flag )
        bs_skip( p_bs, 2 ); /* colour_plane_id */

    if( p_sl->nal_type != HEVC_NAL_IDR_W_RADL && p_sl->nal_type != HEVC_NAL_IDR_N_LP )
        p_sl->pic_order_cnt_lsb = bs_read( p_bs, p_sps->log2_max_pic_order_cnt_lsb_minus4 + 4 );
    else
        p_sl->pic_order_cnt_lsb = 0;

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    if( bs_remain( p_bs ) < 1 )
        return false;

    return true;
}

void hevc_rbsp_release_slice_header( hevc_slice_segment_header_t *p_sh )
{
    free( p_sh );
}

1292
hevc_slice_segment_header_t * hevc_decode_slice_header( const uint8_t *p_buf, size_t i_buf, bool b_escaped,
1293
                                                        pf_get_matchedxps get_matchedxps, void *priv )
1294 1295 1296 1297 1298
{
    hevc_slice_segment_header_t *p_sh = calloc(1, sizeof(hevc_slice_segment_header_t));
    if(likely(p_sh))
    {
        bs_t bs;
1299
        struct hxxx_bsfw_ep3b_ctx_s bsctx;
1300 1301
        if( b_escaped )
        {
1302 1303
            hxxx_bsfw_ep3b_ctx_init( &bsctx );
            bs_init_custom( &bs, p_buf, i_buf, &hxxx_bsfw_ep3b_callbacks, &bsctx );
1304
        }
1305
        else bs_init( &bs, p_buf, i_buf );
1306 1307 1308
        bs_skip( &bs, 1 );
        p_sh->nal_type = bs_read( &bs, 6 );
        p_sh->nuh_layer_id = bs_read( &bs, 6 );
1309 1310
        p_sh->temporal_id_plus1 = bs_read( &bs, 3 );
        if( p_sh->nuh_layer_id > 62 || p_sh->temporal_id_plus1 == 0 ||
1311
           !hevc_parse_slice_segment_header_rbsp( &bs, get_matchedxps, priv, p_sh ) )
1312 1313 1314 1315 1316 1317 1318
        {
            hevc_rbsp_release_slice_header( p_sh );
            p_sh = NULL;
        }
    }
    return p_sh;
}
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328

bool hevc_get_slice_type( const hevc_slice_segment_header_t *p_sli, enum hevc_slice_type_e *pi_type )
{
    if( !p_sli->dependent_slice_segment_flag )
    {
        *pi_type = p_sli->slice_type;
        return true;
    }
    return false;
}
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348

bool hevc_get_profile_level(const es_format_t *p_fmt, uint8_t *pi_profile,
                            uint8_t *pi_level, uint8_t *pi_nal_length_size)
{
    const uint8_t *p = (const uint8_t*)p_fmt->p_extra;
    if(p_fmt->i_extra < 23 || p[0] != 1)
        return false;

    /* HEVCDecoderConfigurationRecord */
    if(pi_profile)
        *pi_profile = p[1] & 0x1F;

    if(pi_level)
        *pi_level = p[12];

    if (pi_nal_length_size)
        *pi_nal_length_size = 1 + (p[21]&0x03);

    return true;
}
1349

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
/*
 * HEVCDecoderConfigurationRecord operations
 */

static void hevc_dcr_params_from_vps( const uint8_t * p_buffer, size_t i_buffer,
                                      struct hevc_dcr_values *p_values )
{
    if( i_buffer < 19 )
        return;

    bs_t bs;
1361 1362 1363
    struct hxxx_bsfw_ep3b_ctx_s bsctx;
    hxxx_bsfw_ep3b_ctx_init( &bsctx );
    bs_init_custom( &bs, p_buffer, i_buffer, &hxxx_bsfw_ep3b_callbacks, &bsctx );
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443