LCOV - code coverage report
Current view: top level - libavformat - hevc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 343 511 67.1 %
Date: 2017-12-15 11:05:35 Functions: 17 22 77.3 %

          Line data    Source code
       1             : /*
       2             :  * Copyright (c) 2014 Tim Walker <tdskywalker@gmail.com>
       3             :  *
       4             :  * This file is part of FFmpeg.
       5             :  *
       6             :  * FFmpeg is free software; you can redistribute it and/or
       7             :  * modify it under the terms of the GNU Lesser General Public
       8             :  * License as published by the Free Software Foundation; either
       9             :  * version 2.1 of the License, or (at your option) any later version.
      10             :  *
      11             :  * FFmpeg is distributed in the hope that it will be useful,
      12             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      13             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      14             :  * Lesser General Public License for more details.
      15             :  *
      16             :  * You should have received a copy of the GNU Lesser General Public
      17             :  * License along with FFmpeg; if not, write to the Free Software
      18             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      19             :  */
      20             : 
      21             : #include "libavcodec/avcodec.h"
      22             : #include "libavcodec/get_bits.h"
      23             : #include "libavcodec/golomb.h"
      24             : #include "libavcodec/hevc.h"
      25             : #include "libavutil/intreadwrite.h"
      26             : #include "avc.h"
      27             : #include "avio.h"
      28             : #include "hevc.h"
      29             : 
      30             : #define MAX_SPATIAL_SEGMENTATION 4096 // max. value of u(12) field
      31             : 
      32             : typedef struct HVCCNALUnitArray {
      33             :     uint8_t  array_completeness;
      34             :     uint8_t  NAL_unit_type;
      35             :     uint16_t numNalus;
      36             :     uint16_t *nalUnitLength;
      37             :     uint8_t  **nalUnit;
      38             : } HVCCNALUnitArray;
      39             : 
      40             : typedef struct HEVCDecoderConfigurationRecord {
      41             :     uint8_t  configurationVersion;
      42             :     uint8_t  general_profile_space;
      43             :     uint8_t  general_tier_flag;
      44             :     uint8_t  general_profile_idc;
      45             :     uint32_t general_profile_compatibility_flags;
      46             :     uint64_t general_constraint_indicator_flags;
      47             :     uint8_t  general_level_idc;
      48             :     uint16_t min_spatial_segmentation_idc;
      49             :     uint8_t  parallelismType;
      50             :     uint8_t  chromaFormat;
      51             :     uint8_t  bitDepthLumaMinus8;
      52             :     uint8_t  bitDepthChromaMinus8;
      53             :     uint16_t avgFrameRate;
      54             :     uint8_t  constantFrameRate;
      55             :     uint8_t  numTemporalLayers;
      56             :     uint8_t  temporalIdNested;
      57             :     uint8_t  lengthSizeMinusOne;
      58             :     uint8_t  numOfArrays;
      59             :     HVCCNALUnitArray *array;
      60             : } HEVCDecoderConfigurationRecord;
      61             : 
      62             : typedef struct HVCCProfileTierLevel {
      63             :     uint8_t  profile_space;
      64             :     uint8_t  tier_flag;
      65             :     uint8_t  profile_idc;
      66             :     uint32_t profile_compatibility_flags;
      67             :     uint64_t constraint_indicator_flags;
      68             :     uint8_t  level_idc;
      69             : } HVCCProfileTierLevel;
      70             : 
      71           2 : static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc,
      72             :                             HVCCProfileTierLevel *ptl)
      73             : {
      74             :     /*
      75             :      * The value of general_profile_space in all the parameter sets must be
      76             :      * identical.
      77             :      */
      78           2 :     hvcc->general_profile_space = ptl->profile_space;
      79             : 
      80             :     /*
      81             :      * The level indication general_level_idc must indicate a level of
      82             :      * capability equal to or greater than the highest level indicated for the
      83             :      * highest tier in all the parameter sets.
      84             :      */
      85           2 :     if (hvcc->general_tier_flag < ptl->tier_flag)
      86           0 :         hvcc->general_level_idc = ptl->level_idc;
      87             :     else
      88           2 :         hvcc->general_level_idc = FFMAX(hvcc->general_level_idc, ptl->level_idc);
      89             : 
      90             :     /*
      91             :      * The tier indication general_tier_flag must indicate a tier equal to or
      92             :      * greater than the highest tier indicated in all the parameter sets.
      93             :      */
      94           2 :     hvcc->general_tier_flag = FFMAX(hvcc->general_tier_flag, ptl->tier_flag);
      95             : 
      96             :     /*
      97             :      * The profile indication general_profile_idc must indicate a profile to
      98             :      * which the stream associated with this configuration record conforms.
      99             :      *
     100             :      * If the sequence parameter sets are marked with different profiles, then
     101             :      * the stream may need examination to determine which profile, if any, the
     102             :      * entire stream conforms to. If the entire stream is not examined, or the
     103             :      * examination reveals that there is no profile to which the entire stream
     104             :      * conforms, then the entire stream must be split into two or more
     105             :      * sub-streams with separate configuration records in which these rules can
     106             :      * be met.
     107             :      *
     108             :      * Note: set the profile to the highest value for the sake of simplicity.
     109             :      */
     110           2 :     hvcc->general_profile_idc = FFMAX(hvcc->general_profile_idc, ptl->profile_idc);
     111             : 
     112             :     /*
     113             :      * Each bit in general_profile_compatibility_flags may only be set if all
     114             :      * the parameter sets set that bit.
     115             :      */
     116           2 :     hvcc->general_profile_compatibility_flags &= ptl->profile_compatibility_flags;
     117             : 
     118             :     /*
     119             :      * Each bit in general_constraint_indicator_flags may only be set if all
     120             :      * the parameter sets set that bit.
     121             :      */
     122           2 :     hvcc->general_constraint_indicator_flags &= ptl->constraint_indicator_flags;
     123           2 : }
     124             : 
     125           2 : static void hvcc_parse_ptl(GetBitContext *gb,
     126             :                            HEVCDecoderConfigurationRecord *hvcc,
     127             :                            unsigned int max_sub_layers_minus1)
     128             : {
     129             :     unsigned int i;
     130             :     HVCCProfileTierLevel general_ptl;
     131             :     uint8_t sub_layer_profile_present_flag[HEVC_MAX_SUB_LAYERS];
     132             :     uint8_t sub_layer_level_present_flag[HEVC_MAX_SUB_LAYERS];
     133             : 
     134           2 :     general_ptl.profile_space               = get_bits(gb, 2);
     135           2 :     general_ptl.tier_flag                   = get_bits1(gb);
     136           2 :     general_ptl.profile_idc                 = get_bits(gb, 5);
     137           2 :     general_ptl.profile_compatibility_flags = get_bits_long(gb, 32);
     138           2 :     general_ptl.constraint_indicator_flags  = get_bits64(gb, 48);
     139           2 :     general_ptl.level_idc                   = get_bits(gb, 8);
     140           2 :     hvcc_update_ptl(hvcc, &general_ptl);
     141             : 
     142           2 :     for (i = 0; i < max_sub_layers_minus1; i++) {
     143           0 :         sub_layer_profile_present_flag[i] = get_bits1(gb);
     144           0 :         sub_layer_level_present_flag[i]   = get_bits1(gb);
     145             :     }
     146             : 
     147           2 :     if (max_sub_layers_minus1 > 0)
     148           0 :         for (i = max_sub_layers_minus1; i < 8; i++)
     149           0 :             skip_bits(gb, 2); // reserved_zero_2bits[i]
     150             : 
     151           2 :     for (i = 0; i < max_sub_layers_minus1; i++) {
     152           0 :         if (sub_layer_profile_present_flag[i]) {
     153             :             /*
     154             :              * sub_layer_profile_space[i]                     u(2)
     155             :              * sub_layer_tier_flag[i]                         u(1)
     156             :              * sub_layer_profile_idc[i]                       u(5)
     157             :              * sub_layer_profile_compatibility_flag[i][0..31] u(32)
     158             :              * sub_layer_progressive_source_flag[i]           u(1)
     159             :              * sub_layer_interlaced_source_flag[i]            u(1)
     160             :              * sub_layer_non_packed_constraint_flag[i]        u(1)
     161             :              * sub_layer_frame_only_constraint_flag[i]        u(1)
     162             :              * sub_layer_reserved_zero_44bits[i]              u(44)
     163             :              */
     164           0 :             skip_bits_long(gb, 32);
     165           0 :             skip_bits_long(gb, 32);
     166           0 :             skip_bits     (gb, 24);
     167             :         }
     168             : 
     169           0 :         if (sub_layer_level_present_flag[i])
     170           0 :             skip_bits(gb, 8);
     171             :     }
     172           2 : }
     173             : 
     174           0 : static void skip_sub_layer_hrd_parameters(GetBitContext *gb,
     175             :                                           unsigned int cpb_cnt_minus1,
     176             :                                           uint8_t sub_pic_hrd_params_present_flag)
     177             : {
     178             :     unsigned int i;
     179             : 
     180           0 :     for (i = 0; i <= cpb_cnt_minus1; i++) {
     181           0 :         get_ue_golomb_long(gb); // bit_rate_value_minus1
     182           0 :         get_ue_golomb_long(gb); // cpb_size_value_minus1
     183             : 
     184           0 :         if (sub_pic_hrd_params_present_flag) {
     185           0 :             get_ue_golomb_long(gb); // cpb_size_du_value_minus1
     186           0 :             get_ue_golomb_long(gb); // bit_rate_du_value_minus1
     187             :         }
     188             : 
     189           0 :         skip_bits1(gb); // cbr_flag
     190             :     }
     191           0 : }
     192             : 
     193           0 : static int skip_hrd_parameters(GetBitContext *gb, uint8_t cprms_present_flag,
     194             :                                 unsigned int max_sub_layers_minus1)
     195             : {
     196             :     unsigned int i;
     197           0 :     uint8_t sub_pic_hrd_params_present_flag = 0;
     198           0 :     uint8_t nal_hrd_parameters_present_flag = 0;
     199           0 :     uint8_t vcl_hrd_parameters_present_flag = 0;
     200             : 
     201           0 :     if (cprms_present_flag) {
     202           0 :         nal_hrd_parameters_present_flag = get_bits1(gb);
     203           0 :         vcl_hrd_parameters_present_flag = get_bits1(gb);
     204             : 
     205           0 :         if (nal_hrd_parameters_present_flag ||
     206             :             vcl_hrd_parameters_present_flag) {
     207           0 :             sub_pic_hrd_params_present_flag = get_bits1(gb);
     208             : 
     209           0 :             if (sub_pic_hrd_params_present_flag)
     210             :                 /*
     211             :                  * tick_divisor_minus2                          u(8)
     212             :                  * du_cpb_removal_delay_increment_length_minus1 u(5)
     213             :                  * sub_pic_cpb_params_in_pic_timing_sei_flag    u(1)
     214             :                  * dpb_output_delay_du_length_minus1            u(5)
     215             :                  */
     216           0 :                 skip_bits(gb, 19);
     217             : 
     218             :             /*
     219             :              * bit_rate_scale u(4)
     220             :              * cpb_size_scale u(4)
     221             :              */
     222           0 :             skip_bits(gb, 8);
     223             : 
     224           0 :             if (sub_pic_hrd_params_present_flag)
     225           0 :                 skip_bits(gb, 4); // cpb_size_du_scale
     226             : 
     227             :             /*
     228             :              * initial_cpb_removal_delay_length_minus1 u(5)
     229             :              * au_cpb_removal_delay_length_minus1      u(5)
     230             :              * dpb_output_delay_length_minus1          u(5)
     231             :              */
     232           0 :             skip_bits(gb, 15);
     233             :         }
     234             :     }
     235             : 
     236           0 :     for (i = 0; i <= max_sub_layers_minus1; i++) {
     237           0 :         unsigned int cpb_cnt_minus1            = 0;
     238           0 :         uint8_t low_delay_hrd_flag             = 0;
     239           0 :         uint8_t fixed_pic_rate_within_cvs_flag = 0;
     240           0 :         uint8_t fixed_pic_rate_general_flag    = get_bits1(gb);
     241             : 
     242           0 :         if (!fixed_pic_rate_general_flag)
     243           0 :             fixed_pic_rate_within_cvs_flag = get_bits1(gb);
     244             : 
     245           0 :         if (fixed_pic_rate_within_cvs_flag)
     246           0 :             get_ue_golomb_long(gb); // elemental_duration_in_tc_minus1
     247             :         else
     248           0 :             low_delay_hrd_flag = get_bits1(gb);
     249             : 
     250           0 :         if (!low_delay_hrd_flag) {
     251           0 :             cpb_cnt_minus1 = get_ue_golomb_long(gb);
     252           0 :             if (cpb_cnt_minus1 > 31)
     253           0 :                 return AVERROR_INVALIDDATA;
     254             :         }
     255             : 
     256           0 :         if (nal_hrd_parameters_present_flag)
     257           0 :             skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
     258             :                                           sub_pic_hrd_params_present_flag);
     259             : 
     260           0 :         if (vcl_hrd_parameters_present_flag)
     261           0 :             skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
     262             :                                           sub_pic_hrd_params_present_flag);
     263             :     }
     264             : 
     265           0 :     return 0;
     266             : }
     267             : 
     268           0 : static void skip_timing_info(GetBitContext *gb)
     269             : {
     270           0 :     skip_bits_long(gb, 32); // num_units_in_tick
     271           0 :     skip_bits_long(gb, 32); // time_scale
     272             : 
     273           0 :     if (get_bits1(gb))          // poc_proportional_to_timing_flag
     274           0 :         get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1
     275           0 : }
     276             : 
     277           1 : static void hvcc_parse_vui(GetBitContext *gb,
     278             :                            HEVCDecoderConfigurationRecord *hvcc,
     279             :                            unsigned int max_sub_layers_minus1)
     280             : {
     281             :     unsigned int min_spatial_segmentation_idc;
     282             : 
     283           1 :     if (get_bits1(gb))              // aspect_ratio_info_present_flag
     284           1 :         if (get_bits(gb, 8) == 255) // aspect_ratio_idc
     285           0 :             skip_bits_long(gb, 32); // sar_width u(16), sar_height u(16)
     286             : 
     287           1 :     if (get_bits1(gb))  // overscan_info_present_flag
     288           0 :         skip_bits1(gb); // overscan_appropriate_flag
     289             : 
     290           1 :     if (get_bits1(gb)) {  // video_signal_type_present_flag
     291           0 :         skip_bits(gb, 4); // video_format u(3), video_full_range_flag u(1)
     292             : 
     293           0 :         if (get_bits1(gb)) // colour_description_present_flag
     294             :             /*
     295             :              * colour_primaries         u(8)
     296             :              * transfer_characteristics u(8)
     297             :              * matrix_coeffs            u(8)
     298             :              */
     299           0 :             skip_bits(gb, 24);
     300             :     }
     301             : 
     302           1 :     if (get_bits1(gb)) {        // chroma_loc_info_present_flag
     303           0 :         get_ue_golomb_long(gb); // chroma_sample_loc_type_top_field
     304           0 :         get_ue_golomb_long(gb); // chroma_sample_loc_type_bottom_field
     305             :     }
     306             : 
     307             :     /*
     308             :      * neutral_chroma_indication_flag u(1)
     309             :      * field_seq_flag                 u(1)
     310             :      * frame_field_info_present_flag  u(1)
     311             :      */
     312           1 :     skip_bits(gb, 3);
     313             : 
     314           1 :     if (get_bits1(gb)) {        // default_display_window_flag
     315           1 :         get_ue_golomb_long(gb); // def_disp_win_left_offset
     316           1 :         get_ue_golomb_long(gb); // def_disp_win_right_offset
     317           1 :         get_ue_golomb_long(gb); // def_disp_win_top_offset
     318           1 :         get_ue_golomb_long(gb); // def_disp_win_bottom_offset
     319             :     }
     320             : 
     321           1 :     if (get_bits1(gb)) { // vui_timing_info_present_flag
     322           0 :         skip_timing_info(gb);
     323             : 
     324           0 :         if (get_bits1(gb)) // vui_hrd_parameters_present_flag
     325           0 :             skip_hrd_parameters(gb, 1, max_sub_layers_minus1);
     326             :     }
     327             : 
     328           1 :     if (get_bits1(gb)) { // bitstream_restriction_flag
     329             :         /*
     330             :          * tiles_fixed_structure_flag              u(1)
     331             :          * motion_vectors_over_pic_boundaries_flag u(1)
     332             :          * restricted_ref_pic_lists_flag           u(1)
     333             :          */
     334           0 :         skip_bits(gb, 3);
     335             : 
     336           0 :         min_spatial_segmentation_idc = get_ue_golomb_long(gb);
     337             : 
     338             :         /*
     339             :          * unsigned int(12) min_spatial_segmentation_idc;
     340             :          *
     341             :          * The min_spatial_segmentation_idc indication must indicate a level of
     342             :          * spatial segmentation equal to or less than the lowest level of
     343             :          * spatial segmentation indicated in all the parameter sets.
     344             :          */
     345           0 :         hvcc->min_spatial_segmentation_idc = FFMIN(hvcc->min_spatial_segmentation_idc,
     346             :                                                    min_spatial_segmentation_idc);
     347             : 
     348           0 :         get_ue_golomb_long(gb); // max_bytes_per_pic_denom
     349           0 :         get_ue_golomb_long(gb); // max_bits_per_min_cu_denom
     350           0 :         get_ue_golomb_long(gb); // log2_max_mv_length_horizontal
     351           0 :         get_ue_golomb_long(gb); // log2_max_mv_length_vertical
     352             :     }
     353           1 : }
     354             : 
     355           1 : static void skip_sub_layer_ordering_info(GetBitContext *gb)
     356             : {
     357           1 :     get_ue_golomb_long(gb); // max_dec_pic_buffering_minus1
     358           1 :     get_ue_golomb_long(gb); // max_num_reorder_pics
     359           1 :     get_ue_golomb_long(gb); // max_latency_increase_plus1
     360           1 : }
     361             : 
     362           1 : static int hvcc_parse_vps(GetBitContext *gb,
     363             :                           HEVCDecoderConfigurationRecord *hvcc)
     364             : {
     365             :     unsigned int vps_max_sub_layers_minus1;
     366             : 
     367             :     /*
     368             :      * vps_video_parameter_set_id u(4)
     369             :      * vps_reserved_three_2bits   u(2)
     370             :      * vps_max_layers_minus1      u(6)
     371             :      */
     372           1 :     skip_bits(gb, 12);
     373             : 
     374           1 :     vps_max_sub_layers_minus1 = get_bits(gb, 3);
     375             : 
     376             :     /*
     377             :      * numTemporalLayers greater than 1 indicates that the stream to which this
     378             :      * configuration record applies is temporally scalable and the contained
     379             :      * number of temporal layers (also referred to as temporal sub-layer or
     380             :      * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
     381             :      * indicates that the stream is not temporally scalable. Value 0 indicates
     382             :      * that it is unknown whether the stream is temporally scalable.
     383             :      */
     384           1 :     hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
     385             :                                     vps_max_sub_layers_minus1 + 1);
     386             : 
     387             :     /*
     388             :      * vps_temporal_id_nesting_flag u(1)
     389             :      * vps_reserved_0xffff_16bits   u(16)
     390             :      */
     391           1 :     skip_bits(gb, 17);
     392             : 
     393           1 :     hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1);
     394             : 
     395             :     /* nothing useful for hvcC past this point */
     396           1 :     return 0;
     397             : }
     398             : 
     399           0 : static void skip_scaling_list_data(GetBitContext *gb)
     400             : {
     401             :     int i, j, k, num_coeffs;
     402             : 
     403           0 :     for (i = 0; i < 4; i++)
     404           0 :         for (j = 0; j < (i == 3 ? 2 : 6); j++)
     405           0 :             if (!get_bits1(gb))         // scaling_list_pred_mode_flag[i][j]
     406           0 :                 get_ue_golomb_long(gb); // scaling_list_pred_matrix_id_delta[i][j]
     407             :             else {
     408           0 :                 num_coeffs = FFMIN(64, 1 << (4 + (i << 1)));
     409             : 
     410           0 :                 if (i > 1)
     411           0 :                     get_se_golomb_long(gb); // scaling_list_dc_coef_minus8[i-2][j]
     412             : 
     413           0 :                 for (k = 0; k < num_coeffs; k++)
     414           0 :                     get_se_golomb_long(gb); // scaling_list_delta_coef
     415             :             }
     416           0 : }
     417             : 
     418          11 : static int parse_rps(GetBitContext *gb, unsigned int rps_idx,
     419             :                      unsigned int num_rps,
     420             :                      unsigned int num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS])
     421             : {
     422             :     unsigned int i;
     423             : 
     424          20 :     if (rps_idx && get_bits1(gb)) { // inter_ref_pic_set_prediction_flag
     425             :         /* this should only happen for slice headers, and this isn't one */
     426           9 :         if (rps_idx >= num_rps)
     427           0 :             return AVERROR_INVALIDDATA;
     428             : 
     429           9 :         skip_bits1        (gb); // delta_rps_sign
     430           9 :         get_ue_golomb_long(gb); // abs_delta_rps_minus1
     431             : 
     432           9 :         num_delta_pocs[rps_idx] = 0;
     433             : 
     434             :         /*
     435             :          * From libavcodec/hevc_ps.c:
     436             :          *
     437             :          * if (is_slice_header) {
     438             :          *    //foo
     439             :          * } else
     440             :          *     rps_ridx = &sps->st_rps[rps - sps->st_rps - 1];
     441             :          *
     442             :          * where:
     443             :          * rps:             &sps->st_rps[rps_idx]
     444             :          * sps->st_rps:     &sps->st_rps[0]
     445             :          * is_slice_header: rps_idx == num_rps
     446             :          *
     447             :          * thus:
     448             :          * if (num_rps != rps_idx)
     449             :          *     rps_ridx = &sps->st_rps[rps_idx - 1];
     450             :          *
     451             :          * NumDeltaPocs[RefRpsIdx]: num_delta_pocs[rps_idx - 1]
     452             :          */
     453          48 :         for (i = 0; i <= num_delta_pocs[rps_idx - 1]; i++) {
     454          39 :             uint8_t use_delta_flag = 0;
     455          39 :             uint8_t used_by_curr_pic_flag = get_bits1(gb);
     456          39 :             if (!used_by_curr_pic_flag)
     457           7 :                 use_delta_flag = get_bits1(gb);
     458             : 
     459          39 :             if (used_by_curr_pic_flag || use_delta_flag)
     460          32 :                 num_delta_pocs[rps_idx]++;
     461             :         }
     462             :     } else {
     463           2 :         unsigned int num_negative_pics = get_ue_golomb_long(gb);
     464           2 :         unsigned int num_positive_pics = get_ue_golomb_long(gb);
     465             : 
     466           2 :         if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > get_bits_left(gb))
     467           0 :             return AVERROR_INVALIDDATA;
     468             : 
     469           2 :         num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics;
     470             : 
     471           7 :         for (i = 0; i < num_negative_pics; i++) {
     472           5 :             get_ue_golomb_long(gb); // delta_poc_s0_minus1[rps_idx]
     473           5 :             skip_bits1        (gb); // used_by_curr_pic_s0_flag[rps_idx]
     474             :         }
     475             : 
     476           2 :         for (i = 0; i < num_positive_pics; i++) {
     477           0 :             get_ue_golomb_long(gb); // delta_poc_s1_minus1[rps_idx]
     478           0 :             skip_bits1        (gb); // used_by_curr_pic_s1_flag[rps_idx]
     479             :         }
     480             :     }
     481             : 
     482          11 :     return 0;
     483             : }
     484             : 
     485           1 : static int hvcc_parse_sps(GetBitContext *gb,
     486             :                           HEVCDecoderConfigurationRecord *hvcc)
     487             : {
     488             :     unsigned int i, sps_max_sub_layers_minus1, log2_max_pic_order_cnt_lsb_minus4;
     489             :     unsigned int num_short_term_ref_pic_sets, num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS];
     490             : 
     491           1 :     skip_bits(gb, 4); // sps_video_parameter_set_id
     492             : 
     493           1 :     sps_max_sub_layers_minus1 = get_bits (gb, 3);
     494             : 
     495             :     /*
     496             :      * numTemporalLayers greater than 1 indicates that the stream to which this
     497             :      * configuration record applies is temporally scalable and the contained
     498             :      * number of temporal layers (also referred to as temporal sub-layer or
     499             :      * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
     500             :      * indicates that the stream is not temporally scalable. Value 0 indicates
     501             :      * that it is unknown whether the stream is temporally scalable.
     502             :      */
     503           1 :     hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
     504             :                                     sps_max_sub_layers_minus1 + 1);
     505             : 
     506           1 :     hvcc->temporalIdNested = get_bits1(gb);
     507             : 
     508           1 :     hvcc_parse_ptl(gb, hvcc, sps_max_sub_layers_minus1);
     509             : 
     510           1 :     get_ue_golomb_long(gb); // sps_seq_parameter_set_id
     511             : 
     512           1 :     hvcc->chromaFormat = get_ue_golomb_long(gb);
     513             : 
     514           1 :     if (hvcc->chromaFormat == 3)
     515           0 :         skip_bits1(gb); // separate_colour_plane_flag
     516             : 
     517           1 :     get_ue_golomb_long(gb); // pic_width_in_luma_samples
     518           1 :     get_ue_golomb_long(gb); // pic_height_in_luma_samples
     519             : 
     520           1 :     if (get_bits1(gb)) {        // conformance_window_flag
     521           1 :         get_ue_golomb_long(gb); // conf_win_left_offset
     522           1 :         get_ue_golomb_long(gb); // conf_win_right_offset
     523           1 :         get_ue_golomb_long(gb); // conf_win_top_offset
     524           1 :         get_ue_golomb_long(gb); // conf_win_bottom_offset
     525             :     }
     526             : 
     527           1 :     hvcc->bitDepthLumaMinus8          = get_ue_golomb_long(gb);
     528           1 :     hvcc->bitDepthChromaMinus8        = get_ue_golomb_long(gb);
     529           1 :     log2_max_pic_order_cnt_lsb_minus4 = get_ue_golomb_long(gb);
     530             : 
     531             :     /* sps_sub_layer_ordering_info_present_flag */
     532           1 :     i = get_bits1(gb) ? 0 : sps_max_sub_layers_minus1;
     533           2 :     for (; i <= sps_max_sub_layers_minus1; i++)
     534           1 :         skip_sub_layer_ordering_info(gb);
     535             : 
     536           1 :     get_ue_golomb_long(gb); // log2_min_luma_coding_block_size_minus3
     537           1 :     get_ue_golomb_long(gb); // log2_diff_max_min_luma_coding_block_size
     538           1 :     get_ue_golomb_long(gb); // log2_min_transform_block_size_minus2
     539           1 :     get_ue_golomb_long(gb); // log2_diff_max_min_transform_block_size
     540           1 :     get_ue_golomb_long(gb); // max_transform_hierarchy_depth_inter
     541           1 :     get_ue_golomb_long(gb); // max_transform_hierarchy_depth_intra
     542             : 
     543           1 :     if (get_bits1(gb) && // scaling_list_enabled_flag
     544           0 :         get_bits1(gb))   // sps_scaling_list_data_present_flag
     545           0 :         skip_scaling_list_data(gb);
     546             : 
     547           1 :     skip_bits1(gb); // amp_enabled_flag
     548           1 :     skip_bits1(gb); // sample_adaptive_offset_enabled_flag
     549             : 
     550           1 :     if (get_bits1(gb)) {           // pcm_enabled_flag
     551           0 :         skip_bits         (gb, 4); // pcm_sample_bit_depth_luma_minus1
     552           0 :         skip_bits         (gb, 4); // pcm_sample_bit_depth_chroma_minus1
     553           0 :         get_ue_golomb_long(gb);    // log2_min_pcm_luma_coding_block_size_minus3
     554           0 :         get_ue_golomb_long(gb);    // log2_diff_max_min_pcm_luma_coding_block_size
     555           0 :         skip_bits1        (gb);    // pcm_loop_filter_disabled_flag
     556             :     }
     557             : 
     558           1 :     num_short_term_ref_pic_sets = get_ue_golomb_long(gb);
     559           1 :     if (num_short_term_ref_pic_sets > HEVC_MAX_SHORT_TERM_REF_PIC_SETS)
     560           0 :         return AVERROR_INVALIDDATA;
     561             : 
     562          12 :     for (i = 0; i < num_short_term_ref_pic_sets; i++) {
     563          11 :         int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, num_delta_pocs);
     564          11 :         if (ret < 0)
     565           0 :             return ret;
     566             :     }
     567             : 
     568           1 :     if (get_bits1(gb)) {                               // long_term_ref_pics_present_flag
     569           0 :         unsigned num_long_term_ref_pics_sps = get_ue_golomb_long(gb);
     570           0 :         if (num_long_term_ref_pics_sps > 31U)
     571           0 :             return AVERROR_INVALIDDATA;
     572           0 :         for (i = 0; i < num_long_term_ref_pics_sps; i++) { // num_long_term_ref_pics_sps
     573           0 :             int len = FFMIN(log2_max_pic_order_cnt_lsb_minus4 + 4, 16);
     574           0 :             skip_bits (gb, len); // lt_ref_pic_poc_lsb_sps[i]
     575           0 :             skip_bits1(gb);      // used_by_curr_pic_lt_sps_flag[i]
     576             :         }
     577             :     }
     578             : 
     579           1 :     skip_bits1(gb); // sps_temporal_mvp_enabled_flag
     580           1 :     skip_bits1(gb); // strong_intra_smoothing_enabled_flag
     581             : 
     582           1 :     if (get_bits1(gb)) // vui_parameters_present_flag
     583           1 :         hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
     584             : 
     585             :     /* nothing useful for hvcC past this point */
     586           1 :     return 0;
     587             : }
     588             : 
     589           1 : static int hvcc_parse_pps(GetBitContext *gb,
     590             :                           HEVCDecoderConfigurationRecord *hvcc)
     591             : {
     592             :     uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
     593             : 
     594           1 :     get_ue_golomb_long(gb); // pps_pic_parameter_set_id
     595           1 :     get_ue_golomb_long(gb); // pps_seq_parameter_set_id
     596             : 
     597             :     /*
     598             :      * dependent_slice_segments_enabled_flag u(1)
     599             :      * output_flag_present_flag              u(1)
     600             :      * num_extra_slice_header_bits           u(3)
     601             :      * sign_data_hiding_enabled_flag         u(1)
     602             :      * cabac_init_present_flag               u(1)
     603             :      */
     604           1 :     skip_bits(gb, 7);
     605             : 
     606           1 :     get_ue_golomb_long(gb); // num_ref_idx_l0_default_active_minus1
     607           1 :     get_ue_golomb_long(gb); // num_ref_idx_l1_default_active_minus1
     608           1 :     get_se_golomb_long(gb); // init_qp_minus26
     609             : 
     610             :     /*
     611             :      * constrained_intra_pred_flag u(1)
     612             :      * transform_skip_enabled_flag u(1)
     613             :      */
     614           1 :     skip_bits(gb, 2);
     615             : 
     616           1 :     if (get_bits1(gb))          // cu_qp_delta_enabled_flag
     617           1 :         get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
     618             : 
     619           1 :     get_se_golomb_long(gb); // pps_cb_qp_offset
     620           1 :     get_se_golomb_long(gb); // pps_cr_qp_offset
     621             : 
     622             :     /*
     623             :      * pps_slice_chroma_qp_offsets_present_flag u(1)
     624             :      * weighted_pred_flag               u(1)
     625             :      * weighted_bipred_flag             u(1)
     626             :      * transquant_bypass_enabled_flag   u(1)
     627             :      */
     628           1 :     skip_bits(gb, 4);
     629             : 
     630           1 :     tiles_enabled_flag               = get_bits1(gb);
     631           1 :     entropy_coding_sync_enabled_flag = get_bits1(gb);
     632             : 
     633           1 :     if (entropy_coding_sync_enabled_flag && tiles_enabled_flag)
     634           0 :         hvcc->parallelismType = 0; // mixed-type parallel decoding
     635           1 :     else if (entropy_coding_sync_enabled_flag)
     636           1 :         hvcc->parallelismType = 3; // wavefront-based parallel decoding
     637           0 :     else if (tiles_enabled_flag)
     638           0 :         hvcc->parallelismType = 2; // tile-based parallel decoding
     639             :     else
     640           0 :         hvcc->parallelismType = 1; // slice-based parallel decoding
     641             : 
     642             :     /* nothing useful for hvcC past this point */
     643           1 :     return 0;
     644             : }
     645             : 
     646           3 : static uint8_t *nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len,
     647             :                                       uint32_t *dst_len)
     648             : {
     649             :     uint8_t *dst;
     650             :     uint32_t i, len;
     651             : 
     652           3 :     dst = av_malloc(src_len + AV_INPUT_BUFFER_PADDING_SIZE);
     653           3 :     if (!dst)
     654           0 :         return NULL;
     655             : 
     656             :     /* NAL unit header (2 bytes) */
     657           3 :     i = len = 0;
     658          12 :     while (i < 2 && i < src_len)
     659           6 :         dst[len++] = src[i++];
     660             : 
     661          61 :     while (i + 2 < src_len)
     662          55 :         if (!src[i] && !src[i + 1] && src[i + 2] == 3) {
     663           8 :             dst[len++] = src[i++];
     664           8 :             dst[len++] = src[i++];
     665           8 :             i++; // remove emulation_prevention_three_byte
     666             :         } else
     667          47 :             dst[len++] = src[i++];
     668             : 
     669          12 :     while (i < src_len)
     670           6 :         dst[len++] = src[i++];
     671             : 
     672           3 :     *dst_len = len;
     673           3 :     return dst;
     674             : }
     675             : 
     676             : 
     677             : 
     678           3 : static void nal_unit_parse_header(GetBitContext *gb, uint8_t *nal_type)
     679             : {
     680           3 :     skip_bits1(gb); // forbidden_zero_bit
     681             : 
     682           3 :     *nal_type = get_bits(gb, 6);
     683             : 
     684             :     /*
     685             :      * nuh_layer_id          u(6)
     686             :      * nuh_temporal_id_plus1 u(3)
     687             :      */
     688           3 :     skip_bits(gb, 9);
     689           3 : }
     690             : 
     691           3 : static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
     692             :                                    uint8_t nal_type, int ps_array_completeness,
     693             :                                    HEVCDecoderConfigurationRecord *hvcc)
     694             : {
     695             :     int ret;
     696             :     uint8_t index;
     697             :     uint16_t numNalus;
     698             :     HVCCNALUnitArray *array;
     699             : 
     700           6 :     for (index = 0; index < hvcc->numOfArrays; index++)
     701           3 :         if (hvcc->array[index].NAL_unit_type == nal_type)
     702           0 :             break;
     703             : 
     704           3 :     if (index >= hvcc->numOfArrays) {
     705             :         uint8_t i;
     706             : 
     707           3 :         ret = av_reallocp_array(&hvcc->array, index + 1, sizeof(HVCCNALUnitArray));
     708           3 :         if (ret < 0)
     709           0 :             return ret;
     710             : 
     711           6 :         for (i = hvcc->numOfArrays; i <= index; i++)
     712           3 :             memset(&hvcc->array[i], 0, sizeof(HVCCNALUnitArray));
     713           3 :         hvcc->numOfArrays = index + 1;
     714             :     }
     715             : 
     716           3 :     array    = &hvcc->array[index];
     717           3 :     numNalus = array->numNalus;
     718             : 
     719           3 :     ret = av_reallocp_array(&array->nalUnit, numNalus + 1, sizeof(uint8_t*));
     720           3 :     if (ret < 0)
     721           0 :         return ret;
     722             : 
     723           3 :     ret = av_reallocp_array(&array->nalUnitLength, numNalus + 1, sizeof(uint16_t));
     724           3 :     if (ret < 0)
     725           0 :         return ret;
     726             : 
     727           3 :     array->nalUnit      [numNalus] = nal_buf;
     728           3 :     array->nalUnitLength[numNalus] = nal_size;
     729           3 :     array->NAL_unit_type           = nal_type;
     730           3 :     array->numNalus++;
     731             : 
     732             :     /*
     733             :      * When the sample entry name is ‘hvc1’, the default and mandatory value of
     734             :      * array_completeness is 1 for arrays of all types of parameter sets, and 0
     735             :      * for all other arrays. When the sample entry name is ‘hev1’, the default
     736             :      * value of array_completeness is 0 for all arrays.
     737             :      */
     738           3 :     if (nal_type == HEVC_NAL_VPS || nal_type == HEVC_NAL_SPS || nal_type == HEVC_NAL_PPS)
     739           3 :         array->array_completeness = ps_array_completeness;
     740             : 
     741           3 :     return 0;
     742             : }
     743             : 
     744           3 : static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
     745             :                              int ps_array_completeness,
     746             :                              HEVCDecoderConfigurationRecord *hvcc)
     747             : {
     748           3 :     int ret = 0;
     749             :     GetBitContext gbc;
     750             :     uint8_t nal_type;
     751             :     uint8_t *rbsp_buf;
     752             :     uint32_t rbsp_size;
     753             : 
     754           3 :     rbsp_buf = nal_unit_extract_rbsp(nal_buf, nal_size, &rbsp_size);
     755           3 :     if (!rbsp_buf) {
     756           0 :         ret = AVERROR(ENOMEM);
     757           0 :         goto end;
     758             :     }
     759             : 
     760           3 :     ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
     761           3 :     if (ret < 0)
     762           0 :         goto end;
     763             : 
     764           3 :     nal_unit_parse_header(&gbc, &nal_type);
     765             : 
     766             :     /*
     767             :      * Note: only 'declarative' SEI messages are allowed in
     768             :      * hvcC. Perhaps the SEI playload type should be checked
     769             :      * and non-declarative SEI messages discarded?
     770             :      */
     771           3 :     switch (nal_type) {
     772           3 :     case HEVC_NAL_VPS:
     773             :     case HEVC_NAL_SPS:
     774             :     case HEVC_NAL_PPS:
     775             :     case HEVC_NAL_SEI_PREFIX:
     776             :     case HEVC_NAL_SEI_SUFFIX:
     777           3 :         ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type,
     778             :                                       ps_array_completeness, hvcc);
     779           3 :         if (ret < 0)
     780           0 :             goto end;
     781           3 :         else if (nal_type == HEVC_NAL_VPS)
     782           1 :             ret = hvcc_parse_vps(&gbc, hvcc);
     783           2 :         else if (nal_type == HEVC_NAL_SPS)
     784           1 :             ret = hvcc_parse_sps(&gbc, hvcc);
     785           1 :         else if (nal_type == HEVC_NAL_PPS)
     786           1 :             ret = hvcc_parse_pps(&gbc, hvcc);
     787           3 :         if (ret < 0)
     788           0 :             goto end;
     789           3 :         break;
     790           0 :     default:
     791           0 :         ret = AVERROR_INVALIDDATA;
     792           0 :         goto end;
     793             :     }
     794             : 
     795           3 : end:
     796           3 :     av_free(rbsp_buf);
     797           3 :     return ret;
     798             : }
     799             : 
     800           1 : static void hvcc_init(HEVCDecoderConfigurationRecord *hvcc)
     801             : {
     802           1 :     memset(hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
     803           1 :     hvcc->configurationVersion = 1;
     804           1 :     hvcc->lengthSizeMinusOne   = 3; // 4 bytes
     805             : 
     806             :     /*
     807             :      * The following fields have all their valid bits set by default,
     808             :      * the ProfileTierLevel parsing code will unset them when needed.
     809             :      */
     810           1 :     hvcc->general_profile_compatibility_flags = 0xffffffff;
     811           1 :     hvcc->general_constraint_indicator_flags  = 0xffffffffffff;
     812             : 
     813             :     /*
     814             :      * Initialize this field with an invalid value which can be used to detect
     815             :      * whether we didn't see any VUI (in which case it should be reset to zero).
     816             :      */
     817           1 :     hvcc->min_spatial_segmentation_idc = MAX_SPATIAL_SEGMENTATION + 1;
     818           1 : }
     819             : 
     820           1 : static void hvcc_close(HEVCDecoderConfigurationRecord *hvcc)
     821             : {
     822             :     uint8_t i;
     823             : 
     824           4 :     for (i = 0; i < hvcc->numOfArrays; i++) {
     825           3 :         hvcc->array[i].numNalus = 0;
     826           3 :         av_freep(&hvcc->array[i].nalUnit);
     827           3 :         av_freep(&hvcc->array[i].nalUnitLength);
     828             :     }
     829             : 
     830           1 :     hvcc->numOfArrays = 0;
     831           1 :     av_freep(&hvcc->array);
     832           1 : }
     833             : 
     834           1 : static int hvcc_write(AVIOContext *pb, HEVCDecoderConfigurationRecord *hvcc)
     835             : {
     836             :     uint8_t i;
     837           1 :     uint16_t j, vps_count = 0, sps_count = 0, pps_count = 0;
     838             : 
     839             :     /*
     840             :      * We only support writing HEVCDecoderConfigurationRecord version 1.
     841             :      */
     842           1 :     hvcc->configurationVersion = 1;
     843             : 
     844             :     /*
     845             :      * If min_spatial_segmentation_idc is invalid, reset to 0 (unspecified).
     846             :      */
     847           1 :     if (hvcc->min_spatial_segmentation_idc > MAX_SPATIAL_SEGMENTATION)
     848           1 :         hvcc->min_spatial_segmentation_idc = 0;
     849             : 
     850             :     /*
     851             :      * parallelismType indicates the type of parallelism that is used to meet
     852             :      * the restrictions imposed by min_spatial_segmentation_idc when the value
     853             :      * of min_spatial_segmentation_idc is greater than 0.
     854             :      */
     855           1 :     if (!hvcc->min_spatial_segmentation_idc)
     856           1 :         hvcc->parallelismType = 0;
     857             : 
     858             :     /*
     859             :      * It's unclear how to properly compute these fields, so
     860             :      * let's always set them to values meaning 'unspecified'.
     861             :      */
     862           1 :     hvcc->avgFrameRate      = 0;
     863           1 :     hvcc->constantFrameRate = 0;
     864             : 
     865           1 :     av_log(NULL, AV_LOG_TRACE,  "configurationVersion:                %"PRIu8"\n",
     866           1 :             hvcc->configurationVersion);
     867           1 :     av_log(NULL, AV_LOG_TRACE,  "general_profile_space:               %"PRIu8"\n",
     868           1 :             hvcc->general_profile_space);
     869           1 :     av_log(NULL, AV_LOG_TRACE,  "general_tier_flag:                   %"PRIu8"\n",
     870           1 :             hvcc->general_tier_flag);
     871           1 :     av_log(NULL, AV_LOG_TRACE,  "general_profile_idc:                 %"PRIu8"\n",
     872           1 :             hvcc->general_profile_idc);
     873           1 :     av_log(NULL, AV_LOG_TRACE, "general_profile_compatibility_flags: 0x%08"PRIx32"\n",
     874             :             hvcc->general_profile_compatibility_flags);
     875           1 :     av_log(NULL, AV_LOG_TRACE, "general_constraint_indicator_flags:  0x%012"PRIx64"\n",
     876             :             hvcc->general_constraint_indicator_flags);
     877           1 :     av_log(NULL, AV_LOG_TRACE,  "general_level_idc:                   %"PRIu8"\n",
     878           1 :             hvcc->general_level_idc);
     879           1 :     av_log(NULL, AV_LOG_TRACE,  "min_spatial_segmentation_idc:        %"PRIu16"\n",
     880           1 :             hvcc->min_spatial_segmentation_idc);
     881           1 :     av_log(NULL, AV_LOG_TRACE,  "parallelismType:                     %"PRIu8"\n",
     882           1 :             hvcc->parallelismType);
     883           1 :     av_log(NULL, AV_LOG_TRACE,  "chromaFormat:                        %"PRIu8"\n",
     884           1 :             hvcc->chromaFormat);
     885           1 :     av_log(NULL, AV_LOG_TRACE,  "bitDepthLumaMinus8:                  %"PRIu8"\n",
     886           1 :             hvcc->bitDepthLumaMinus8);
     887           1 :     av_log(NULL, AV_LOG_TRACE,  "bitDepthChromaMinus8:                %"PRIu8"\n",
     888           1 :             hvcc->bitDepthChromaMinus8);
     889           1 :     av_log(NULL, AV_LOG_TRACE,  "avgFrameRate:                        %"PRIu16"\n",
     890           1 :             hvcc->avgFrameRate);
     891           1 :     av_log(NULL, AV_LOG_TRACE,  "constantFrameRate:                   %"PRIu8"\n",
     892           1 :             hvcc->constantFrameRate);
     893           1 :     av_log(NULL, AV_LOG_TRACE,  "numTemporalLayers:                   %"PRIu8"\n",
     894           1 :             hvcc->numTemporalLayers);
     895           1 :     av_log(NULL, AV_LOG_TRACE,  "temporalIdNested:                    %"PRIu8"\n",
     896           1 :             hvcc->temporalIdNested);
     897           1 :     av_log(NULL, AV_LOG_TRACE,  "lengthSizeMinusOne:                  %"PRIu8"\n",
     898           1 :             hvcc->lengthSizeMinusOne);
     899           1 :     av_log(NULL, AV_LOG_TRACE,  "numOfArrays:                         %"PRIu8"\n",
     900           1 :             hvcc->numOfArrays);
     901           4 :     for (i = 0; i < hvcc->numOfArrays; i++) {
     902           3 :         av_log(NULL, AV_LOG_TRACE, "array_completeness[%"PRIu8"]:               %"PRIu8"\n",
     903           3 :                 i, hvcc->array[i].array_completeness);
     904           3 :         av_log(NULL, AV_LOG_TRACE, "NAL_unit_type[%"PRIu8"]:                    %"PRIu8"\n",
     905           3 :                 i, hvcc->array[i].NAL_unit_type);
     906           3 :         av_log(NULL, AV_LOG_TRACE, "numNalus[%"PRIu8"]:                         %"PRIu16"\n",
     907           3 :                 i, hvcc->array[i].numNalus);
     908           6 :         for (j = 0; j < hvcc->array[i].numNalus; j++)
     909           3 :             av_log(NULL, AV_LOG_TRACE,
     910             :                     "nalUnitLength[%"PRIu8"][%"PRIu16"]:                 %"PRIu16"\n",
     911           3 :                     i, j, hvcc->array[i].nalUnitLength[j]);
     912             :     }
     913             : 
     914             :     /*
     915             :      * We need at least one of each: VPS, SPS and PPS.
     916             :      */
     917           4 :     for (i = 0; i < hvcc->numOfArrays; i++)
     918           3 :         switch (hvcc->array[i].NAL_unit_type) {
     919           1 :         case HEVC_NAL_VPS:
     920           1 :             vps_count += hvcc->array[i].numNalus;
     921           1 :             break;
     922           1 :         case HEVC_NAL_SPS:
     923           1 :             sps_count += hvcc->array[i].numNalus;
     924           1 :             break;
     925           1 :         case HEVC_NAL_PPS:
     926           1 :             pps_count += hvcc->array[i].numNalus;
     927           1 :             break;
     928           0 :         default:
     929           0 :             break;
     930             :         }
     931           1 :     if (!vps_count || vps_count > HEVC_MAX_VPS_COUNT ||
     932           1 :         !sps_count || sps_count > HEVC_MAX_SPS_COUNT ||
     933           1 :         !pps_count || pps_count > HEVC_MAX_PPS_COUNT)
     934           0 :         return AVERROR_INVALIDDATA;
     935             : 
     936             :     /* unsigned int(8) configurationVersion = 1; */
     937           1 :     avio_w8(pb, hvcc->configurationVersion);
     938             : 
     939             :     /*
     940             :      * unsigned int(2) general_profile_space;
     941             :      * unsigned int(1) general_tier_flag;
     942             :      * unsigned int(5) general_profile_idc;
     943             :      */
     944           3 :     avio_w8(pb, hvcc->general_profile_space << 6 |
     945           1 :                 hvcc->general_tier_flag     << 5 |
     946           1 :                 hvcc->general_profile_idc);
     947             : 
     948             :     /* unsigned int(32) general_profile_compatibility_flags; */
     949           1 :     avio_wb32(pb, hvcc->general_profile_compatibility_flags);
     950             : 
     951             :     /* unsigned int(48) general_constraint_indicator_flags; */
     952           1 :     avio_wb32(pb, hvcc->general_constraint_indicator_flags >> 16);
     953           1 :     avio_wb16(pb, hvcc->general_constraint_indicator_flags);
     954             : 
     955             :     /* unsigned int(8) general_level_idc; */
     956           1 :     avio_w8(pb, hvcc->general_level_idc);
     957             : 
     958             :     /*
     959             :      * bit(4) reserved = ‘1111’b;
     960             :      * unsigned int(12) min_spatial_segmentation_idc;
     961             :      */
     962           1 :     avio_wb16(pb, hvcc->min_spatial_segmentation_idc | 0xf000);
     963             : 
     964             :     /*
     965             :      * bit(6) reserved = ‘111111’b;
     966             :      * unsigned int(2) parallelismType;
     967             :      */
     968           1 :     avio_w8(pb, hvcc->parallelismType | 0xfc);
     969             : 
     970             :     /*
     971             :      * bit(6) reserved = ‘111111’b;
     972             :      * unsigned int(2) chromaFormat;
     973             :      */
     974           1 :     avio_w8(pb, hvcc->chromaFormat | 0xfc);
     975             : 
     976             :     /*
     977             :      * bit(5) reserved = ‘11111’b;
     978             :      * unsigned int(3) bitDepthLumaMinus8;
     979             :      */
     980           1 :     avio_w8(pb, hvcc->bitDepthLumaMinus8 | 0xf8);
     981             : 
     982             :     /*
     983             :      * bit(5) reserved = ‘11111’b;
     984             :      * unsigned int(3) bitDepthChromaMinus8;
     985             :      */
     986           1 :     avio_w8(pb, hvcc->bitDepthChromaMinus8 | 0xf8);
     987             : 
     988             :     /* bit(16) avgFrameRate; */
     989           1 :     avio_wb16(pb, hvcc->avgFrameRate);
     990             : 
     991             :     /*
     992             :      * bit(2) constantFrameRate;
     993             :      * bit(3) numTemporalLayers;
     994             :      * bit(1) temporalIdNested;
     995             :      * unsigned int(2) lengthSizeMinusOne;
     996             :      */
     997           3 :     avio_w8(pb, hvcc->constantFrameRate << 6 |
     998           2 :                 hvcc->numTemporalLayers << 3 |
     999           1 :                 hvcc->temporalIdNested  << 2 |
    1000           1 :                 hvcc->lengthSizeMinusOne);
    1001             : 
    1002             :     /* unsigned int(8) numOfArrays; */
    1003           1 :     avio_w8(pb, hvcc->numOfArrays);
    1004             : 
    1005           4 :     for (i = 0; i < hvcc->numOfArrays; i++) {
    1006             :         /*
    1007             :          * bit(1) array_completeness;
    1008             :          * unsigned int(1) reserved = 0;
    1009             :          * unsigned int(6) NAL_unit_type;
    1010             :          */
    1011           6 :         avio_w8(pb, hvcc->array[i].array_completeness << 7 |
    1012           3 :                     hvcc->array[i].NAL_unit_type & 0x3f);
    1013             : 
    1014             :         /* unsigned int(16) numNalus; */
    1015           3 :         avio_wb16(pb, hvcc->array[i].numNalus);
    1016             : 
    1017           6 :         for (j = 0; j < hvcc->array[i].numNalus; j++) {
    1018             :             /* unsigned int(16) nalUnitLength; */
    1019           3 :             avio_wb16(pb, hvcc->array[i].nalUnitLength[j]);
    1020             : 
    1021             :             /* bit(8*nalUnitLength) nalUnit; */
    1022           3 :             avio_write(pb, hvcc->array[i].nalUnit[j],
    1023           3 :                        hvcc->array[i].nalUnitLength[j]);
    1024             :         }
    1025             :     }
    1026             : 
    1027           1 :     return 0;
    1028             : }
    1029             : 
    1030          48 : int ff_hevc_annexb2mp4(AVIOContext *pb, const uint8_t *buf_in,
    1031             :                        int size, int filter_ps, int *ps_count)
    1032             : {
    1033          48 :     int num_ps = 0, ret = 0;
    1034          48 :     uint8_t *buf, *end, *start = NULL;
    1035             : 
    1036          48 :     if (!filter_ps) {
    1037          48 :         ret = ff_avc_parse_nal_units(pb, buf_in, size);
    1038          48 :         goto end;
    1039             :     }
    1040             : 
    1041           0 :     ret = ff_avc_parse_nal_units_buf(buf_in, &start, &size);
    1042           0 :     if (ret < 0)
    1043           0 :         goto end;
    1044             : 
    1045           0 :     ret = 0;
    1046           0 :     buf = start;
    1047           0 :     end = start + size;
    1048             : 
    1049           0 :     while (end - buf > 4) {
    1050           0 :         uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
    1051           0 :         uint8_t type = (buf[4] >> 1) & 0x3f;
    1052             : 
    1053           0 :         buf += 4;
    1054             : 
    1055           0 :         switch (type) {
    1056           0 :         case HEVC_NAL_VPS:
    1057             :         case HEVC_NAL_SPS:
    1058             :         case HEVC_NAL_PPS:
    1059           0 :             num_ps++;
    1060           0 :             break;
    1061           0 :         default:
    1062           0 :             ret += 4 + len;
    1063           0 :             avio_wb32(pb, len);
    1064           0 :             avio_write(pb, buf, len);
    1065           0 :             break;
    1066             :         }
    1067             : 
    1068           0 :         buf += len;
    1069             :     }
    1070             : 
    1071           0 : end:
    1072          48 :     av_free(start);
    1073          48 :     if (ps_count)
    1074           0 :         *ps_count = num_ps;
    1075          48 :     return ret;
    1076             : }
    1077             : 
    1078           0 : int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out,
    1079             :                            int *size, int filter_ps, int *ps_count)
    1080             : {
    1081             :     AVIOContext *pb;
    1082             :     int ret;
    1083             : 
    1084           0 :     ret = avio_open_dyn_buf(&pb);
    1085           0 :     if (ret < 0)
    1086           0 :         return ret;
    1087             : 
    1088           0 :     ret   = ff_hevc_annexb2mp4(pb, buf_in, *size, filter_ps, ps_count);
    1089           0 :     *size = avio_close_dyn_buf(pb, buf_out);
    1090             : 
    1091           0 :     return ret;
    1092             : }
    1093             : 
    1094           1 : int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data,
    1095             :                        int size, int ps_array_completeness)
    1096             : {
    1097           1 :     int ret = 0;
    1098           1 :     uint8_t *buf, *end, *start = NULL;
    1099             :     HEVCDecoderConfigurationRecord hvcc;
    1100             : 
    1101           1 :     hvcc_init(&hvcc);
    1102             : 
    1103           1 :     if (size < 6) {
    1104             :         /* We can't write a valid hvcC from the provided data */
    1105           0 :         ret = AVERROR_INVALIDDATA;
    1106           0 :         goto end;
    1107           1 :     } else if (*data == 1) {
    1108             :         /* Data is already hvcC-formatted */
    1109           0 :         avio_write(pb, data, size);
    1110           0 :         goto end;
    1111           1 :     } else if (!(AV_RB24(data) == 1 || AV_RB32(data) == 1)) {
    1112             :         /* Not a valid Annex B start code prefix */
    1113           0 :         ret = AVERROR_INVALIDDATA;
    1114           0 :         goto end;
    1115             :     }
    1116             : 
    1117           1 :     ret = ff_avc_parse_nal_units_buf(data, &start, &size);
    1118           1 :     if (ret < 0)
    1119           0 :         goto end;
    1120             : 
    1121           1 :     buf = start;
    1122           1 :     end = start + size;
    1123             : 
    1124           5 :     while (end - buf > 4) {
    1125           3 :         uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
    1126           3 :         uint8_t type = (buf[4] >> 1) & 0x3f;
    1127             : 
    1128           3 :         buf += 4;
    1129             : 
    1130           3 :         switch (type) {
    1131           3 :         case HEVC_NAL_VPS:
    1132             :         case HEVC_NAL_SPS:
    1133             :         case HEVC_NAL_PPS:
    1134             :         case HEVC_NAL_SEI_PREFIX:
    1135             :         case HEVC_NAL_SEI_SUFFIX:
    1136           3 :             ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc);
    1137           3 :             if (ret < 0)
    1138           0 :                 goto end;
    1139           3 :             break;
    1140           0 :         default:
    1141           0 :             break;
    1142             :         }
    1143             : 
    1144           3 :         buf += len;
    1145             :     }
    1146             : 
    1147           1 :     ret = hvcc_write(pb, &hvcc);
    1148             : 
    1149           1 : end:
    1150           1 :     hvcc_close(&hvcc);
    1151           1 :     av_free(start);
    1152           1 :     return ret;
    1153             : }

Generated by: LCOV version 1.13