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 unsigned num_long_term_ref_pics_sps = get_ue_golomb_long(gb);
569 if (num_long_term_ref_pics_sps > 31U)
570 return AVERROR_INVALIDDATA;
571 for (i = 0; i < num_long_term_ref_pics_sps; i++) { // num_long_term_ref_pics_sps
572 int len = FFMIN(log2_max_pic_order_cnt_lsb_minus4 + 4, 16);
573 skip_bits (gb, len); // lt_ref_pic_poc_lsb_sps[i]
574 skip_bits1(gb); // used_by_curr_pic_lt_sps_flag[i]
578 skip_bits1(gb); // sps_temporal_mvp_enabled_flag
579 skip_bits1(gb); // strong_intra_smoothing_enabled_flag
581 if (get_bits1(gb)) // vui_parameters_present_flag
582 hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
584 /* nothing useful for hvcC past this point */
588 static int hvcc_parse_pps(GetBitContext *gb,
589 HEVCDecoderConfigurationRecord *hvcc)
591 uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
593 get_ue_golomb_long(gb); // pps_pic_parameter_set_id
594 get_ue_golomb_long(gb); // pps_seq_parameter_set_id
597 * dependent_slice_segments_enabled_flag u(1)
598 * output_flag_present_flag u(1)
599 * num_extra_slice_header_bits u(3)
600 * sign_data_hiding_enabled_flag u(1)
601 * cabac_init_present_flag u(1)
605 get_ue_golomb_long(gb); // num_ref_idx_l0_default_active_minus1
606 get_ue_golomb_long(gb); // num_ref_idx_l1_default_active_minus1
607 get_se_golomb_long(gb); // init_qp_minus26
610 * constrained_intra_pred_flag u(1)
611 * transform_skip_enabled_flag u(1)
615 if (get_bits1(gb)) // cu_qp_delta_enabled_flag
616 get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
618 get_se_golomb_long(gb); // pps_cb_qp_offset
619 get_se_golomb_long(gb); // pps_cr_qp_offset
622 * pps_slice_chroma_qp_offsets_present_flag u(1)
623 * weighted_pred_flag u(1)
624 * weighted_bipred_flag u(1)
625 * transquant_bypass_enabled_flag u(1)
629 tiles_enabled_flag = get_bits1(gb);
630 entropy_coding_sync_enabled_flag = get_bits1(gb);
632 if (entropy_coding_sync_enabled_flag && tiles_enabled_flag)
633 hvcc->parallelismType = 0; // mixed-type parallel decoding
634 else if (entropy_coding_sync_enabled_flag)
635 hvcc->parallelismType = 3; // wavefront-based parallel decoding
636 else if (tiles_enabled_flag)
637 hvcc->parallelismType = 2; // tile-based parallel decoding
639 hvcc->parallelismType = 1; // slice-based parallel decoding
641 /* nothing useful for hvcC past this point */
645 static uint8_t *nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len,
651 dst = av_malloc(src_len + AV_INPUT_BUFFER_PADDING_SIZE);
655 /* NAL unit header (2 bytes) */
657 while (i < 2 && i < src_len)
658 dst[len++] = src[i++];
660 while (i + 2 < src_len)
661 if (!src[i] && !src[i + 1] && src[i + 2] == 3) {
662 dst[len++] = src[i++];
663 dst[len++] = src[i++];
664 i++; // remove emulation_prevention_three_byte
666 dst[len++] = src[i++];
669 dst[len++] = src[i++];
677 static void nal_unit_parse_header(GetBitContext *gb, uint8_t *nal_type)
679 skip_bits1(gb); // forbidden_zero_bit
681 *nal_type = get_bits(gb, 6);
685 * nuh_temporal_id_plus1 u(3)
690 static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
691 uint8_t nal_type, int ps_array_completeness,
692 HEVCDecoderConfigurationRecord *hvcc)
697 HVCCNALUnitArray *array;
699 for (index = 0; index < hvcc->numOfArrays; index++)
700 if (hvcc->array[index].NAL_unit_type == nal_type)
703 if (index >= hvcc->numOfArrays) {
706 ret = av_reallocp_array(&hvcc->array, index + 1, sizeof(HVCCNALUnitArray));
710 for (i = hvcc->numOfArrays; i <= index; i++)
711 memset(&hvcc->array[i], 0, sizeof(HVCCNALUnitArray));
712 hvcc->numOfArrays = index + 1;
715 array = &hvcc->array[index];
716 numNalus = array->numNalus;
718 ret = av_reallocp_array(&array->nalUnit, numNalus + 1, sizeof(uint8_t*));
722 ret = av_reallocp_array(&array->nalUnitLength, numNalus + 1, sizeof(uint16_t));
726 array->nalUnit [numNalus] = nal_buf;
727 array->nalUnitLength[numNalus] = nal_size;
728 array->NAL_unit_type = nal_type;
732 * When the sample entry name is ‘hvc1’, the default and mandatory value of
733 * array_completeness is 1 for arrays of all types of parameter sets, and 0
734 * for all other arrays. When the sample entry name is ‘hev1’, the default
735 * value of array_completeness is 0 for all arrays.
737 if (nal_type == NAL_VPS || nal_type == NAL_SPS || nal_type == NAL_PPS)
738 array->array_completeness = ps_array_completeness;
743 static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
744 int ps_array_completeness,
745 HEVCDecoderConfigurationRecord *hvcc)
753 rbsp_buf = nal_unit_extract_rbsp(nal_buf, nal_size, &rbsp_size);
755 ret = AVERROR(ENOMEM);
759 ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
763 nal_unit_parse_header(&gbc, &nal_type);
766 * Note: only 'declarative' SEI messages are allowed in
767 * hvcC. Perhaps the SEI playload type should be checked
768 * and non-declarative SEI messages discarded?
776 ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type,
777 ps_array_completeness, hvcc);
780 else if (nal_type == NAL_VPS)
781 ret = hvcc_parse_vps(&gbc, hvcc);
782 else if (nal_type == NAL_SPS)
783 ret = hvcc_parse_sps(&gbc, hvcc);
784 else if (nal_type == NAL_PPS)
785 ret = hvcc_parse_pps(&gbc, hvcc);
790 ret = AVERROR_INVALIDDATA;
799 static void hvcc_init(HEVCDecoderConfigurationRecord *hvcc)
801 memset(hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
802 hvcc->configurationVersion = 1;
803 hvcc->lengthSizeMinusOne = 3; // 4 bytes
806 * The following fields have all their valid bits set by default,
807 * the ProfileTierLevel parsing code will unset them when needed.
809 hvcc->general_profile_compatibility_flags = 0xffffffff;
810 hvcc->general_constraint_indicator_flags = 0xffffffffffff;
813 * Initialize this field with an invalid value which can be used to detect
814 * whether we didn't see any VUI (in which case it should be reset to zero).
816 hvcc->min_spatial_segmentation_idc = MAX_SPATIAL_SEGMENTATION + 1;
819 static void hvcc_close(HEVCDecoderConfigurationRecord *hvcc)
823 for (i = 0; i < hvcc->numOfArrays; i++) {
824 hvcc->array[i].numNalus = 0;
825 av_freep(&hvcc->array[i].nalUnit);
826 av_freep(&hvcc->array[i].nalUnitLength);
829 hvcc->numOfArrays = 0;
830 av_freep(&hvcc->array);
833 static int hvcc_write(AVIOContext *pb, HEVCDecoderConfigurationRecord *hvcc)
836 uint16_t j, vps_count = 0, sps_count = 0, pps_count = 0;
839 * We only support writing HEVCDecoderConfigurationRecord version 1.
841 hvcc->configurationVersion = 1;
844 * If min_spatial_segmentation_idc is invalid, reset to 0 (unspecified).
846 if (hvcc->min_spatial_segmentation_idc > MAX_SPATIAL_SEGMENTATION)
847 hvcc->min_spatial_segmentation_idc = 0;
850 * parallelismType indicates the type of parallelism that is used to meet
851 * the restrictions imposed by min_spatial_segmentation_idc when the value
852 * of min_spatial_segmentation_idc is greater than 0.
854 if (!hvcc->min_spatial_segmentation_idc)
855 hvcc->parallelismType = 0;
858 * It's unclear how to properly compute these fields, so
859 * let's always set them to values meaning 'unspecified'.
861 hvcc->avgFrameRate = 0;
862 hvcc->constantFrameRate = 0;
864 av_log(NULL, AV_LOG_TRACE, "configurationVersion: %"PRIu8"\n",
865 hvcc->configurationVersion);
866 av_log(NULL, AV_LOG_TRACE, "general_profile_space: %"PRIu8"\n",
867 hvcc->general_profile_space);
868 av_log(NULL, AV_LOG_TRACE, "general_tier_flag: %"PRIu8"\n",
869 hvcc->general_tier_flag);
870 av_log(NULL, AV_LOG_TRACE, "general_profile_idc: %"PRIu8"\n",
871 hvcc->general_profile_idc);
872 av_log(NULL, AV_LOG_TRACE, "general_profile_compatibility_flags: 0x%08"PRIx32"\n",
873 hvcc->general_profile_compatibility_flags);
874 av_log(NULL, AV_LOG_TRACE, "general_constraint_indicator_flags: 0x%012"PRIx64"\n",
875 hvcc->general_constraint_indicator_flags);
876 av_log(NULL, AV_LOG_TRACE, "general_level_idc: %"PRIu8"\n",
877 hvcc->general_level_idc);
878 av_log(NULL, AV_LOG_TRACE, "min_spatial_segmentation_idc: %"PRIu16"\n",
879 hvcc->min_spatial_segmentation_idc);
880 av_log(NULL, AV_LOG_TRACE, "parallelismType: %"PRIu8"\n",
881 hvcc->parallelismType);
882 av_log(NULL, AV_LOG_TRACE, "chromaFormat: %"PRIu8"\n",
884 av_log(NULL, AV_LOG_TRACE, "bitDepthLumaMinus8: %"PRIu8"\n",
885 hvcc->bitDepthLumaMinus8);
886 av_log(NULL, AV_LOG_TRACE, "bitDepthChromaMinus8: %"PRIu8"\n",
887 hvcc->bitDepthChromaMinus8);
888 av_log(NULL, AV_LOG_TRACE, "avgFrameRate: %"PRIu16"\n",
890 av_log(NULL, AV_LOG_TRACE, "constantFrameRate: %"PRIu8"\n",
891 hvcc->constantFrameRate);
892 av_log(NULL, AV_LOG_TRACE, "numTemporalLayers: %"PRIu8"\n",
893 hvcc->numTemporalLayers);
894 av_log(NULL, AV_LOG_TRACE, "temporalIdNested: %"PRIu8"\n",
895 hvcc->temporalIdNested);
896 av_log(NULL, AV_LOG_TRACE, "lengthSizeMinusOne: %"PRIu8"\n",
897 hvcc->lengthSizeMinusOne);
898 av_log(NULL, AV_LOG_TRACE, "numOfArrays: %"PRIu8"\n",
900 for (i = 0; i < hvcc->numOfArrays; i++) {
901 av_log(NULL, AV_LOG_TRACE, "array_completeness[%"PRIu8"]: %"PRIu8"\n",
902 i, hvcc->array[i].array_completeness);
903 av_log(NULL, AV_LOG_TRACE, "NAL_unit_type[%"PRIu8"]: %"PRIu8"\n",
904 i, hvcc->array[i].NAL_unit_type);
905 av_log(NULL, AV_LOG_TRACE, "numNalus[%"PRIu8"]: %"PRIu16"\n",
906 i, hvcc->array[i].numNalus);
907 for (j = 0; j < hvcc->array[i].numNalus; j++)
908 av_log(NULL, AV_LOG_TRACE,
909 "nalUnitLength[%"PRIu8"][%"PRIu16"]: %"PRIu16"\n",
910 i, j, hvcc->array[i].nalUnitLength[j]);
914 * We need at least one of each: VPS, SPS and PPS.
916 for (i = 0; i < hvcc->numOfArrays; i++)
917 switch (hvcc->array[i].NAL_unit_type) {
919 vps_count += hvcc->array[i].numNalus;
922 sps_count += hvcc->array[i].numNalus;
925 pps_count += hvcc->array[i].numNalus;
930 if (!vps_count || vps_count > MAX_VPS_COUNT ||
931 !sps_count || sps_count > MAX_SPS_COUNT ||
932 !pps_count || pps_count > MAX_PPS_COUNT)
933 return AVERROR_INVALIDDATA;
935 /* unsigned int(8) configurationVersion = 1; */
936 avio_w8(pb, hvcc->configurationVersion);
939 * unsigned int(2) general_profile_space;
940 * unsigned int(1) general_tier_flag;
941 * unsigned int(5) general_profile_idc;
943 avio_w8(pb, hvcc->general_profile_space << 6 |
944 hvcc->general_tier_flag << 5 |
945 hvcc->general_profile_idc);
947 /* unsigned int(32) general_profile_compatibility_flags; */
948 avio_wb32(pb, hvcc->general_profile_compatibility_flags);
950 /* unsigned int(48) general_constraint_indicator_flags; */
951 avio_wb32(pb, hvcc->general_constraint_indicator_flags >> 16);
952 avio_wb16(pb, hvcc->general_constraint_indicator_flags);
954 /* unsigned int(8) general_level_idc; */
955 avio_w8(pb, hvcc->general_level_idc);
958 * bit(4) reserved = ‘1111’b;
959 * unsigned int(12) min_spatial_segmentation_idc;
961 avio_wb16(pb, hvcc->min_spatial_segmentation_idc | 0xf000);
964 * bit(6) reserved = ‘111111’b;
965 * unsigned int(2) parallelismType;
967 avio_w8(pb, hvcc->parallelismType | 0xfc);
970 * bit(6) reserved = ‘111111’b;
971 * unsigned int(2) chromaFormat;
973 avio_w8(pb, hvcc->chromaFormat | 0xfc);
976 * bit(5) reserved = ‘11111’b;
977 * unsigned int(3) bitDepthLumaMinus8;
979 avio_w8(pb, hvcc->bitDepthLumaMinus8 | 0xf8);
982 * bit(5) reserved = ‘11111’b;
983 * unsigned int(3) bitDepthChromaMinus8;
985 avio_w8(pb, hvcc->bitDepthChromaMinus8 | 0xf8);
987 /* bit(16) avgFrameRate; */
988 avio_wb16(pb, hvcc->avgFrameRate);
991 * bit(2) constantFrameRate;
992 * bit(3) numTemporalLayers;
993 * bit(1) temporalIdNested;
994 * unsigned int(2) lengthSizeMinusOne;
996 avio_w8(pb, hvcc->constantFrameRate << 6 |
997 hvcc->numTemporalLayers << 3 |
998 hvcc->temporalIdNested << 2 |
999 hvcc->lengthSizeMinusOne);
1001 /* unsigned int(8) numOfArrays; */
1002 avio_w8(pb, hvcc->numOfArrays);
1004 for (i = 0; i < hvcc->numOfArrays; i++) {
1006 * bit(1) array_completeness;
1007 * unsigned int(1) reserved = 0;
1008 * unsigned int(6) NAL_unit_type;
1010 avio_w8(pb, hvcc->array[i].array_completeness << 7 |
1011 hvcc->array[i].NAL_unit_type & 0x3f);
1013 /* unsigned int(16) numNalus; */
1014 avio_wb16(pb, hvcc->array[i].numNalus);
1016 for (j = 0; j < hvcc->array[i].numNalus; j++) {
1017 /* unsigned int(16) nalUnitLength; */
1018 avio_wb16(pb, hvcc->array[i].nalUnitLength[j]);
1020 /* bit(8*nalUnitLength) nalUnit; */
1021 avio_write(pb, hvcc->array[i].nalUnit[j],
1022 hvcc->array[i].nalUnitLength[j]);
1029 int ff_hevc_annexb2mp4(AVIOContext *pb, const uint8_t *buf_in,
1030 int size, int filter_ps, int *ps_count)
1032 int num_ps = 0, ret = 0;
1033 uint8_t *buf, *end, *start = NULL;
1036 ret = ff_avc_parse_nal_units(pb, buf_in, size);
1040 ret = ff_avc_parse_nal_units_buf(buf_in, &start, &size);
1048 while (end - buf > 4) {
1049 uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1050 uint8_t type = (buf[4] >> 1) & 0x3f;
1063 avio_write(pb, buf, len);
1077 int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out,
1078 int *size, int filter_ps, int *ps_count)
1083 ret = avio_open_dyn_buf(&pb);
1087 ret = ff_hevc_annexb2mp4(pb, buf_in, *size, filter_ps, ps_count);
1088 *size = avio_close_dyn_buf(pb, buf_out);
1093 int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data,
1094 int size, int ps_array_completeness)
1097 uint8_t *buf, *end, *start = NULL;
1098 HEVCDecoderConfigurationRecord hvcc;
1103 /* We can't write a valid hvcC from the provided data */
1104 ret = AVERROR_INVALIDDATA;
1106 } else if (*data == 1) {
1107 /* Data is already hvcC-formatted */
1108 avio_write(pb, data, size);
1110 } else if (!(AV_RB24(data) == 1 || AV_RB32(data) == 1)) {
1111 /* Not a valid Annex B start code prefix */
1112 ret = AVERROR_INVALIDDATA;
1116 ret = ff_avc_parse_nal_units_buf(data, &start, &size);
1123 while (end - buf > 4) {
1124 uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1125 uint8_t type = (buf[4] >> 1) & 0x3f;
1133 case NAL_SEI_PREFIX:
1134 case NAL_SEI_SUFFIX:
1135 ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc);
1146 ret = hvcc_write(pb, &hvcc);