2 * Copyright (c) 2014 Tim Walker <tdskywalker@gmail.com>
4 * This file is part of FFmpeg.
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.
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.
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
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"
30 #define MAX_SPATIAL_SEGMENTATION 4096 // max. value of u(12) field
32 typedef struct HVCCNALUnitArray {
33 uint8_t array_completeness;
34 uint8_t NAL_unit_type;
36 uint16_t *nalUnitLength;
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;
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;
59 HVCCNALUnitArray *array;
60 } HEVCDecoderConfigurationRecord;
62 typedef struct HVCCProfileTierLevel {
63 uint8_t profile_space;
66 uint32_t profile_compatibility_flags;
67 uint64_t constraint_indicator_flags;
69 } HVCCProfileTierLevel;
71 static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc,
72 HVCCProfileTierLevel *ptl)
75 * The value of general_profile_space in all the parameter sets must be
78 hvcc->general_profile_space = ptl->profile_space;
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.
85 if (hvcc->general_tier_flag < ptl->tier_flag)
86 hvcc->general_level_idc = ptl->level_idc;
88 hvcc->general_level_idc = FFMAX(hvcc->general_level_idc, ptl->level_idc);
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.
94 hvcc->general_tier_flag = FFMAX(hvcc->general_tier_flag, ptl->tier_flag);
97 * The profile indication general_profile_idc must indicate a profile to
98 * which the stream associated with this configuration record conforms.
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
108 * Note: set the profile to the highest value for the sake of simplicity.
110 hvcc->general_profile_idc = FFMAX(hvcc->general_profile_idc, ptl->profile_idc);
113 * Each bit in general_profile_compatibility_flags may only be set if all
114 * the parameter sets set that bit.
116 hvcc->general_profile_compatibility_flags &= ptl->profile_compatibility_flags;
119 * Each bit in general_constraint_indicator_flags may only be set if all
120 * the parameter sets set that bit.
122 hvcc->general_constraint_indicator_flags &= ptl->constraint_indicator_flags;
125 static void hvcc_parse_ptl(GetBitContext *gb,
126 HEVCDecoderConfigurationRecord *hvcc,
127 unsigned int max_sub_layers_minus1)
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];
134 general_ptl.profile_space = get_bits(gb, 2);
135 general_ptl.tier_flag = get_bits1(gb);
136 general_ptl.profile_idc = get_bits(gb, 5);
137 general_ptl.profile_compatibility_flags = get_bits_long(gb, 32);
138 general_ptl.constraint_indicator_flags = get_bits64(gb, 48);
139 general_ptl.level_idc = get_bits(gb, 8);
140 hvcc_update_ptl(hvcc, &general_ptl);
142 for (i = 0; i < max_sub_layers_minus1; i++) {
143 sub_layer_profile_present_flag[i] = get_bits1(gb);
144 sub_layer_level_present_flag[i] = get_bits1(gb);
147 if (max_sub_layers_minus1 > 0)
148 for (i = max_sub_layers_minus1; i < 8; i++)
149 skip_bits(gb, 2); // reserved_zero_2bits[i]
151 for (i = 0; i < max_sub_layers_minus1; i++) {
152 if (sub_layer_profile_present_flag[i]) {
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)
164 skip_bits_long(gb, 32);
165 skip_bits_long(gb, 32);
169 if (sub_layer_level_present_flag[i])
174 static void skip_sub_layer_hrd_parameters(GetBitContext *gb,
175 unsigned int cpb_cnt_minus1,
176 uint8_t sub_pic_hrd_params_present_flag)
180 for (i = 0; i <= cpb_cnt_minus1; i++) {
181 get_ue_golomb_long(gb); // bit_rate_value_minus1
182 get_ue_golomb_long(gb); // cpb_size_value_minus1
184 if (sub_pic_hrd_params_present_flag) {
185 get_ue_golomb_long(gb); // cpb_size_du_value_minus1
186 get_ue_golomb_long(gb); // bit_rate_du_value_minus1
189 skip_bits1(gb); // cbr_flag
193 static int skip_hrd_parameters(GetBitContext *gb, uint8_t cprms_present_flag,
194 unsigned int max_sub_layers_minus1)
197 uint8_t sub_pic_hrd_params_present_flag = 0;
198 uint8_t nal_hrd_parameters_present_flag = 0;
199 uint8_t vcl_hrd_parameters_present_flag = 0;
201 if (cprms_present_flag) {
202 nal_hrd_parameters_present_flag = get_bits1(gb);
203 vcl_hrd_parameters_present_flag = get_bits1(gb);
205 if (nal_hrd_parameters_present_flag ||
206 vcl_hrd_parameters_present_flag) {
207 sub_pic_hrd_params_present_flag = get_bits1(gb);
209 if (sub_pic_hrd_params_present_flag)
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)
219 * bit_rate_scale u(4)
220 * cpb_size_scale u(4)
224 if (sub_pic_hrd_params_present_flag)
225 skip_bits(gb, 4); // cpb_size_du_scale
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)
236 for (i = 0; i <= max_sub_layers_minus1; i++) {
237 unsigned int cpb_cnt_minus1 = 0;
238 uint8_t low_delay_hrd_flag = 0;
239 uint8_t fixed_pic_rate_within_cvs_flag = 0;
240 uint8_t fixed_pic_rate_general_flag = get_bits1(gb);
242 if (!fixed_pic_rate_general_flag)
243 fixed_pic_rate_within_cvs_flag = get_bits1(gb);
245 if (fixed_pic_rate_within_cvs_flag)
246 get_ue_golomb_long(gb); // elemental_duration_in_tc_minus1
248 low_delay_hrd_flag = get_bits1(gb);
250 if (!low_delay_hrd_flag) {
251 cpb_cnt_minus1 = get_ue_golomb_long(gb);
252 if (cpb_cnt_minus1 > 31)
253 return AVERROR_INVALIDDATA;
256 if (nal_hrd_parameters_present_flag)
257 skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
258 sub_pic_hrd_params_present_flag);
260 if (vcl_hrd_parameters_present_flag)
261 skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
262 sub_pic_hrd_params_present_flag);
268 static void skip_timing_info(GetBitContext *gb)
270 skip_bits_long(gb, 32); // num_units_in_tick
271 skip_bits_long(gb, 32); // time_scale
273 if (get_bits1(gb)) // poc_proportional_to_timing_flag
274 get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1
277 static void hvcc_parse_vui(GetBitContext *gb,
278 HEVCDecoderConfigurationRecord *hvcc,
279 unsigned int max_sub_layers_minus1)
281 unsigned int min_spatial_segmentation_idc;
283 if (get_bits1(gb)) // aspect_ratio_info_present_flag
284 if (get_bits(gb, 8) == 255) // aspect_ratio_idc
285 skip_bits_long(gb, 32); // sar_width u(16), sar_height u(16)
287 if (get_bits1(gb)) // overscan_info_present_flag
288 skip_bits1(gb); // overscan_appropriate_flag
290 if (get_bits1(gb)) { // video_signal_type_present_flag
291 skip_bits(gb, 4); // video_format u(3), video_full_range_flag u(1)
293 if (get_bits1(gb)) // colour_description_present_flag
295 * colour_primaries u(8)
296 * transfer_characteristics u(8)
302 if (get_bits1(gb)) { // chroma_loc_info_present_flag
303 get_ue_golomb_long(gb); // chroma_sample_loc_type_top_field
304 get_ue_golomb_long(gb); // chroma_sample_loc_type_bottom_field
308 * neutral_chroma_indication_flag u(1)
309 * field_seq_flag u(1)
310 * frame_field_info_present_flag u(1)
314 if (get_bits1(gb)) { // default_display_window_flag
315 get_ue_golomb_long(gb); // def_disp_win_left_offset
316 get_ue_golomb_long(gb); // def_disp_win_right_offset
317 get_ue_golomb_long(gb); // def_disp_win_top_offset
318 get_ue_golomb_long(gb); // def_disp_win_bottom_offset
321 if (get_bits1(gb)) { // vui_timing_info_present_flag
322 skip_timing_info(gb);
324 if (get_bits1(gb)) // vui_hrd_parameters_present_flag
325 skip_hrd_parameters(gb, 1, max_sub_layers_minus1);
328 if (get_bits1(gb)) { // bitstream_restriction_flag
330 * tiles_fixed_structure_flag u(1)
331 * motion_vectors_over_pic_boundaries_flag u(1)
332 * restricted_ref_pic_lists_flag u(1)
336 min_spatial_segmentation_idc = get_ue_golomb_long(gb);
339 * unsigned int(12) min_spatial_segmentation_idc;
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.
345 hvcc->min_spatial_segmentation_idc = FFMIN(hvcc->min_spatial_segmentation_idc,
346 min_spatial_segmentation_idc);
348 get_ue_golomb_long(gb); // max_bytes_per_pic_denom
349 get_ue_golomb_long(gb); // max_bits_per_min_cu_denom
350 get_ue_golomb_long(gb); // log2_max_mv_length_horizontal
351 get_ue_golomb_long(gb); // log2_max_mv_length_vertical
355 static void skip_sub_layer_ordering_info(GetBitContext *gb)
357 get_ue_golomb_long(gb); // max_dec_pic_buffering_minus1
358 get_ue_golomb_long(gb); // max_num_reorder_pics
359 get_ue_golomb_long(gb); // max_latency_increase_plus1
362 static int hvcc_parse_vps(GetBitContext *gb,
363 HEVCDecoderConfigurationRecord *hvcc)
365 unsigned int vps_max_sub_layers_minus1;
368 * vps_video_parameter_set_id u(4)
369 * vps_reserved_three_2bits u(2)
370 * vps_max_layers_minus1 u(6)
374 vps_max_sub_layers_minus1 = get_bits(gb, 3);
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.
384 hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
385 vps_max_sub_layers_minus1 + 1);
388 * vps_temporal_id_nesting_flag u(1)
389 * vps_reserved_0xffff_16bits u(16)
393 hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1);
395 /* nothing useful for hvcC past this point */
399 static void skip_scaling_list_data(GetBitContext *gb)
401 int i, j, k, num_coeffs;
403 for (i = 0; i < 4; i++)
404 for (j = 0; j < (i == 3 ? 2 : 6); j++)
405 if (!get_bits1(gb)) // scaling_list_pred_mode_flag[i][j]
406 get_ue_golomb_long(gb); // scaling_list_pred_matrix_id_delta[i][j]
408 num_coeffs = FFMIN(64, 1 << (4 + (i << 1)));
411 get_se_golomb_long(gb); // scaling_list_dc_coef_minus8[i-2][j]
413 for (k = 0; k < num_coeffs; k++)
414 get_se_golomb_long(gb); // scaling_list_delta_coef
418 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])
424 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 if (rps_idx >= num_rps)
427 return AVERROR_INVALIDDATA;
429 skip_bits1 (gb); // delta_rps_sign
430 get_ue_golomb_long(gb); // abs_delta_rps_minus1
432 num_delta_pocs[rps_idx] = 0;
435 * From libavcodec/hevc_ps.c:
437 * if (is_slice_header) {
440 * rps_ridx = &sps->st_rps[rps - sps->st_rps - 1];
443 * rps: &sps->st_rps[rps_idx]
444 * sps->st_rps: &sps->st_rps[0]
445 * is_slice_header: rps_idx == num_rps
448 * if (num_rps != rps_idx)
449 * rps_ridx = &sps->st_rps[rps_idx - 1];
451 * NumDeltaPocs[RefRpsIdx]: num_delta_pocs[rps_idx - 1]
453 for (i = 0; i <= num_delta_pocs[rps_idx - 1]; i++) {
454 uint8_t use_delta_flag = 0;
455 uint8_t used_by_curr_pic_flag = get_bits1(gb);
456 if (!used_by_curr_pic_flag)
457 use_delta_flag = get_bits1(gb);
459 if (used_by_curr_pic_flag || use_delta_flag)
460 num_delta_pocs[rps_idx]++;
463 unsigned int num_negative_pics = get_ue_golomb_long(gb);
464 unsigned int num_positive_pics = get_ue_golomb_long(gb);
466 if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > get_bits_left(gb))
467 return AVERROR_INVALIDDATA;
469 num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics;
471 for (i = 0; i < num_negative_pics; i++) {
472 get_ue_golomb_long(gb); // delta_poc_s0_minus1[rps_idx]
473 skip_bits1 (gb); // used_by_curr_pic_s0_flag[rps_idx]
476 for (i = 0; i < num_positive_pics; i++) {
477 get_ue_golomb_long(gb); // delta_poc_s1_minus1[rps_idx]
478 skip_bits1 (gb); // used_by_curr_pic_s1_flag[rps_idx]
485 static int hvcc_parse_sps(GetBitContext *gb,
486 HEVCDecoderConfigurationRecord *hvcc)
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];
491 skip_bits(gb, 4); // sps_video_parameter_set_id
493 sps_max_sub_layers_minus1 = get_bits (gb, 3);
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.
503 hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
504 sps_max_sub_layers_minus1 + 1);
506 hvcc->temporalIdNested = get_bits1(gb);
508 hvcc_parse_ptl(gb, hvcc, sps_max_sub_layers_minus1);
510 get_ue_golomb_long(gb); // sps_seq_parameter_set_id
512 hvcc->chromaFormat = get_ue_golomb_long(gb);
514 if (hvcc->chromaFormat == 3)
515 skip_bits1(gb); // separate_colour_plane_flag
517 get_ue_golomb_long(gb); // pic_width_in_luma_samples
518 get_ue_golomb_long(gb); // pic_height_in_luma_samples
520 if (get_bits1(gb)) { // conformance_window_flag
521 get_ue_golomb_long(gb); // conf_win_left_offset
522 get_ue_golomb_long(gb); // conf_win_right_offset
523 get_ue_golomb_long(gb); // conf_win_top_offset
524 get_ue_golomb_long(gb); // conf_win_bottom_offset
527 hvcc->bitDepthLumaMinus8 = get_ue_golomb_long(gb);
528 hvcc->bitDepthChromaMinus8 = get_ue_golomb_long(gb);
529 log2_max_pic_order_cnt_lsb_minus4 = get_ue_golomb_long(gb);
531 /* sps_sub_layer_ordering_info_present_flag */
532 i = get_bits1(gb) ? 0 : sps_max_sub_layers_minus1;
533 for (; i <= sps_max_sub_layers_minus1; i++)
534 skip_sub_layer_ordering_info(gb);
536 get_ue_golomb_long(gb); // log2_min_luma_coding_block_size_minus3
537 get_ue_golomb_long(gb); // log2_diff_max_min_luma_coding_block_size
538 get_ue_golomb_long(gb); // log2_min_transform_block_size_minus2
539 get_ue_golomb_long(gb); // log2_diff_max_min_transform_block_size
540 get_ue_golomb_long(gb); // max_transform_hierarchy_depth_inter
541 get_ue_golomb_long(gb); // max_transform_hierarchy_depth_intra
543 if (get_bits1(gb) && // scaling_list_enabled_flag
544 get_bits1(gb)) // sps_scaling_list_data_present_flag
545 skip_scaling_list_data(gb);
547 skip_bits1(gb); // amp_enabled_flag
548 skip_bits1(gb); // sample_adaptive_offset_enabled_flag
550 if (get_bits1(gb)) { // pcm_enabled_flag
551 skip_bits (gb, 4); // pcm_sample_bit_depth_luma_minus1
552 skip_bits (gb, 4); // pcm_sample_bit_depth_chroma_minus1
553 get_ue_golomb_long(gb); // log2_min_pcm_luma_coding_block_size_minus3
554 get_ue_golomb_long(gb); // log2_diff_max_min_pcm_luma_coding_block_size
555 skip_bits1 (gb); // pcm_loop_filter_disabled_flag
558 num_short_term_ref_pic_sets = get_ue_golomb_long(gb);
559 if (num_short_term_ref_pic_sets > HEVC_MAX_SHORT_TERM_REF_PIC_SETS)
560 return AVERROR_INVALIDDATA;
562 for (i = 0; i < num_short_term_ref_pic_sets; i++) {
563 int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, num_delta_pocs);
568 if (get_bits1(gb)) { // long_term_ref_pics_present_flag
569 unsigned num_long_term_ref_pics_sps = get_ue_golomb_long(gb);
570 if (num_long_term_ref_pics_sps > 31U)
571 return AVERROR_INVALIDDATA;
572 for (i = 0; i < num_long_term_ref_pics_sps; i++) { // num_long_term_ref_pics_sps
573 int len = FFMIN(log2_max_pic_order_cnt_lsb_minus4 + 4, 16);
574 skip_bits (gb, len); // lt_ref_pic_poc_lsb_sps[i]
575 skip_bits1(gb); // used_by_curr_pic_lt_sps_flag[i]
579 skip_bits1(gb); // sps_temporal_mvp_enabled_flag
580 skip_bits1(gb); // strong_intra_smoothing_enabled_flag
582 if (get_bits1(gb)) // vui_parameters_present_flag
583 hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
585 /* nothing useful for hvcC past this point */
589 static int hvcc_parse_pps(GetBitContext *gb,
590 HEVCDecoderConfigurationRecord *hvcc)
592 uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
594 get_ue_golomb_long(gb); // pps_pic_parameter_set_id
595 get_ue_golomb_long(gb); // pps_seq_parameter_set_id
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)
606 get_ue_golomb_long(gb); // num_ref_idx_l0_default_active_minus1
607 get_ue_golomb_long(gb); // num_ref_idx_l1_default_active_minus1
608 get_se_golomb_long(gb); // init_qp_minus26
611 * constrained_intra_pred_flag u(1)
612 * transform_skip_enabled_flag u(1)
616 if (get_bits1(gb)) // cu_qp_delta_enabled_flag
617 get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
619 get_se_golomb_long(gb); // pps_cb_qp_offset
620 get_se_golomb_long(gb); // pps_cr_qp_offset
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)
630 tiles_enabled_flag = get_bits1(gb);
631 entropy_coding_sync_enabled_flag = get_bits1(gb);
633 if (entropy_coding_sync_enabled_flag && tiles_enabled_flag)
634 hvcc->parallelismType = 0; // mixed-type parallel decoding
635 else if (entropy_coding_sync_enabled_flag)
636 hvcc->parallelismType = 3; // wavefront-based parallel decoding
637 else if (tiles_enabled_flag)
638 hvcc->parallelismType = 2; // tile-based parallel decoding
640 hvcc->parallelismType = 1; // slice-based parallel decoding
642 /* nothing useful for hvcC past this point */
646 static void nal_unit_parse_header(GetBitContext *gb, uint8_t *nal_type)
648 skip_bits1(gb); // forbidden_zero_bit
650 *nal_type = get_bits(gb, 6);
654 * nuh_temporal_id_plus1 u(3)
659 static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
660 uint8_t nal_type, int ps_array_completeness,
661 HEVCDecoderConfigurationRecord *hvcc)
666 HVCCNALUnitArray *array;
668 for (index = 0; index < hvcc->numOfArrays; index++)
669 if (hvcc->array[index].NAL_unit_type == nal_type)
672 if (index >= hvcc->numOfArrays) {
675 ret = av_reallocp_array(&hvcc->array, index + 1, sizeof(HVCCNALUnitArray));
679 for (i = hvcc->numOfArrays; i <= index; i++)
680 memset(&hvcc->array[i], 0, sizeof(HVCCNALUnitArray));
681 hvcc->numOfArrays = index + 1;
684 array = &hvcc->array[index];
685 numNalus = array->numNalus;
687 ret = av_reallocp_array(&array->nalUnit, numNalus + 1, sizeof(uint8_t*));
691 ret = av_reallocp_array(&array->nalUnitLength, numNalus + 1, sizeof(uint16_t));
695 array->nalUnit [numNalus] = nal_buf;
696 array->nalUnitLength[numNalus] = nal_size;
697 array->NAL_unit_type = nal_type;
701 * When the sample entry name is ‘hvc1’, the default and mandatory value of
702 * array_completeness is 1 for arrays of all types of parameter sets, and 0
703 * for all other arrays. When the sample entry name is ‘hev1’, the default
704 * value of array_completeness is 0 for all arrays.
706 if (nal_type == HEVC_NAL_VPS || nal_type == HEVC_NAL_SPS || nal_type == HEVC_NAL_PPS)
707 array->array_completeness = ps_array_completeness;
712 static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
713 int ps_array_completeness,
714 HEVCDecoderConfigurationRecord *hvcc)
722 rbsp_buf = ff_nal_unit_extract_rbsp(nal_buf, nal_size, &rbsp_size, 2);
724 ret = AVERROR(ENOMEM);
728 ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
732 nal_unit_parse_header(&gbc, &nal_type);
735 * Note: only 'declarative' SEI messages are allowed in
736 * hvcC. Perhaps the SEI playload type should be checked
737 * and non-declarative SEI messages discarded?
743 case HEVC_NAL_SEI_PREFIX:
744 case HEVC_NAL_SEI_SUFFIX:
745 ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type,
746 ps_array_completeness, hvcc);
749 else if (nal_type == HEVC_NAL_VPS)
750 ret = hvcc_parse_vps(&gbc, hvcc);
751 else if (nal_type == HEVC_NAL_SPS)
752 ret = hvcc_parse_sps(&gbc, hvcc);
753 else if (nal_type == HEVC_NAL_PPS)
754 ret = hvcc_parse_pps(&gbc, hvcc);
759 ret = AVERROR_INVALIDDATA;
768 static void hvcc_init(HEVCDecoderConfigurationRecord *hvcc)
770 memset(hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
771 hvcc->configurationVersion = 1;
772 hvcc->lengthSizeMinusOne = 3; // 4 bytes
775 * The following fields have all their valid bits set by default,
776 * the ProfileTierLevel parsing code will unset them when needed.
778 hvcc->general_profile_compatibility_flags = 0xffffffff;
779 hvcc->general_constraint_indicator_flags = 0xffffffffffff;
782 * Initialize this field with an invalid value which can be used to detect
783 * whether we didn't see any VUI (in which case it should be reset to zero).
785 hvcc->min_spatial_segmentation_idc = MAX_SPATIAL_SEGMENTATION + 1;
788 static void hvcc_close(HEVCDecoderConfigurationRecord *hvcc)
792 for (i = 0; i < hvcc->numOfArrays; i++) {
793 hvcc->array[i].numNalus = 0;
794 av_freep(&hvcc->array[i].nalUnit);
795 av_freep(&hvcc->array[i].nalUnitLength);
798 hvcc->numOfArrays = 0;
799 av_freep(&hvcc->array);
802 static int hvcc_write(AVIOContext *pb, HEVCDecoderConfigurationRecord *hvcc)
805 uint16_t j, vps_count = 0, sps_count = 0, pps_count = 0;
808 * We only support writing HEVCDecoderConfigurationRecord version 1.
810 hvcc->configurationVersion = 1;
813 * If min_spatial_segmentation_idc is invalid, reset to 0 (unspecified).
815 if (hvcc->min_spatial_segmentation_idc > MAX_SPATIAL_SEGMENTATION)
816 hvcc->min_spatial_segmentation_idc = 0;
819 * parallelismType indicates the type of parallelism that is used to meet
820 * the restrictions imposed by min_spatial_segmentation_idc when the value
821 * of min_spatial_segmentation_idc is greater than 0.
823 if (!hvcc->min_spatial_segmentation_idc)
824 hvcc->parallelismType = 0;
827 * It's unclear how to properly compute these fields, so
828 * let's always set them to values meaning 'unspecified'.
830 hvcc->avgFrameRate = 0;
831 hvcc->constantFrameRate = 0;
833 av_log(NULL, AV_LOG_TRACE, "configurationVersion: %"PRIu8"\n",
834 hvcc->configurationVersion);
835 av_log(NULL, AV_LOG_TRACE, "general_profile_space: %"PRIu8"\n",
836 hvcc->general_profile_space);
837 av_log(NULL, AV_LOG_TRACE, "general_tier_flag: %"PRIu8"\n",
838 hvcc->general_tier_flag);
839 av_log(NULL, AV_LOG_TRACE, "general_profile_idc: %"PRIu8"\n",
840 hvcc->general_profile_idc);
841 av_log(NULL, AV_LOG_TRACE, "general_profile_compatibility_flags: 0x%08"PRIx32"\n",
842 hvcc->general_profile_compatibility_flags);
843 av_log(NULL, AV_LOG_TRACE, "general_constraint_indicator_flags: 0x%012"PRIx64"\n",
844 hvcc->general_constraint_indicator_flags);
845 av_log(NULL, AV_LOG_TRACE, "general_level_idc: %"PRIu8"\n",
846 hvcc->general_level_idc);
847 av_log(NULL, AV_LOG_TRACE, "min_spatial_segmentation_idc: %"PRIu16"\n",
848 hvcc->min_spatial_segmentation_idc);
849 av_log(NULL, AV_LOG_TRACE, "parallelismType: %"PRIu8"\n",
850 hvcc->parallelismType);
851 av_log(NULL, AV_LOG_TRACE, "chromaFormat: %"PRIu8"\n",
853 av_log(NULL, AV_LOG_TRACE, "bitDepthLumaMinus8: %"PRIu8"\n",
854 hvcc->bitDepthLumaMinus8);
855 av_log(NULL, AV_LOG_TRACE, "bitDepthChromaMinus8: %"PRIu8"\n",
856 hvcc->bitDepthChromaMinus8);
857 av_log(NULL, AV_LOG_TRACE, "avgFrameRate: %"PRIu16"\n",
859 av_log(NULL, AV_LOG_TRACE, "constantFrameRate: %"PRIu8"\n",
860 hvcc->constantFrameRate);
861 av_log(NULL, AV_LOG_TRACE, "numTemporalLayers: %"PRIu8"\n",
862 hvcc->numTemporalLayers);
863 av_log(NULL, AV_LOG_TRACE, "temporalIdNested: %"PRIu8"\n",
864 hvcc->temporalIdNested);
865 av_log(NULL, AV_LOG_TRACE, "lengthSizeMinusOne: %"PRIu8"\n",
866 hvcc->lengthSizeMinusOne);
867 av_log(NULL, AV_LOG_TRACE, "numOfArrays: %"PRIu8"\n",
869 for (i = 0; i < hvcc->numOfArrays; i++) {
870 av_log(NULL, AV_LOG_TRACE, "array_completeness[%"PRIu8"]: %"PRIu8"\n",
871 i, hvcc->array[i].array_completeness);
872 av_log(NULL, AV_LOG_TRACE, "NAL_unit_type[%"PRIu8"]: %"PRIu8"\n",
873 i, hvcc->array[i].NAL_unit_type);
874 av_log(NULL, AV_LOG_TRACE, "numNalus[%"PRIu8"]: %"PRIu16"\n",
875 i, hvcc->array[i].numNalus);
876 for (j = 0; j < hvcc->array[i].numNalus; j++)
877 av_log(NULL, AV_LOG_TRACE,
878 "nalUnitLength[%"PRIu8"][%"PRIu16"]: %"PRIu16"\n",
879 i, j, hvcc->array[i].nalUnitLength[j]);
883 * We need at least one of each: VPS, SPS and PPS.
885 for (i = 0; i < hvcc->numOfArrays; i++)
886 switch (hvcc->array[i].NAL_unit_type) {
888 vps_count += hvcc->array[i].numNalus;
891 sps_count += hvcc->array[i].numNalus;
894 pps_count += hvcc->array[i].numNalus;
899 if (!vps_count || vps_count > HEVC_MAX_VPS_COUNT ||
900 !sps_count || sps_count > HEVC_MAX_SPS_COUNT ||
901 !pps_count || pps_count > HEVC_MAX_PPS_COUNT)
902 return AVERROR_INVALIDDATA;
904 /* unsigned int(8) configurationVersion = 1; */
905 avio_w8(pb, hvcc->configurationVersion);
908 * unsigned int(2) general_profile_space;
909 * unsigned int(1) general_tier_flag;
910 * unsigned int(5) general_profile_idc;
912 avio_w8(pb, hvcc->general_profile_space << 6 |
913 hvcc->general_tier_flag << 5 |
914 hvcc->general_profile_idc);
916 /* unsigned int(32) general_profile_compatibility_flags; */
917 avio_wb32(pb, hvcc->general_profile_compatibility_flags);
919 /* unsigned int(48) general_constraint_indicator_flags; */
920 avio_wb32(pb, hvcc->general_constraint_indicator_flags >> 16);
921 avio_wb16(pb, hvcc->general_constraint_indicator_flags);
923 /* unsigned int(8) general_level_idc; */
924 avio_w8(pb, hvcc->general_level_idc);
927 * bit(4) reserved = ‘1111’b;
928 * unsigned int(12) min_spatial_segmentation_idc;
930 avio_wb16(pb, hvcc->min_spatial_segmentation_idc | 0xf000);
933 * bit(6) reserved = ‘111111’b;
934 * unsigned int(2) parallelismType;
936 avio_w8(pb, hvcc->parallelismType | 0xfc);
939 * bit(6) reserved = ‘111111’b;
940 * unsigned int(2) chromaFormat;
942 avio_w8(pb, hvcc->chromaFormat | 0xfc);
945 * bit(5) reserved = ‘11111’b;
946 * unsigned int(3) bitDepthLumaMinus8;
948 avio_w8(pb, hvcc->bitDepthLumaMinus8 | 0xf8);
951 * bit(5) reserved = ‘11111’b;
952 * unsigned int(3) bitDepthChromaMinus8;
954 avio_w8(pb, hvcc->bitDepthChromaMinus8 | 0xf8);
956 /* bit(16) avgFrameRate; */
957 avio_wb16(pb, hvcc->avgFrameRate);
960 * bit(2) constantFrameRate;
961 * bit(3) numTemporalLayers;
962 * bit(1) temporalIdNested;
963 * unsigned int(2) lengthSizeMinusOne;
965 avio_w8(pb, hvcc->constantFrameRate << 6 |
966 hvcc->numTemporalLayers << 3 |
967 hvcc->temporalIdNested << 2 |
968 hvcc->lengthSizeMinusOne);
970 /* unsigned int(8) numOfArrays; */
971 avio_w8(pb, hvcc->numOfArrays);
973 for (i = 0; i < hvcc->numOfArrays; i++) {
975 * bit(1) array_completeness;
976 * unsigned int(1) reserved = 0;
977 * unsigned int(6) NAL_unit_type;
979 avio_w8(pb, hvcc->array[i].array_completeness << 7 |
980 hvcc->array[i].NAL_unit_type & 0x3f);
982 /* unsigned int(16) numNalus; */
983 avio_wb16(pb, hvcc->array[i].numNalus);
985 for (j = 0; j < hvcc->array[i].numNalus; j++) {
986 /* unsigned int(16) nalUnitLength; */
987 avio_wb16(pb, hvcc->array[i].nalUnitLength[j]);
989 /* bit(8*nalUnitLength) nalUnit; */
990 avio_write(pb, hvcc->array[i].nalUnit[j],
991 hvcc->array[i].nalUnitLength[j]);
998 int ff_hevc_annexb2mp4(AVIOContext *pb, const uint8_t *buf_in,
999 int size, int filter_ps, int *ps_count)
1001 int num_ps = 0, ret = 0;
1002 uint8_t *buf, *end, *start = NULL;
1005 ret = ff_avc_parse_nal_units(pb, buf_in, size);
1009 ret = ff_avc_parse_nal_units_buf(buf_in, &start, &size);
1017 while (end - buf > 4) {
1018 uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1019 uint8_t type = (buf[4] >> 1) & 0x3f;
1032 avio_write(pb, buf, len);
1046 int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out,
1047 int *size, int filter_ps, int *ps_count)
1052 ret = avio_open_dyn_buf(&pb);
1056 ret = ff_hevc_annexb2mp4(pb, buf_in, *size, filter_ps, ps_count);
1057 *size = avio_close_dyn_buf(pb, buf_out);
1062 int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data,
1063 int size, int ps_array_completeness)
1066 uint8_t *buf, *end, *start = NULL;
1067 HEVCDecoderConfigurationRecord hvcc;
1072 /* We can't write a valid hvcC from the provided data */
1073 ret = AVERROR_INVALIDDATA;
1075 } else if (*data == 1) {
1076 /* Data is already hvcC-formatted */
1077 avio_write(pb, data, size);
1079 } else if (!(AV_RB24(data) == 1 || AV_RB32(data) == 1)) {
1080 /* Not a valid Annex B start code prefix */
1081 ret = AVERROR_INVALIDDATA;
1085 ret = ff_avc_parse_nal_units_buf(data, &start, &size);
1092 while (end - buf > 4) {
1093 uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1094 uint8_t type = (buf[4] >> 1) & 0x3f;
1102 case HEVC_NAL_SEI_PREFIX:
1103 case HEVC_NAL_SEI_SUFFIX:
1104 ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc);
1115 ret = hvcc_write(pb, &hvcc);