]> git.sesse.net Git - ffmpeg/blob - libavformat/hevc.c
opus_rc: rename total_bits_used to total_bits and #define some constants
[ffmpeg] / libavformat / hevc.c
1 /*
2  * Copyright (c) 2014 Tim Walker <tdskywalker@gmail.com>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "libavcodec/get_bits.h"
22 #include "libavcodec/golomb.h"
23 #include "libavcodec/hevc.h"
24 #include "libavutil/intreadwrite.h"
25 #include "avc.h"
26 #include "avio.h"
27 #include "hevc.h"
28
29 #define MAX_SPATIAL_SEGMENTATION 4096 // max. value of u(12) field
30
31 typedef struct HVCCNALUnitArray {
32     uint8_t  array_completeness;
33     uint8_t  NAL_unit_type;
34     uint16_t numNalus;
35     uint16_t *nalUnitLength;
36     uint8_t  **nalUnit;
37 } HVCCNALUnitArray;
38
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;
49     uint8_t  chromaFormat;
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;
57     uint8_t  numOfArrays;
58     HVCCNALUnitArray *array;
59 } HEVCDecoderConfigurationRecord;
60
61 typedef struct HVCCProfileTierLevel {
62     uint8_t  profile_space;
63     uint8_t  tier_flag;
64     uint8_t  profile_idc;
65     uint32_t profile_compatibility_flags;
66     uint64_t constraint_indicator_flags;
67     uint8_t  level_idc;
68 } HVCCProfileTierLevel;
69
70 static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc,
71                             HVCCProfileTierLevel *ptl)
72 {
73     /*
74      * The value of general_profile_space in all the parameter sets must be
75      * identical.
76      */
77     hvcc->general_profile_space = ptl->profile_space;
78
79     /*
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.
83      */
84     if (hvcc->general_tier_flag < ptl->tier_flag)
85         hvcc->general_level_idc = ptl->level_idc;
86     else
87         hvcc->general_level_idc = FFMAX(hvcc->general_level_idc, ptl->level_idc);
88
89     /*
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.
92      */
93     hvcc->general_tier_flag = FFMAX(hvcc->general_tier_flag, ptl->tier_flag);
94
95     /*
96      * The profile indication general_profile_idc must indicate a profile to
97      * which the stream associated with this configuration record conforms.
98      *
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
105      * be met.
106      *
107      * Note: set the profile to the highest value for the sake of simplicity.
108      */
109     hvcc->general_profile_idc = FFMAX(hvcc->general_profile_idc, ptl->profile_idc);
110
111     /*
112      * Each bit in general_profile_compatibility_flags may only be set if all
113      * the parameter sets set that bit.
114      */
115     hvcc->general_profile_compatibility_flags &= ptl->profile_compatibility_flags;
116
117     /*
118      * Each bit in general_constraint_indicator_flags may only be set if all
119      * the parameter sets set that bit.
120      */
121     hvcc->general_constraint_indicator_flags &= ptl->constraint_indicator_flags;
122 }
123
124 static void hvcc_parse_ptl(GetBitContext *gb,
125                            HEVCDecoderConfigurationRecord *hvcc,
126                            unsigned int max_sub_layers_minus1)
127 {
128     unsigned int i;
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];
132
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);
140
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);
144     }
145
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]
149
150     for (i = 0; i < max_sub_layers_minus1; i++) {
151         if (sub_layer_profile_present_flag[i]) {
152             /*
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)
162              */
163             skip_bits_long(gb, 32);
164             skip_bits_long(gb, 32);
165             skip_bits     (gb, 24);
166         }
167
168         if (sub_layer_level_present_flag[i])
169             skip_bits(gb, 8);
170     }
171 }
172
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)
176 {
177     unsigned int i;
178
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
182
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
186         }
187
188         skip_bits1(gb); // cbr_flag
189     }
190 }
191
192 static int skip_hrd_parameters(GetBitContext *gb, uint8_t cprms_present_flag,
193                                 unsigned int max_sub_layers_minus1)
194 {
195     unsigned int i;
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;
199
200     if (cprms_present_flag) {
201         nal_hrd_parameters_present_flag = get_bits1(gb);
202         vcl_hrd_parameters_present_flag = get_bits1(gb);
203
204         if (nal_hrd_parameters_present_flag ||
205             vcl_hrd_parameters_present_flag) {
206             sub_pic_hrd_params_present_flag = get_bits1(gb);
207
208             if (sub_pic_hrd_params_present_flag)
209                 /*
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)
214                  */
215                 skip_bits(gb, 19);
216
217             /*
218              * bit_rate_scale u(4)
219              * cpb_size_scale u(4)
220              */
221             skip_bits(gb, 8);
222
223             if (sub_pic_hrd_params_present_flag)
224                 skip_bits(gb, 4); // cpb_size_du_scale
225
226             /*
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)
230              */
231             skip_bits(gb, 15);
232         }
233     }
234
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);
240
241         if (!fixed_pic_rate_general_flag)
242             fixed_pic_rate_within_cvs_flag = get_bits1(gb);
243
244         if (fixed_pic_rate_within_cvs_flag)
245             get_ue_golomb_long(gb); // elemental_duration_in_tc_minus1
246         else
247             low_delay_hrd_flag = get_bits1(gb);
248
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;
253         }
254
255         if (nal_hrd_parameters_present_flag)
256             skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
257                                           sub_pic_hrd_params_present_flag);
258
259         if (vcl_hrd_parameters_present_flag)
260             skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
261                                           sub_pic_hrd_params_present_flag);
262     }
263
264     return 0;
265 }
266
267 static void skip_timing_info(GetBitContext *gb)
268 {
269     skip_bits_long(gb, 32); // num_units_in_tick
270     skip_bits_long(gb, 32); // time_scale
271
272     if (get_bits1(gb))          // poc_proportional_to_timing_flag
273         get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1
274 }
275
276 static void hvcc_parse_vui(GetBitContext *gb,
277                            HEVCDecoderConfigurationRecord *hvcc,
278                            unsigned int max_sub_layers_minus1)
279 {
280     unsigned int min_spatial_segmentation_idc;
281
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)
285
286     if (get_bits1(gb))  // overscan_info_present_flag
287         skip_bits1(gb); // overscan_appropriate_flag
288
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)
291
292         if (get_bits1(gb)) // colour_description_present_flag
293             /*
294              * colour_primaries         u(8)
295              * transfer_characteristics u(8)
296              * matrix_coeffs            u(8)
297              */
298             skip_bits(gb, 24);
299     }
300
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
304     }
305
306     /*
307      * neutral_chroma_indication_flag u(1)
308      * field_seq_flag                 u(1)
309      * frame_field_info_present_flag  u(1)
310      */
311     skip_bits(gb, 3);
312
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
318     }
319
320     if (get_bits1(gb)) { // vui_timing_info_present_flag
321         skip_timing_info(gb);
322
323         if (get_bits1(gb)) // vui_hrd_parameters_present_flag
324             skip_hrd_parameters(gb, 1, max_sub_layers_minus1);
325     }
326
327     if (get_bits1(gb)) { // bitstream_restriction_flag
328         /*
329          * tiles_fixed_structure_flag              u(1)
330          * motion_vectors_over_pic_boundaries_flag u(1)
331          * restricted_ref_pic_lists_flag           u(1)
332          */
333         skip_bits(gb, 3);
334
335         min_spatial_segmentation_idc = get_ue_golomb_long(gb);
336
337         /*
338          * unsigned int(12) min_spatial_segmentation_idc;
339          *
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.
343          */
344         hvcc->min_spatial_segmentation_idc = FFMIN(hvcc->min_spatial_segmentation_idc,
345                                                    min_spatial_segmentation_idc);
346
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
351     }
352 }
353
354 static void skip_sub_layer_ordering_info(GetBitContext *gb)
355 {
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
359 }
360
361 static int hvcc_parse_vps(GetBitContext *gb,
362                           HEVCDecoderConfigurationRecord *hvcc)
363 {
364     unsigned int vps_max_sub_layers_minus1;
365
366     /*
367      * vps_video_parameter_set_id u(4)
368      * vps_reserved_three_2bits   u(2)
369      * vps_max_layers_minus1      u(6)
370      */
371     skip_bits(gb, 12);
372
373     vps_max_sub_layers_minus1 = get_bits(gb, 3);
374
375     /*
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.
382      */
383     hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
384                                     vps_max_sub_layers_minus1 + 1);
385
386     /*
387      * vps_temporal_id_nesting_flag u(1)
388      * vps_reserved_0xffff_16bits   u(16)
389      */
390     skip_bits(gb, 17);
391
392     hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1);
393
394     /* nothing useful for hvcC past this point */
395     return 0;
396 }
397
398 static void skip_scaling_list_data(GetBitContext *gb)
399 {
400     int i, j, k, num_coeffs;
401
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]
406             else {
407                 num_coeffs = FFMIN(64, 1 << (4 + (i << 1)));
408
409                 if (i > 1)
410                     get_se_golomb_long(gb); // scaling_list_dc_coef_minus8[i-2][j]
411
412                 for (k = 0; k < num_coeffs; k++)
413                     get_se_golomb_long(gb); // scaling_list_delta_coef
414             }
415 }
416
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])
420 {
421     unsigned int i;
422
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;
427
428         skip_bits1        (gb); // delta_rps_sign
429         get_ue_golomb_long(gb); // abs_delta_rps_minus1
430
431         num_delta_pocs[rps_idx] = 0;
432
433         /*
434          * From libavcodec/hevc_ps.c:
435          *
436          * if (is_slice_header) {
437          *    //foo
438          * } else
439          *     rps_ridx = &sps->st_rps[rps - sps->st_rps - 1];
440          *
441          * where:
442          * rps:             &sps->st_rps[rps_idx]
443          * sps->st_rps:     &sps->st_rps[0]
444          * is_slice_header: rps_idx == num_rps
445          *
446          * thus:
447          * if (num_rps != rps_idx)
448          *     rps_ridx = &sps->st_rps[rps_idx - 1];
449          *
450          * NumDeltaPocs[RefRpsIdx]: num_delta_pocs[rps_idx - 1]
451          */
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);
457
458             if (used_by_curr_pic_flag || use_delta_flag)
459                 num_delta_pocs[rps_idx]++;
460         }
461     } else {
462         unsigned int num_negative_pics = get_ue_golomb_long(gb);
463         unsigned int num_positive_pics = get_ue_golomb_long(gb);
464
465         if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > get_bits_left(gb))
466             return AVERROR_INVALIDDATA;
467
468         num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics;
469
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]
473         }
474
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]
478         }
479     }
480
481     return 0;
482 }
483
484 static int hvcc_parse_sps(GetBitContext *gb,
485                           HEVCDecoderConfigurationRecord *hvcc)
486 {
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];
489
490     skip_bits(gb, 4); // sps_video_parameter_set_id
491
492     sps_max_sub_layers_minus1 = get_bits (gb, 3);
493
494     /*
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.
501      */
502     hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
503                                     sps_max_sub_layers_minus1 + 1);
504
505     hvcc->temporalIdNested = get_bits1(gb);
506
507     hvcc_parse_ptl(gb, hvcc, sps_max_sub_layers_minus1);
508
509     get_ue_golomb_long(gb); // sps_seq_parameter_set_id
510
511     hvcc->chromaFormat = get_ue_golomb_long(gb);
512
513     if (hvcc->chromaFormat == 3)
514         skip_bits1(gb); // separate_colour_plane_flag
515
516     get_ue_golomb_long(gb); // pic_width_in_luma_samples
517     get_ue_golomb_long(gb); // pic_height_in_luma_samples
518
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
524     }
525
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);
529
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);
534
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
541
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);
545
546     skip_bits1(gb); // amp_enabled_flag
547     skip_bits1(gb); // sample_adaptive_offset_enabled_flag
548
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
555     }
556
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;
560
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);
563         if (ret < 0)
564             return ret;
565     }
566
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]
575         }
576     }
577
578     skip_bits1(gb); // sps_temporal_mvp_enabled_flag
579     skip_bits1(gb); // strong_intra_smoothing_enabled_flag
580
581     if (get_bits1(gb)) // vui_parameters_present_flag
582         hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
583
584     /* nothing useful for hvcC past this point */
585     return 0;
586 }
587
588 static int hvcc_parse_pps(GetBitContext *gb,
589                           HEVCDecoderConfigurationRecord *hvcc)
590 {
591     uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
592
593     get_ue_golomb_long(gb); // pps_pic_parameter_set_id
594     get_ue_golomb_long(gb); // pps_seq_parameter_set_id
595
596     /*
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)
602      */
603     skip_bits(gb, 7);
604
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
608
609     /*
610      * constrained_intra_pred_flag u(1)
611      * transform_skip_enabled_flag u(1)
612      */
613     skip_bits(gb, 2);
614
615     if (get_bits1(gb))          // cu_qp_delta_enabled_flag
616         get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
617
618     get_se_golomb_long(gb); // pps_cb_qp_offset
619     get_se_golomb_long(gb); // pps_cr_qp_offset
620
621     /*
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)
626      */
627     skip_bits(gb, 4);
628
629     tiles_enabled_flag               = get_bits1(gb);
630     entropy_coding_sync_enabled_flag = get_bits1(gb);
631
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
638     else
639         hvcc->parallelismType = 1; // slice-based parallel decoding
640
641     /* nothing useful for hvcC past this point */
642     return 0;
643 }
644
645 static uint8_t *nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len,
646                                       uint32_t *dst_len)
647 {
648     uint8_t *dst;
649     uint32_t i, len;
650
651     dst = av_malloc(src_len + AV_INPUT_BUFFER_PADDING_SIZE);
652     if (!dst)
653         return NULL;
654
655     /* NAL unit header (2 bytes) */
656     i = len = 0;
657     while (i < 2 && i < src_len)
658         dst[len++] = src[i++];
659
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
665         } else
666             dst[len++] = src[i++];
667
668     while (i < src_len)
669         dst[len++] = src[i++];
670
671     *dst_len = len;
672     return dst;
673 }
674
675
676
677 static void nal_unit_parse_header(GetBitContext *gb, uint8_t *nal_type)
678 {
679     skip_bits1(gb); // forbidden_zero_bit
680
681     *nal_type = get_bits(gb, 6);
682
683     /*
684      * nuh_layer_id          u(6)
685      * nuh_temporal_id_plus1 u(3)
686      */
687     skip_bits(gb, 9);
688 }
689
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)
693 {
694     int ret;
695     uint8_t index;
696     uint16_t numNalus;
697     HVCCNALUnitArray *array;
698
699     for (index = 0; index < hvcc->numOfArrays; index++)
700         if (hvcc->array[index].NAL_unit_type == nal_type)
701             break;
702
703     if (index >= hvcc->numOfArrays) {
704         uint8_t i;
705
706         ret = av_reallocp_array(&hvcc->array, index + 1, sizeof(HVCCNALUnitArray));
707         if (ret < 0)
708             return ret;
709
710         for (i = hvcc->numOfArrays; i <= index; i++)
711             memset(&hvcc->array[i], 0, sizeof(HVCCNALUnitArray));
712         hvcc->numOfArrays = index + 1;
713     }
714
715     array    = &hvcc->array[index];
716     numNalus = array->numNalus;
717
718     ret = av_reallocp_array(&array->nalUnit, numNalus + 1, sizeof(uint8_t*));
719     if (ret < 0)
720         return ret;
721
722     ret = av_reallocp_array(&array->nalUnitLength, numNalus + 1, sizeof(uint16_t));
723     if (ret < 0)
724         return ret;
725
726     array->nalUnit      [numNalus] = nal_buf;
727     array->nalUnitLength[numNalus] = nal_size;
728     array->NAL_unit_type           = nal_type;
729     array->numNalus++;
730
731     /*
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.
736      */
737     if (nal_type == NAL_VPS || nal_type == NAL_SPS || nal_type == NAL_PPS)
738         array->array_completeness = ps_array_completeness;
739
740     return 0;
741 }
742
743 static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
744                              int ps_array_completeness,
745                              HEVCDecoderConfigurationRecord *hvcc)
746 {
747     int ret = 0;
748     GetBitContext gbc;
749     uint8_t nal_type;
750     uint8_t *rbsp_buf;
751     uint32_t rbsp_size;
752
753     rbsp_buf = nal_unit_extract_rbsp(nal_buf, nal_size, &rbsp_size);
754     if (!rbsp_buf) {
755         ret = AVERROR(ENOMEM);
756         goto end;
757     }
758
759     ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
760     if (ret < 0)
761         goto end;
762
763     nal_unit_parse_header(&gbc, &nal_type);
764
765     /*
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?
769      */
770     switch (nal_type) {
771     case NAL_VPS:
772     case NAL_SPS:
773     case NAL_PPS:
774     case NAL_SEI_PREFIX:
775     case NAL_SEI_SUFFIX:
776         ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type,
777                                       ps_array_completeness, hvcc);
778         if (ret < 0)
779             goto end;
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);
786         if (ret < 0)
787             goto end;
788         break;
789     default:
790         ret = AVERROR_INVALIDDATA;
791         goto end;
792     }
793
794 end:
795     av_free(rbsp_buf);
796     return ret;
797 }
798
799 static void hvcc_init(HEVCDecoderConfigurationRecord *hvcc)
800 {
801     memset(hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
802     hvcc->configurationVersion = 1;
803     hvcc->lengthSizeMinusOne   = 3; // 4 bytes
804
805     /*
806      * The following fields have all their valid bits set by default,
807      * the ProfileTierLevel parsing code will unset them when needed.
808      */
809     hvcc->general_profile_compatibility_flags = 0xffffffff;
810     hvcc->general_constraint_indicator_flags  = 0xffffffffffff;
811
812     /*
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).
815      */
816     hvcc->min_spatial_segmentation_idc = MAX_SPATIAL_SEGMENTATION + 1;
817 }
818
819 static void hvcc_close(HEVCDecoderConfigurationRecord *hvcc)
820 {
821     uint8_t i;
822
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);
827     }
828
829     hvcc->numOfArrays = 0;
830     av_freep(&hvcc->array);
831 }
832
833 static int hvcc_write(AVIOContext *pb, HEVCDecoderConfigurationRecord *hvcc)
834 {
835     uint8_t i;
836     uint16_t j, vps_count = 0, sps_count = 0, pps_count = 0;
837
838     /*
839      * We only support writing HEVCDecoderConfigurationRecord version 1.
840      */
841     hvcc->configurationVersion = 1;
842
843     /*
844      * If min_spatial_segmentation_idc is invalid, reset to 0 (unspecified).
845      */
846     if (hvcc->min_spatial_segmentation_idc > MAX_SPATIAL_SEGMENTATION)
847         hvcc->min_spatial_segmentation_idc = 0;
848
849     /*
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.
853      */
854     if (!hvcc->min_spatial_segmentation_idc)
855         hvcc->parallelismType = 0;
856
857     /*
858      * It's unclear how to properly compute these fields, so
859      * let's always set them to values meaning 'unspecified'.
860      */
861     hvcc->avgFrameRate      = 0;
862     hvcc->constantFrameRate = 0;
863
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",
883             hvcc->chromaFormat);
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",
889             hvcc->avgFrameRate);
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",
899             hvcc->numOfArrays);
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]);
911     }
912
913     /*
914      * We need at least one of each: VPS, SPS and PPS.
915      */
916     for (i = 0; i < hvcc->numOfArrays; i++)
917         switch (hvcc->array[i].NAL_unit_type) {
918         case NAL_VPS:
919             vps_count += hvcc->array[i].numNalus;
920             break;
921         case NAL_SPS:
922             sps_count += hvcc->array[i].numNalus;
923             break;
924         case NAL_PPS:
925             pps_count += hvcc->array[i].numNalus;
926             break;
927         default:
928             break;
929         }
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;
934
935     /* unsigned int(8) configurationVersion = 1; */
936     avio_w8(pb, hvcc->configurationVersion);
937
938     /*
939      * unsigned int(2) general_profile_space;
940      * unsigned int(1) general_tier_flag;
941      * unsigned int(5) general_profile_idc;
942      */
943     avio_w8(pb, hvcc->general_profile_space << 6 |
944                 hvcc->general_tier_flag     << 5 |
945                 hvcc->general_profile_idc);
946
947     /* unsigned int(32) general_profile_compatibility_flags; */
948     avio_wb32(pb, hvcc->general_profile_compatibility_flags);
949
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);
953
954     /* unsigned int(8) general_level_idc; */
955     avio_w8(pb, hvcc->general_level_idc);
956
957     /*
958      * bit(4) reserved = ‘1111’b;
959      * unsigned int(12) min_spatial_segmentation_idc;
960      */
961     avio_wb16(pb, hvcc->min_spatial_segmentation_idc | 0xf000);
962
963     /*
964      * bit(6) reserved = ‘111111’b;
965      * unsigned int(2) parallelismType;
966      */
967     avio_w8(pb, hvcc->parallelismType | 0xfc);
968
969     /*
970      * bit(6) reserved = ‘111111’b;
971      * unsigned int(2) chromaFormat;
972      */
973     avio_w8(pb, hvcc->chromaFormat | 0xfc);
974
975     /*
976      * bit(5) reserved = ‘11111’b;
977      * unsigned int(3) bitDepthLumaMinus8;
978      */
979     avio_w8(pb, hvcc->bitDepthLumaMinus8 | 0xf8);
980
981     /*
982      * bit(5) reserved = ‘11111’b;
983      * unsigned int(3) bitDepthChromaMinus8;
984      */
985     avio_w8(pb, hvcc->bitDepthChromaMinus8 | 0xf8);
986
987     /* bit(16) avgFrameRate; */
988     avio_wb16(pb, hvcc->avgFrameRate);
989
990     /*
991      * bit(2) constantFrameRate;
992      * bit(3) numTemporalLayers;
993      * bit(1) temporalIdNested;
994      * unsigned int(2) lengthSizeMinusOne;
995      */
996     avio_w8(pb, hvcc->constantFrameRate << 6 |
997                 hvcc->numTemporalLayers << 3 |
998                 hvcc->temporalIdNested  << 2 |
999                 hvcc->lengthSizeMinusOne);
1000
1001     /* unsigned int(8) numOfArrays; */
1002     avio_w8(pb, hvcc->numOfArrays);
1003
1004     for (i = 0; i < hvcc->numOfArrays; i++) {
1005         /*
1006          * bit(1) array_completeness;
1007          * unsigned int(1) reserved = 0;
1008          * unsigned int(6) NAL_unit_type;
1009          */
1010         avio_w8(pb, hvcc->array[i].array_completeness << 7 |
1011                     hvcc->array[i].NAL_unit_type & 0x3f);
1012
1013         /* unsigned int(16) numNalus; */
1014         avio_wb16(pb, hvcc->array[i].numNalus);
1015
1016         for (j = 0; j < hvcc->array[i].numNalus; j++) {
1017             /* unsigned int(16) nalUnitLength; */
1018             avio_wb16(pb, hvcc->array[i].nalUnitLength[j]);
1019
1020             /* bit(8*nalUnitLength) nalUnit; */
1021             avio_write(pb, hvcc->array[i].nalUnit[j],
1022                        hvcc->array[i].nalUnitLength[j]);
1023         }
1024     }
1025
1026     return 0;
1027 }
1028
1029 int ff_hevc_annexb2mp4(AVIOContext *pb, const uint8_t *buf_in,
1030                        int size, int filter_ps, int *ps_count)
1031 {
1032     int num_ps = 0, ret = 0;
1033     uint8_t *buf, *end, *start = NULL;
1034
1035     if (!filter_ps) {
1036         ret = ff_avc_parse_nal_units(pb, buf_in, size);
1037         goto end;
1038     }
1039
1040     ret = ff_avc_parse_nal_units_buf(buf_in, &start, &size);
1041     if (ret < 0)
1042         goto end;
1043
1044     ret = 0;
1045     buf = start;
1046     end = start + size;
1047
1048     while (end - buf > 4) {
1049         uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1050         uint8_t type = (buf[4] >> 1) & 0x3f;
1051
1052         buf += 4;
1053
1054         switch (type) {
1055         case NAL_VPS:
1056         case NAL_SPS:
1057         case NAL_PPS:
1058             num_ps++;
1059             break;
1060         default:
1061             ret += 4 + len;
1062             avio_wb32(pb, len);
1063             avio_write(pb, buf, len);
1064             break;
1065         }
1066
1067         buf += len;
1068     }
1069
1070 end:
1071     av_free(start);
1072     if (ps_count)
1073         *ps_count = num_ps;
1074     return ret;
1075 }
1076
1077 int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out,
1078                            int *size, int filter_ps, int *ps_count)
1079 {
1080     AVIOContext *pb;
1081     int ret;
1082
1083     ret = avio_open_dyn_buf(&pb);
1084     if (ret < 0)
1085         return ret;
1086
1087     ret   = ff_hevc_annexb2mp4(pb, buf_in, *size, filter_ps, ps_count);
1088     *size = avio_close_dyn_buf(pb, buf_out);
1089
1090     return ret;
1091 }
1092
1093 int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data,
1094                        int size, int ps_array_completeness)
1095 {
1096     int ret = 0;
1097     uint8_t *buf, *end, *start = NULL;
1098     HEVCDecoderConfigurationRecord hvcc;
1099
1100     hvcc_init(&hvcc);
1101
1102     if (size < 6) {
1103         /* We can't write a valid hvcC from the provided data */
1104         ret = AVERROR_INVALIDDATA;
1105         goto end;
1106     } else if (*data == 1) {
1107         /* Data is already hvcC-formatted */
1108         avio_write(pb, data, size);
1109         goto end;
1110     } else if (!(AV_RB24(data) == 1 || AV_RB32(data) == 1)) {
1111         /* Not a valid Annex B start code prefix */
1112         ret = AVERROR_INVALIDDATA;
1113         goto end;
1114     }
1115
1116     ret = ff_avc_parse_nal_units_buf(data, &start, &size);
1117     if (ret < 0)
1118         goto end;
1119
1120     buf = start;
1121     end = start + size;
1122
1123     while (end - buf > 4) {
1124         uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
1125         uint8_t type = (buf[4] >> 1) & 0x3f;
1126
1127         buf += 4;
1128
1129         switch (type) {
1130         case NAL_VPS:
1131         case NAL_SPS:
1132         case NAL_PPS:
1133         case NAL_SEI_PREFIX:
1134         case NAL_SEI_SUFFIX:
1135             ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc);
1136             if (ret < 0)
1137                 goto end;
1138             break;
1139         default:
1140             break;
1141         }
1142
1143         buf += len;
1144     }
1145
1146     ret = hvcc_write(pb, &hvcc);
1147
1148 end:
1149     hvcc_close(&hvcc);
1150     av_free(start);
1151     return ret;
1152 }