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/get_bits.h"
22 #include "libavcodec/golomb.h"
23 #include "libavcodec/hevc.h"
24 #include "libavutil/intreadwrite.h"
29 #define MAX_SPATIAL_SEGMENTATION 4096 // max. value of u(12) field
31 typedef struct HVCCNALUnitArray {
32 uint8_t array_completeness;
33 uint8_t NAL_unit_type;
35 uint16_t *nalUnitLength;
39 typedef struct HEVCDecoderConfigurationRecord {
40 uint8_t configurationVersion;
41 uint8_t general_profile_space;
42 uint8_t general_tier_flag;
43 uint8_t general_profile_idc;
44 uint32_t general_profile_compatibility_flags;
45 uint64_t general_constraint_indicator_flags;
46 uint8_t general_level_idc;
47 uint16_t min_spatial_segmentation_idc;
48 uint8_t parallelismType;
50 uint8_t bitDepthLumaMinus8;
51 uint8_t bitDepthChromaMinus8;
52 uint16_t avgFrameRate;
53 uint8_t constantFrameRate;
54 uint8_t numTemporalLayers;
55 uint8_t temporalIdNested;
56 uint8_t lengthSizeMinusOne;
58 HVCCNALUnitArray *array;
59 } HEVCDecoderConfigurationRecord;
61 typedef struct HVCCProfileTierLevel {
62 uint8_t profile_space;
65 uint32_t profile_compatibility_flags;
66 uint64_t constraint_indicator_flags;
68 } HVCCProfileTierLevel;
70 static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc,
71 HVCCProfileTierLevel *ptl)
74 * The value of general_profile_space in all the parameter sets must be
77 hvcc->general_profile_space = ptl->profile_space;
80 * The level indication general_level_idc must indicate a level of
81 * capability equal to or greater than the highest level indicated for the
82 * highest tier in all the parameter sets.
84 if (hvcc->general_tier_flag < ptl->tier_flag)
85 hvcc->general_level_idc = ptl->level_idc;
87 hvcc->general_level_idc = FFMAX(hvcc->general_level_idc, ptl->level_idc);
90 * The tier indication general_tier_flag must indicate a tier equal to or
91 * greater than the highest tier indicated in all the parameter sets.
93 hvcc->general_tier_flag = FFMAX(hvcc->general_tier_flag, ptl->tier_flag);
96 * The profile indication general_profile_idc must indicate a profile to
97 * which the stream associated with this configuration record conforms.
99 * If the sequence parameter sets are marked with different profiles, then
100 * the stream may need examination to determine which profile, if any, the
101 * entire stream conforms to. If the entire stream is not examined, or the
102 * examination reveals that there is no profile to which the entire stream
103 * conforms, then the entire stream must be split into two or more
104 * sub-streams with separate configuration records in which these rules can
107 * Note: set the profile to the highest value for the sake of simplicity.
109 hvcc->general_profile_idc = FFMAX(hvcc->general_profile_idc, ptl->profile_idc);
112 * Each bit in general_profile_compatibility_flags may only be set if all
113 * the parameter sets set that bit.
115 hvcc->general_profile_compatibility_flags &= ptl->profile_compatibility_flags;
118 * Each bit in general_constraint_indicator_flags may only be set if all
119 * the parameter sets set that bit.
121 hvcc->general_constraint_indicator_flags &= ptl->constraint_indicator_flags;
124 static void hvcc_parse_ptl(GetBitContext *gb,
125 HEVCDecoderConfigurationRecord *hvcc,
126 unsigned int max_sub_layers_minus1)
129 HVCCProfileTierLevel general_ptl;
130 uint8_t sub_layer_profile_present_flag[MAX_SUB_LAYERS];
131 uint8_t sub_layer_level_present_flag[MAX_SUB_LAYERS];
133 general_ptl.profile_space = get_bits(gb, 2);
134 general_ptl.tier_flag = get_bits1(gb);
135 general_ptl.profile_idc = get_bits(gb, 5);
136 general_ptl.profile_compatibility_flags = get_bits_long(gb, 32);
137 general_ptl.constraint_indicator_flags = get_bits64(gb, 48);
138 general_ptl.level_idc = get_bits(gb, 8);
139 hvcc_update_ptl(hvcc, &general_ptl);
141 for (i = 0; i < max_sub_layers_minus1; i++) {
142 sub_layer_profile_present_flag[i] = get_bits1(gb);
143 sub_layer_level_present_flag[i] = get_bits1(gb);
146 if (max_sub_layers_minus1 > 0)
147 for (i = max_sub_layers_minus1; i < 8; i++)
148 skip_bits(gb, 2); // reserved_zero_2bits[i]
150 for (i = 0; i < max_sub_layers_minus1; i++) {
151 if (sub_layer_profile_present_flag[i]) {
153 * sub_layer_profile_space[i] u(2)
154 * sub_layer_tier_flag[i] u(1)
155 * sub_layer_profile_idc[i] u(5)
156 * sub_layer_profile_compatibility_flag[i][0..31] u(32)
157 * sub_layer_progressive_source_flag[i] u(1)
158 * sub_layer_interlaced_source_flag[i] u(1)
159 * sub_layer_non_packed_constraint_flag[i] u(1)
160 * sub_layer_frame_only_constraint_flag[i] u(1)
161 * sub_layer_reserved_zero_44bits[i] u(44)
163 skip_bits_long(gb, 32);
164 skip_bits_long(gb, 32);
168 if (sub_layer_level_present_flag[i])
173 static void skip_sub_layer_hrd_parameters(GetBitContext *gb,
174 unsigned int cpb_cnt_minus1,
175 uint8_t sub_pic_hrd_params_present_flag)
179 for (i = 0; i <= cpb_cnt_minus1; i++) {
180 get_ue_golomb_long(gb); // bit_rate_value_minus1
181 get_ue_golomb_long(gb); // cpb_size_value_minus1
183 if (sub_pic_hrd_params_present_flag) {
184 get_ue_golomb_long(gb); // cpb_size_du_value_minus1
185 get_ue_golomb_long(gb); // bit_rate_du_value_minus1
188 skip_bits1(gb); // cbr_flag
192 static int skip_hrd_parameters(GetBitContext *gb, uint8_t cprms_present_flag,
193 unsigned int max_sub_layers_minus1)
196 uint8_t sub_pic_hrd_params_present_flag = 0;
197 uint8_t nal_hrd_parameters_present_flag = 0;
198 uint8_t vcl_hrd_parameters_present_flag = 0;
200 if (cprms_present_flag) {
201 nal_hrd_parameters_present_flag = get_bits1(gb);
202 vcl_hrd_parameters_present_flag = get_bits1(gb);
204 if (nal_hrd_parameters_present_flag ||
205 vcl_hrd_parameters_present_flag) {
206 sub_pic_hrd_params_present_flag = get_bits1(gb);
208 if (sub_pic_hrd_params_present_flag)
210 * tick_divisor_minus2 u(8)
211 * du_cpb_removal_delay_increment_length_minus1 u(5)
212 * sub_pic_cpb_params_in_pic_timing_sei_flag u(1)
213 * dpb_output_delay_du_length_minus1 u(5)
218 * bit_rate_scale u(4)
219 * cpb_size_scale u(4)
223 if (sub_pic_hrd_params_present_flag)
224 skip_bits(gb, 4); // cpb_size_du_scale
227 * initial_cpb_removal_delay_length_minus1 u(5)
228 * au_cpb_removal_delay_length_minus1 u(5)
229 * dpb_output_delay_length_minus1 u(5)
235 for (i = 0; i <= max_sub_layers_minus1; i++) {
236 unsigned int cpb_cnt_minus1 = 0;
237 uint8_t low_delay_hrd_flag = 0;
238 uint8_t fixed_pic_rate_within_cvs_flag = 0;
239 uint8_t fixed_pic_rate_general_flag = get_bits1(gb);
241 if (!fixed_pic_rate_general_flag)
242 fixed_pic_rate_within_cvs_flag = get_bits1(gb);
244 if (fixed_pic_rate_within_cvs_flag)
245 get_ue_golomb_long(gb); // elemental_duration_in_tc_minus1
247 low_delay_hrd_flag = get_bits1(gb);
249 if (!low_delay_hrd_flag) {
250 cpb_cnt_minus1 = get_ue_golomb_long(gb);
251 if (cpb_cnt_minus1 > 31)
252 return AVERROR_INVALIDDATA;
255 if (nal_hrd_parameters_present_flag)
256 skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
257 sub_pic_hrd_params_present_flag);
259 if (vcl_hrd_parameters_present_flag)
260 skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
261 sub_pic_hrd_params_present_flag);
267 static void skip_timing_info(GetBitContext *gb)
269 skip_bits_long(gb, 32); // num_units_in_tick
270 skip_bits_long(gb, 32); // time_scale
272 if (get_bits1(gb)) // poc_proportional_to_timing_flag
273 get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1
276 static void hvcc_parse_vui(GetBitContext *gb,
277 HEVCDecoderConfigurationRecord *hvcc,
278 unsigned int max_sub_layers_minus1)
280 unsigned int min_spatial_segmentation_idc;
282 if (get_bits1(gb)) // aspect_ratio_info_present_flag
283 if (get_bits(gb, 8) == 255) // aspect_ratio_idc
284 skip_bits_long(gb, 32); // sar_width u(16), sar_height u(16)
286 if (get_bits1(gb)) // overscan_info_present_flag
287 skip_bits1(gb); // overscan_appropriate_flag
289 if (get_bits1(gb)) { // video_signal_type_present_flag
290 skip_bits(gb, 4); // video_format u(3), video_full_range_flag u(1)
292 if (get_bits1(gb)) // colour_description_present_flag
294 * colour_primaries u(8)
295 * transfer_characteristics u(8)
301 if (get_bits1(gb)) { // chroma_loc_info_present_flag
302 get_ue_golomb_long(gb); // chroma_sample_loc_type_top_field
303 get_ue_golomb_long(gb); // chroma_sample_loc_type_bottom_field
307 * neutral_chroma_indication_flag u(1)
308 * field_seq_flag u(1)
309 * frame_field_info_present_flag u(1)
313 if (get_bits1(gb)) { // default_display_window_flag
314 get_ue_golomb_long(gb); // def_disp_win_left_offset
315 get_ue_golomb_long(gb); // def_disp_win_right_offset
316 get_ue_golomb_long(gb); // def_disp_win_top_offset
317 get_ue_golomb_long(gb); // def_disp_win_bottom_offset
320 if (get_bits1(gb)) { // vui_timing_info_present_flag
321 skip_timing_info(gb);
323 if (get_bits1(gb)) // vui_hrd_parameters_present_flag
324 skip_hrd_parameters(gb, 1, max_sub_layers_minus1);
327 if (get_bits1(gb)) { // bitstream_restriction_flag
329 * tiles_fixed_structure_flag u(1)
330 * motion_vectors_over_pic_boundaries_flag u(1)
331 * restricted_ref_pic_lists_flag u(1)
335 min_spatial_segmentation_idc = get_ue_golomb_long(gb);
338 * unsigned int(12) min_spatial_segmentation_idc;
340 * The min_spatial_segmentation_idc indication must indicate a level of
341 * spatial segmentation equal to or less than the lowest level of
342 * spatial segmentation indicated in all the parameter sets.
344 hvcc->min_spatial_segmentation_idc = FFMIN(hvcc->min_spatial_segmentation_idc,
345 min_spatial_segmentation_idc);
347 get_ue_golomb_long(gb); // max_bytes_per_pic_denom
348 get_ue_golomb_long(gb); // max_bits_per_min_cu_denom
349 get_ue_golomb_long(gb); // log2_max_mv_length_horizontal
350 get_ue_golomb_long(gb); // log2_max_mv_length_vertical
354 static void skip_sub_layer_ordering_info(GetBitContext *gb)
356 get_ue_golomb_long(gb); // max_dec_pic_buffering_minus1
357 get_ue_golomb_long(gb); // max_num_reorder_pics
358 get_ue_golomb_long(gb); // max_latency_increase_plus1
361 static int hvcc_parse_vps(GetBitContext *gb,
362 HEVCDecoderConfigurationRecord *hvcc)
364 unsigned int vps_max_sub_layers_minus1;
367 * vps_video_parameter_set_id u(4)
368 * vps_reserved_three_2bits u(2)
369 * vps_max_layers_minus1 u(6)
373 vps_max_sub_layers_minus1 = get_bits(gb, 3);
376 * numTemporalLayers greater than 1 indicates that the stream to which this
377 * configuration record applies is temporally scalable and the contained
378 * number of temporal layers (also referred to as temporal sub-layer or
379 * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
380 * indicates that the stream is not temporally scalable. Value 0 indicates
381 * that it is unknown whether the stream is temporally scalable.
383 hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
384 vps_max_sub_layers_minus1 + 1);
387 * vps_temporal_id_nesting_flag u(1)
388 * vps_reserved_0xffff_16bits u(16)
392 hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1);
394 /* nothing useful for hvcC past this point */
398 static void skip_scaling_list_data(GetBitContext *gb)
400 int i, j, k, num_coeffs;
402 for (i = 0; i < 4; i++)
403 for (j = 0; j < (i == 3 ? 2 : 6); j++)
404 if (!get_bits1(gb)) // scaling_list_pred_mode_flag[i][j]
405 get_ue_golomb_long(gb); // scaling_list_pred_matrix_id_delta[i][j]
407 num_coeffs = FFMIN(64, 1 << (4 + (i << 1)));
410 get_se_golomb_long(gb); // scaling_list_dc_coef_minus8[i-2][j]
412 for (k = 0; k < num_coeffs; k++)
413 get_se_golomb_long(gb); // scaling_list_delta_coef
417 static int parse_rps(GetBitContext *gb, unsigned int rps_idx,
418 unsigned int num_rps,
419 unsigned int num_delta_pocs[MAX_SHORT_TERM_RPS_COUNT])
423 if (rps_idx && get_bits1(gb)) { // inter_ref_pic_set_prediction_flag
424 /* this should only happen for slice headers, and this isn't one */
425 if (rps_idx >= num_rps)
426 return AVERROR_INVALIDDATA;
428 skip_bits1 (gb); // delta_rps_sign
429 get_ue_golomb_long(gb); // abs_delta_rps_minus1
431 num_delta_pocs[rps_idx] = 0;
434 * From libavcodec/hevc_ps.c:
436 * if (is_slice_header) {
439 * rps_ridx = &sps->st_rps[rps - sps->st_rps - 1];
442 * rps: &sps->st_rps[rps_idx]
443 * sps->st_rps: &sps->st_rps[0]
444 * is_slice_header: rps_idx == num_rps
447 * if (num_rps != rps_idx)
448 * rps_ridx = &sps->st_rps[rps_idx - 1];
450 * NumDeltaPocs[RefRpsIdx]: num_delta_pocs[rps_idx - 1]
452 for (i = 0; i <= num_delta_pocs[rps_idx - 1]; i++) {
453 uint8_t use_delta_flag = 0;
454 uint8_t used_by_curr_pic_flag = get_bits1(gb);
455 if (!used_by_curr_pic_flag)
456 use_delta_flag = get_bits1(gb);
458 if (used_by_curr_pic_flag || use_delta_flag)
459 num_delta_pocs[rps_idx]++;
462 unsigned int num_negative_pics = get_ue_golomb_long(gb);
463 unsigned int num_positive_pics = get_ue_golomb_long(gb);
465 if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > get_bits_left(gb))
466 return AVERROR_INVALIDDATA;
468 num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics;
470 for (i = 0; i < num_negative_pics; i++) {
471 get_ue_golomb_long(gb); // delta_poc_s0_minus1[rps_idx]
472 skip_bits1 (gb); // used_by_curr_pic_s0_flag[rps_idx]
475 for (i = 0; i < num_positive_pics; i++) {
476 get_ue_golomb_long(gb); // delta_poc_s1_minus1[rps_idx]
477 skip_bits1 (gb); // used_by_curr_pic_s1_flag[rps_idx]
484 static int hvcc_parse_sps(GetBitContext *gb,
485 HEVCDecoderConfigurationRecord *hvcc)
487 unsigned int i, sps_max_sub_layers_minus1, log2_max_pic_order_cnt_lsb_minus4;
488 unsigned int num_short_term_ref_pic_sets, num_delta_pocs[MAX_SHORT_TERM_RPS_COUNT];
490 skip_bits(gb, 4); // sps_video_parameter_set_id
492 sps_max_sub_layers_minus1 = get_bits (gb, 3);
495 * numTemporalLayers greater than 1 indicates that the stream to which this
496 * configuration record applies is temporally scalable and the contained
497 * number of temporal layers (also referred to as temporal sub-layer or
498 * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
499 * indicates that the stream is not temporally scalable. Value 0 indicates
500 * that it is unknown whether the stream is temporally scalable.
502 hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
503 sps_max_sub_layers_minus1 + 1);
505 hvcc->temporalIdNested = get_bits1(gb);
507 hvcc_parse_ptl(gb, hvcc, sps_max_sub_layers_minus1);
509 get_ue_golomb_long(gb); // sps_seq_parameter_set_id
511 hvcc->chromaFormat = get_ue_golomb_long(gb);
513 if (hvcc->chromaFormat == 3)
514 skip_bits1(gb); // separate_colour_plane_flag
516 get_ue_golomb_long(gb); // pic_width_in_luma_samples
517 get_ue_golomb_long(gb); // pic_height_in_luma_samples
519 if (get_bits1(gb)) { // conformance_window_flag
520 get_ue_golomb_long(gb); // conf_win_left_offset
521 get_ue_golomb_long(gb); // conf_win_right_offset
522 get_ue_golomb_long(gb); // conf_win_top_offset
523 get_ue_golomb_long(gb); // conf_win_bottom_offset
526 hvcc->bitDepthLumaMinus8 = get_ue_golomb_long(gb);
527 hvcc->bitDepthChromaMinus8 = get_ue_golomb_long(gb);
528 log2_max_pic_order_cnt_lsb_minus4 = get_ue_golomb_long(gb);
530 /* sps_sub_layer_ordering_info_present_flag */
531 i = get_bits1(gb) ? 0 : sps_max_sub_layers_minus1;
532 for (; i <= sps_max_sub_layers_minus1; i++)
533 skip_sub_layer_ordering_info(gb);
535 get_ue_golomb_long(gb); // log2_min_luma_coding_block_size_minus3
536 get_ue_golomb_long(gb); // log2_diff_max_min_luma_coding_block_size
537 get_ue_golomb_long(gb); // log2_min_transform_block_size_minus2
538 get_ue_golomb_long(gb); // log2_diff_max_min_transform_block_size
539 get_ue_golomb_long(gb); // max_transform_hierarchy_depth_inter
540 get_ue_golomb_long(gb); // max_transform_hierarchy_depth_intra
542 if (get_bits1(gb) && // scaling_list_enabled_flag
543 get_bits1(gb)) // sps_scaling_list_data_present_flag
544 skip_scaling_list_data(gb);
546 skip_bits1(gb); // amp_enabled_flag
547 skip_bits1(gb); // sample_adaptive_offset_enabled_flag
549 if (get_bits1(gb)) { // pcm_enabled_flag
550 skip_bits (gb, 4); // pcm_sample_bit_depth_luma_minus1
551 skip_bits (gb, 4); // pcm_sample_bit_depth_chroma_minus1
552 get_ue_golomb_long(gb); // log2_min_pcm_luma_coding_block_size_minus3
553 get_ue_golomb_long(gb); // log2_diff_max_min_pcm_luma_coding_block_size
554 skip_bits1 (gb); // pcm_loop_filter_disabled_flag
557 num_short_term_ref_pic_sets = get_ue_golomb_long(gb);
558 if (num_short_term_ref_pic_sets > MAX_SHORT_TERM_RPS_COUNT)
559 return AVERROR_INVALIDDATA;
561 for (i = 0; i < num_short_term_ref_pic_sets; i++) {
562 int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, num_delta_pocs);
567 if (get_bits1(gb)) { // long_term_ref_pics_present_flag
568 for (i = 0; i < get_ue_golomb_long(gb); i++) { // num_long_term_ref_pics_sps
569 int len = FFMIN(log2_max_pic_order_cnt_lsb_minus4 + 4, 16);
570 skip_bits (gb, len); // lt_ref_pic_poc_lsb_sps[i]
571 skip_bits1(gb); // used_by_curr_pic_lt_sps_flag[i]
575 skip_bits1(gb); // sps_temporal_mvp_enabled_flag
576 skip_bits1(gb); // strong_intra_smoothing_enabled_flag
578 if (get_bits1(gb)) // vui_parameters_present_flag
579 hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
581 /* nothing useful for hvcC past this point */
585 static int hvcc_parse_pps(GetBitContext *gb,
586 HEVCDecoderConfigurationRecord *hvcc)
588 uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
590 get_ue_golomb_long(gb); // pps_pic_parameter_set_id
591 get_ue_golomb_long(gb); // pps_seq_parameter_set_id
594 * dependent_slice_segments_enabled_flag u(1)
595 * output_flag_present_flag u(1)
596 * num_extra_slice_header_bits u(3)
597 * sign_data_hiding_enabled_flag u(1)
598 * cabac_init_present_flag u(1)
602 get_ue_golomb_long(gb); // num_ref_idx_l0_default_active_minus1
603 get_ue_golomb_long(gb); // num_ref_idx_l1_default_active_minus1
604 get_se_golomb_long(gb); // init_qp_minus26
607 * constrained_intra_pred_flag u(1)
608 * transform_skip_enabled_flag u(1)
612 if (get_bits1(gb)) // cu_qp_delta_enabled_flag
613 get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
615 get_se_golomb_long(gb); // pps_cb_qp_offset
616 get_se_golomb_long(gb); // pps_cr_qp_offset
619 * weighted_pred_flag u(1)
620 * weighted_bipred_flag u(1)
621 * transquant_bypass_enabled_flag u(1)
625 tiles_enabled_flag = get_bits1(gb);
626 entropy_coding_sync_enabled_flag = get_bits1(gb);
628 if (entropy_coding_sync_enabled_flag && tiles_enabled_flag)
629 hvcc->parallelismType = 0; // mixed-type parallel decoding
630 else if (entropy_coding_sync_enabled_flag)
631 hvcc->parallelismType = 3; // wavefront-based parallel decoding
632 else if (tiles_enabled_flag)
633 hvcc->parallelismType = 2; // tile-based parallel decoding
635 hvcc->parallelismType = 1; // slice-based parallel decoding
637 /* nothing useful for hvcC past this point */
641 static uint8_t *nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len,
647 dst = av_malloc(src_len);
651 /* NAL unit header (2 bytes) */
653 while (i < 2 && i < src_len)
654 dst[len++] = src[i++];
656 while (i + 2 < src_len)
657 if (!src[i] && !src[i + 1] && src[i + 2] == 3) {
658 dst[len++] = src[i++];
659 dst[len++] = src[i++];
660 i++; // remove emulation_prevention_three_byte
662 dst[len++] = src[i++];
665 dst[len++] = src[i++];
673 static void nal_unit_parse_header(GetBitContext *gb, uint8_t *nal_type)
675 skip_bits1(gb); // forbidden_zero_bit
677 *nal_type = get_bits(gb, 6);
681 * nuh_temporal_id_plus1 u(3)
686 static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
687 uint8_t nal_type, int ps_array_completeness,
688 HEVCDecoderConfigurationRecord *hvcc)
693 HVCCNALUnitArray *array;
695 for (index = 0; index < hvcc->numOfArrays; index++)
696 if (hvcc->array[index].NAL_unit_type == nal_type)
699 if (index >= hvcc->numOfArrays) {
702 ret = av_reallocp_array(&hvcc->array, index + 1, sizeof(HVCCNALUnitArray));
706 for (i = hvcc->numOfArrays; i <= index; i++)
707 memset(&hvcc->array[i], 0, sizeof(HVCCNALUnitArray));
708 hvcc->numOfArrays = index + 1;
711 array = &hvcc->array[index];
712 numNalus = array->numNalus;
714 ret = av_reallocp_array(&array->nalUnit, numNalus + 1, sizeof(uint8_t*));
718 ret = av_reallocp_array(&array->nalUnitLength, numNalus + 1, sizeof(uint16_t));
722 array->nalUnit [numNalus] = nal_buf;
723 array->nalUnitLength[numNalus] = nal_size;
724 array->NAL_unit_type = nal_type;
728 * When the sample entry name is ‘hvc1’, the default and mandatory value of
729 * array_completeness is 1 for arrays of all types of parameter sets, and 0
730 * for all other arrays. When the sample entry name is ‘hev1’, the default
731 * value of array_completeness is 0 for all arrays.
733 if (nal_type == NAL_VPS || nal_type == NAL_SPS || nal_type == NAL_PPS)
734 array->array_completeness = ps_array_completeness;
739 static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
740 int ps_array_completeness,
741 HEVCDecoderConfigurationRecord *hvcc)
749 rbsp_buf = nal_unit_extract_rbsp(nal_buf, nal_size, &rbsp_size);
751 ret = AVERROR(ENOMEM);
755 ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
759 nal_unit_parse_header(&gbc, &nal_type);
762 * Note: only 'declarative' SEI messages are allowed in
763 * hvcC. Perhaps the SEI playload type should be checked
764 * and non-declarative SEI messages discarded?
772 ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type,
773 ps_array_completeness, hvcc);
776 else if (nal_type == NAL_VPS)
777 ret = hvcc_parse_vps(&gbc, hvcc);
778 else if (nal_type == NAL_SPS)
779 ret = hvcc_parse_sps(&gbc, hvcc);
780 else if (nal_type == NAL_PPS)
781 ret = hvcc_parse_pps(&gbc, hvcc);
786 ret = AVERROR_INVALIDDATA;
795 static void hvcc_init(HEVCDecoderConfigurationRecord *hvcc)
797 memset(hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
798 hvcc->configurationVersion = 1;
799 hvcc->lengthSizeMinusOne = 3; // 4 bytes
802 * The following fields have all their valid bits set by default,
803 * the ProfileTierLevel parsing code will unset them when needed.
805 hvcc->general_profile_compatibility_flags = 0xffffffff;
806 hvcc->general_constraint_indicator_flags = 0xffffffffffff;
809 * Initialize this field with an invalid value which can be used to detect
810 * whether we didn't see any VUI (in which case it should be reset to zero).
812 hvcc->min_spatial_segmentation_idc = MAX_SPATIAL_SEGMENTATION + 1;
815 static void hvcc_close(HEVCDecoderConfigurationRecord *hvcc)
819 for (i = 0; i < hvcc->numOfArrays; i++) {
820 hvcc->array[i].numNalus = 0;
821 av_freep(&hvcc->array[i].nalUnit);
822 av_freep(&hvcc->array[i].nalUnitLength);
825 hvcc->numOfArrays = 0;
826 av_freep(&hvcc->array);
829 static int hvcc_write(AVIOContext *pb, HEVCDecoderConfigurationRecord *hvcc)
832 uint16_t j, vps_count = 0, sps_count = 0, pps_count = 0;
835 * We only support writing HEVCDecoderConfigurationRecord version 1.
837 hvcc->configurationVersion = 1;
840 * If min_spatial_segmentation_idc is invalid, reset to 0 (unspecified).
842 if (hvcc->min_spatial_segmentation_idc > MAX_SPATIAL_SEGMENTATION)
843 hvcc->min_spatial_segmentation_idc = 0;
846 * parallelismType indicates the type of parallelism that is used to meet
847 * the restrictions imposed by min_spatial_segmentation_idc when the value
848 * of min_spatial_segmentation_idc is greater than 0.
850 if (!hvcc->min_spatial_segmentation_idc)
851 hvcc->parallelismType = 0;
854 * It's unclear how to properly compute these fields, so
855 * let's always set them to values meaning 'unspecified'.
857 hvcc->avgFrameRate = 0;
858 hvcc->constantFrameRate = 0;
860 av_log(NULL, AV_LOG_TRACE, "configurationVersion: %"PRIu8"\n",
861 hvcc->configurationVersion);
862 av_log(NULL, AV_LOG_TRACE, "general_profile_space: %"PRIu8"\n",
863 hvcc->general_profile_space);
864 av_log(NULL, AV_LOG_TRACE, "general_tier_flag: %"PRIu8"\n",
865 hvcc->general_tier_flag);
866 av_log(NULL, AV_LOG_TRACE, "general_profile_idc: %"PRIu8"\n",
867 hvcc->general_profile_idc);
868 av_log(NULL, AV_LOG_TRACE, "general_profile_compatibility_flags: 0x%08"PRIx32"\n",
869 hvcc->general_profile_compatibility_flags);
870 av_log(NULL, AV_LOG_TRACE, "general_constraint_indicator_flags: 0x%012"PRIx64"\n",
871 hvcc->general_constraint_indicator_flags);
872 av_log(NULL, AV_LOG_TRACE, "general_level_idc: %"PRIu8"\n",
873 hvcc->general_level_idc);
874 av_log(NULL, AV_LOG_TRACE, "min_spatial_segmentation_idc: %"PRIu16"\n",
875 hvcc->min_spatial_segmentation_idc);
876 av_log(NULL, AV_LOG_TRACE, "parallelismType: %"PRIu8"\n",
877 hvcc->parallelismType);
878 av_log(NULL, AV_LOG_TRACE, "chromaFormat: %"PRIu8"\n",
880 av_log(NULL, AV_LOG_TRACE, "bitDepthLumaMinus8: %"PRIu8"\n",
881 hvcc->bitDepthLumaMinus8);
882 av_log(NULL, AV_LOG_TRACE, "bitDepthChromaMinus8: %"PRIu8"\n",
883 hvcc->bitDepthChromaMinus8);
884 av_log(NULL, AV_LOG_TRACE, "avgFrameRate: %"PRIu16"\n",
886 av_log(NULL, AV_LOG_TRACE, "constantFrameRate: %"PRIu8"\n",
887 hvcc->constantFrameRate);
888 av_log(NULL, AV_LOG_TRACE, "numTemporalLayers: %"PRIu8"\n",
889 hvcc->numTemporalLayers);
890 av_log(NULL, AV_LOG_TRACE, "temporalIdNested: %"PRIu8"\n",
891 hvcc->temporalIdNested);
892 av_log(NULL, AV_LOG_TRACE, "lengthSizeMinusOne: %"PRIu8"\n",
893 hvcc->lengthSizeMinusOne);
894 av_log(NULL, AV_LOG_TRACE, "numOfArrays: %"PRIu8"\n",
896 for (i = 0; i < hvcc->numOfArrays; i++) {
897 av_log(NULL, AV_LOG_TRACE, "array_completeness[%"PRIu8"]: %"PRIu8"\n",
898 i, hvcc->array[i].array_completeness);
899 av_log(NULL, AV_LOG_TRACE, "NAL_unit_type[%"PRIu8"]: %"PRIu8"\n",
900 i, hvcc->array[i].NAL_unit_type);
901 av_log(NULL, AV_LOG_TRACE, "numNalus[%"PRIu8"]: %"PRIu16"\n",
902 i, hvcc->array[i].numNalus);
903 for (j = 0; j < hvcc->array[i].numNalus; j++)
904 av_log(NULL, AV_LOG_TRACE,
905 "nalUnitLength[%"PRIu8"][%"PRIu16"]: %"PRIu16"\n",
906 i, j, hvcc->array[i].nalUnitLength[j]);
910 * We need at least one of each: VPS, SPS and PPS.
912 for (i = 0; i < hvcc->numOfArrays; i++)
913 switch (hvcc->array[i].NAL_unit_type) {
915 vps_count += hvcc->array[i].numNalus;
918 sps_count += hvcc->array[i].numNalus;
921 pps_count += hvcc->array[i].numNalus;
926 if (!vps_count || vps_count > MAX_VPS_COUNT ||
927 !sps_count || sps_count > MAX_SPS_COUNT ||
928 !pps_count || pps_count > MAX_PPS_COUNT)
929 return AVERROR_INVALIDDATA;
931 /* unsigned int(8) configurationVersion = 1; */
932 avio_w8(pb, hvcc->configurationVersion);
935 * unsigned int(2) general_profile_space;
936 * unsigned int(1) general_tier_flag;
937 * unsigned int(5) general_profile_idc;
939 avio_w8(pb, hvcc->general_profile_space << 6 |
940 hvcc->general_tier_flag << 5 |
941 hvcc->general_profile_idc);
943 /* unsigned int(32) general_profile_compatibility_flags; */
944 avio_wb32(pb, hvcc->general_profile_compatibility_flags);
946 /* unsigned int(48) general_constraint_indicator_flags; */
947 avio_wb32(pb, hvcc->general_constraint_indicator_flags >> 16);
948 avio_wb16(pb, hvcc->general_constraint_indicator_flags);
950 /* unsigned int(8) general_level_idc; */
951 avio_w8(pb, hvcc->general_level_idc);
954 * bit(4) reserved = ‘1111’b;
955 * unsigned int(12) min_spatial_segmentation_idc;
957 avio_wb16(pb, hvcc->min_spatial_segmentation_idc | 0xf000);
960 * bit(6) reserved = ‘111111’b;
961 * unsigned int(2) parallelismType;
963 avio_w8(pb, hvcc->parallelismType | 0xfc);
966 * bit(6) reserved = ‘111111’b;
967 * unsigned int(2) chromaFormat;
969 avio_w8(pb, hvcc->chromaFormat | 0xfc);
972 * bit(5) reserved = ‘11111’b;
973 * unsigned int(3) bitDepthLumaMinus8;
975 avio_w8(pb, hvcc->bitDepthLumaMinus8 | 0xf8);
978 * bit(5) reserved = ‘11111’b;
979 * unsigned int(3) bitDepthChromaMinus8;
981 avio_w8(pb, hvcc->bitDepthChromaMinus8 | 0xf8);
983 /* bit(16) avgFrameRate; */
984 avio_wb16(pb, hvcc->avgFrameRate);
987 * bit(2) constantFrameRate;
988 * bit(3) numTemporalLayers;
989 * bit(1) temporalIdNested;
990 * unsigned int(2) lengthSizeMinusOne;
992 avio_w8(pb, hvcc->constantFrameRate << 6 |
993 hvcc->numTemporalLayers << 3 |
994 hvcc->temporalIdNested << 2 |
995 hvcc->lengthSizeMinusOne);
997 /* unsigned int(8) numOfArrays; */
998 avio_w8(pb, hvcc->numOfArrays);
1000 for (i = 0; i < hvcc->numOfArrays; i++) {
1002 * bit(1) array_completeness;
1003 * unsigned int(1) reserved = 0;
1004 * unsigned int(6) NAL_unit_type;
1006 avio_w8(pb, hvcc->array[i].array_completeness << 7 |
1007 hvcc->array[i].NAL_unit_type & 0x3f);
1009 /* unsigned int(16) numNalus; */
1010 avio_wb16(pb, hvcc->array[i].numNalus);
1012 for (j = 0; j < hvcc->array[i].numNalus; j++) {
1013 /* unsigned int(16) nalUnitLength; */
1014 avio_wb16(pb, hvcc->array[i].nalUnitLength[j]);
1016 /* bit(8*nalUnitLength) nalUnit; */
1017 avio_write(pb, hvcc->array[i].nalUnit[j],
1018 hvcc->array[i].nalUnitLength[j]);
1025 int ff_hevc_annexb2mp4(AVIOContext *pb, const uint8_t *buf_in,
1026 int size, int filter_ps, int *ps_count)
1028 int num_ps = 0, ret = 0;
1029 uint8_t *buf, *end, *start = NULL;
1032 ret = ff_avc_parse_nal_units(pb, buf_in, size);
1036 ret = ff_avc_parse_nal_units_buf(buf_in, &start, &size);
1044 while (end - buf > 4) {
1045 uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1046 uint8_t type = (buf[4] >> 1) & 0x3f;
1059 avio_write(pb, buf, len);
1073 int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out,
1074 int *size, int filter_ps, int *ps_count)
1079 ret = avio_open_dyn_buf(&pb);
1083 ret = ff_hevc_annexb2mp4(pb, buf_in, *size, filter_ps, ps_count);
1084 *size = avio_close_dyn_buf(pb, buf_out);
1089 int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data,
1090 int size, int ps_array_completeness)
1093 uint8_t *buf, *end, *start = NULL;
1094 HEVCDecoderConfigurationRecord hvcc;
1099 /* We can't write a valid hvcC from the provided data */
1100 ret = AVERROR_INVALIDDATA;
1102 } else if (*data == 1) {
1103 /* Data is already hvcC-formatted */
1104 avio_write(pb, data, size);
1106 } else if (!(AV_RB24(data) == 1 || AV_RB32(data) == 1)) {
1107 /* Not a valid Annex B start code prefix */
1108 ret = AVERROR_INVALIDDATA;
1112 ret = ff_avc_parse_nal_units_buf(data, &start, &size);
1119 while (end - buf > 4) {
1120 uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1121 uint8_t type = (buf[4] >> 1) & 0x3f;
1129 case NAL_SEI_PREFIX:
1130 case NAL_SEI_SUFFIX:
1131 ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc);
1142 ret = hvcc_write(pb, &hvcc);