]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264_ps.c
Merge commit 'a08b5d7b5725932f4ad39e95c5d6589392dee2c6'
[ffmpeg] / libavcodec / h264_ps.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... parameter set decoding
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * H.264 / AVC / MPEG4 part10 parameter set decoding.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include <inttypes.h>
29
30 #include "libavutil/imgutils.h"
31 #include "internal.h"
32 #include "mathops.h"
33 #include "avcodec.h"
34 #include "h264.h"
35 #include "h264data.h"
36 #include "golomb.h"
37
38 #define MAX_LOG2_MAX_FRAME_NUM    (12 + 4)
39 #define MIN_LOG2_MAX_FRAME_NUM    4
40
41 static const uint8_t default_scaling4[2][16] = {
42     {  6, 13, 20, 28, 13, 20, 28, 32,
43       20, 28, 32, 37, 28, 32, 37, 42 },
44     { 10, 14, 20, 24, 14, 20, 24, 27,
45       20, 24, 27, 30, 24, 27, 30, 34 }
46 };
47
48 static const uint8_t default_scaling8[2][64] = {
49     {  6, 10, 13, 16, 18, 23, 25, 27,
50       10, 11, 16, 18, 23, 25, 27, 29,
51       13, 16, 18, 23, 25, 27, 29, 31,
52       16, 18, 23, 25, 27, 29, 31, 33,
53       18, 23, 25, 27, 29, 31, 33, 36,
54       23, 25, 27, 29, 31, 33, 36, 38,
55       25, 27, 29, 31, 33, 36, 38, 40,
56       27, 29, 31, 33, 36, 38, 40, 42 },
57     {  9, 13, 15, 17, 19, 21, 22, 24,
58       13, 13, 17, 19, 21, 22, 24, 25,
59       15, 17, 19, 21, 22, 24, 25, 27,
60       17, 19, 21, 22, 24, 25, 27, 28,
61       19, 21, 22, 24, 25, 27, 28, 30,
62       21, 22, 24, 25, 27, 28, 30, 32,
63       22, 24, 25, 27, 28, 30, 32, 33,
64       24, 25, 27, 28, 30, 32, 33, 35 }
65 };
66
67 /* maximum number of MBs in the DPB for a given level */
68 static const int level_max_dpb_mbs[][2] = {
69     { 10, 396       },
70     { 11, 900       },
71     { 12, 2376      },
72     { 13, 2376      },
73     { 20, 2376      },
74     { 21, 4752      },
75     { 22, 8100      },
76     { 30, 8100      },
77     { 31, 18000     },
78     { 32, 20480     },
79     { 40, 32768     },
80     { 41, 32768     },
81     { 42, 34816     },
82     { 50, 110400    },
83     { 51, 184320    },
84     { 52, 184320    },
85 };
86
87 static inline int decode_hrd_parameters(H264Context *h, SPS *sps)
88 {
89     int cpb_count, i;
90     cpb_count = get_ue_golomb_31(&h->gb) + 1;
91
92     if (cpb_count > 32U) {
93         av_log(h->avctx, AV_LOG_ERROR, "cpb_count %d invalid\n", cpb_count);
94         return AVERROR_INVALIDDATA;
95     }
96
97     get_bits(&h->gb, 4); /* bit_rate_scale */
98     get_bits(&h->gb, 4); /* cpb_size_scale */
99     for (i = 0; i < cpb_count; i++) {
100         get_ue_golomb_long(&h->gb); /* bit_rate_value_minus1 */
101         get_ue_golomb_long(&h->gb); /* cpb_size_value_minus1 */
102         get_bits1(&h->gb);          /* cbr_flag */
103     }
104     sps->initial_cpb_removal_delay_length = get_bits(&h->gb, 5) + 1;
105     sps->cpb_removal_delay_length         = get_bits(&h->gb, 5) + 1;
106     sps->dpb_output_delay_length          = get_bits(&h->gb, 5) + 1;
107     sps->time_offset_length               = get_bits(&h->gb, 5);
108     sps->cpb_cnt                          = cpb_count;
109     return 0;
110 }
111
112 static inline int decode_vui_parameters(H264Context *h, SPS *sps)
113 {
114     int aspect_ratio_info_present_flag;
115     unsigned int aspect_ratio_idc;
116
117     aspect_ratio_info_present_flag = get_bits1(&h->gb);
118
119     if (aspect_ratio_info_present_flag) {
120         aspect_ratio_idc = get_bits(&h->gb, 8);
121         if (aspect_ratio_idc == EXTENDED_SAR) {
122             sps->sar.num = get_bits(&h->gb, 16);
123             sps->sar.den = get_bits(&h->gb, 16);
124         } else if (aspect_ratio_idc < FF_ARRAY_ELEMS(ff_h264_pixel_aspect)) {
125             sps->sar = ff_h264_pixel_aspect[aspect_ratio_idc];
126         } else {
127             av_log(h->avctx, AV_LOG_ERROR, "illegal aspect ratio\n");
128             return AVERROR_INVALIDDATA;
129         }
130     } else {
131         sps->sar.num =
132         sps->sar.den = 0;
133     }
134
135     if (get_bits1(&h->gb))      /* overscan_info_present_flag */
136         get_bits1(&h->gb);      /* overscan_appropriate_flag */
137
138     sps->video_signal_type_present_flag = get_bits1(&h->gb);
139     if (sps->video_signal_type_present_flag) {
140         get_bits(&h->gb, 3);                 /* video_format */
141         sps->full_range = get_bits1(&h->gb); /* video_full_range_flag */
142
143         sps->colour_description_present_flag = get_bits1(&h->gb);
144         if (sps->colour_description_present_flag) {
145             sps->color_primaries = get_bits(&h->gb, 8); /* colour_primaries */
146             sps->color_trc       = get_bits(&h->gb, 8); /* transfer_characteristics */
147             sps->colorspace      = get_bits(&h->gb, 8); /* matrix_coefficients */
148             if (sps->color_primaries >= AVCOL_PRI_NB)
149                 sps->color_primaries = AVCOL_PRI_UNSPECIFIED;
150             if (sps->color_trc >= AVCOL_TRC_NB)
151                 sps->color_trc = AVCOL_TRC_UNSPECIFIED;
152             if (sps->colorspace >= AVCOL_SPC_NB)
153                 sps->colorspace = AVCOL_SPC_UNSPECIFIED;
154         }
155     }
156
157     /* chroma_location_info_present_flag */
158     if (get_bits1(&h->gb)) {
159         /* chroma_sample_location_type_top_field */
160         h->avctx->chroma_sample_location = get_ue_golomb(&h->gb) + 1;
161         get_ue_golomb(&h->gb);  /* chroma_sample_location_type_bottom_field */
162     }
163
164     if (show_bits1(&h->gb) && get_bits_left(&h->gb) < 10) {
165         av_log(h->avctx, AV_LOG_WARNING, "Truncated VUI\n");
166         return 0;
167     }
168
169     sps->timing_info_present_flag = get_bits1(&h->gb);
170     if (sps->timing_info_present_flag) {
171         unsigned num_units_in_tick = get_bits_long(&h->gb, 32);
172         unsigned time_scale        = get_bits_long(&h->gb, 32);
173         if (!num_units_in_tick || !time_scale) {
174             av_log(h->avctx, AV_LOG_ERROR,
175                    "time_scale/num_units_in_tick invalid or unsupported (%u/%u)\n",
176                    time_scale, num_units_in_tick);
177             sps->timing_info_present_flag = 0;
178         } else {
179             sps->num_units_in_tick = num_units_in_tick;
180             sps->time_scale = time_scale;
181         }
182         sps->fixed_frame_rate_flag = get_bits1(&h->gb);
183     }
184
185     sps->nal_hrd_parameters_present_flag = get_bits1(&h->gb);
186     if (sps->nal_hrd_parameters_present_flag)
187         if (decode_hrd_parameters(h, sps) < 0)
188             return AVERROR_INVALIDDATA;
189     sps->vcl_hrd_parameters_present_flag = get_bits1(&h->gb);
190     if (sps->vcl_hrd_parameters_present_flag)
191         if (decode_hrd_parameters(h, sps) < 0)
192             return AVERROR_INVALIDDATA;
193     if (sps->nal_hrd_parameters_present_flag ||
194         sps->vcl_hrd_parameters_present_flag)
195         get_bits1(&h->gb);     /* low_delay_hrd_flag */
196     sps->pic_struct_present_flag = get_bits1(&h->gb);
197     if (!get_bits_left(&h->gb))
198         return 0;
199     sps->bitstream_restriction_flag = get_bits1(&h->gb);
200     if (sps->bitstream_restriction_flag) {
201         get_bits1(&h->gb);     /* motion_vectors_over_pic_boundaries_flag */
202         get_ue_golomb(&h->gb); /* max_bytes_per_pic_denom */
203         get_ue_golomb(&h->gb); /* max_bits_per_mb_denom */
204         get_ue_golomb(&h->gb); /* log2_max_mv_length_horizontal */
205         get_ue_golomb(&h->gb); /* log2_max_mv_length_vertical */
206         sps->num_reorder_frames = get_ue_golomb(&h->gb);
207         get_ue_golomb(&h->gb); /*max_dec_frame_buffering*/
208
209         if (get_bits_left(&h->gb) < 0) {
210             sps->num_reorder_frames         = 0;
211             sps->bitstream_restriction_flag = 0;
212         }
213
214         if (sps->num_reorder_frames > 16U
215             /* max_dec_frame_buffering || max_dec_frame_buffering > 16 */) {
216             av_log(h->avctx, AV_LOG_ERROR,
217                    "Clipping illegal num_reorder_frames %d\n",
218                    sps->num_reorder_frames);
219             sps->num_reorder_frames = 16;
220             return AVERROR_INVALIDDATA;
221         }
222     }
223
224     return 0;
225 }
226
227 static void decode_scaling_list(H264Context *h, uint8_t *factors, int size,
228                                 const uint8_t *jvt_list,
229                                 const uint8_t *fallback_list)
230 {
231     int i, last = 8, next = 8;
232     const uint8_t *scan = size == 16 ? ff_zigzag_scan : ff_zigzag_direct;
233     if (!get_bits1(&h->gb)) /* matrix not written, we use the predicted one */
234         memcpy(factors, fallback_list, size * sizeof(uint8_t));
235     else
236         for (i = 0; i < size; i++) {
237             if (next)
238                 next = (last + get_se_golomb(&h->gb)) & 0xff;
239             if (!i && !next) { /* matrix not written, we use the preset one */
240                 memcpy(factors, jvt_list, size * sizeof(uint8_t));
241                 break;
242             }
243             last = factors[scan[i]] = next ? next : last;
244         }
245 }
246
247 static void decode_scaling_matrices(H264Context *h, SPS *sps,
248                                     PPS *pps, int is_sps,
249                                     uint8_t(*scaling_matrix4)[16],
250                                     uint8_t(*scaling_matrix8)[64])
251 {
252     int fallback_sps = !is_sps && sps->scaling_matrix_present;
253     const uint8_t *fallback[4] = {
254         fallback_sps ? sps->scaling_matrix4[0] : default_scaling4[0],
255         fallback_sps ? sps->scaling_matrix4[3] : default_scaling4[1],
256         fallback_sps ? sps->scaling_matrix8[0] : default_scaling8[0],
257         fallback_sps ? sps->scaling_matrix8[3] : default_scaling8[1]
258     };
259     if (get_bits1(&h->gb)) {
260         sps->scaling_matrix_present |= is_sps;
261         decode_scaling_list(h, scaling_matrix4[0], 16, default_scaling4[0], fallback[0]);        // Intra, Y
262         decode_scaling_list(h, scaling_matrix4[1], 16, default_scaling4[0], scaling_matrix4[0]); // Intra, Cr
263         decode_scaling_list(h, scaling_matrix4[2], 16, default_scaling4[0], scaling_matrix4[1]); // Intra, Cb
264         decode_scaling_list(h, scaling_matrix4[3], 16, default_scaling4[1], fallback[1]);        // Inter, Y
265         decode_scaling_list(h, scaling_matrix4[4], 16, default_scaling4[1], scaling_matrix4[3]); // Inter, Cr
266         decode_scaling_list(h, scaling_matrix4[5], 16, default_scaling4[1], scaling_matrix4[4]); // Inter, Cb
267         if (is_sps || pps->transform_8x8_mode) {
268             decode_scaling_list(h, scaling_matrix8[0], 64, default_scaling8[0], fallback[2]); // Intra, Y
269             decode_scaling_list(h, scaling_matrix8[3], 64, default_scaling8[1], fallback[3]); // Inter, Y
270             if (sps->chroma_format_idc == 3) {
271                 decode_scaling_list(h, scaling_matrix8[1], 64, default_scaling8[0], scaling_matrix8[0]); // Intra, Cr
272                 decode_scaling_list(h, scaling_matrix8[4], 64, default_scaling8[1], scaling_matrix8[3]); // Inter, Cr
273                 decode_scaling_list(h, scaling_matrix8[2], 64, default_scaling8[0], scaling_matrix8[1]); // Intra, Cb
274                 decode_scaling_list(h, scaling_matrix8[5], 64, default_scaling8[1], scaling_matrix8[4]); // Inter, Cb
275             }
276         }
277     }
278 }
279
280 int ff_h264_decode_seq_parameter_set(H264Context *h, int ignore_truncation)
281 {
282     int profile_idc, level_idc, constraint_set_flags = 0;
283     unsigned int sps_id;
284     int i, log2_max_frame_num_minus4;
285     SPS *sps;
286
287     sps = av_mallocz(sizeof(SPS));
288     if (!sps)
289         return AVERROR(ENOMEM);
290
291     sps->data_size = h->gb.buffer_end - h->gb.buffer;
292     if (sps->data_size > sizeof(sps->data)) {
293         av_log(h->avctx, AV_LOG_WARNING, "Truncating likely oversized SPS\n");
294         sps->data_size = sizeof(sps->data);
295     }
296     memcpy(sps->data, h->gb.buffer, sps->data_size);
297
298     profile_idc           = get_bits(&h->gb, 8);
299     constraint_set_flags |= get_bits1(&h->gb) << 0;   // constraint_set0_flag
300     constraint_set_flags |= get_bits1(&h->gb) << 1;   // constraint_set1_flag
301     constraint_set_flags |= get_bits1(&h->gb) << 2;   // constraint_set2_flag
302     constraint_set_flags |= get_bits1(&h->gb) << 3;   // constraint_set3_flag
303     constraint_set_flags |= get_bits1(&h->gb) << 4;   // constraint_set4_flag
304     constraint_set_flags |= get_bits1(&h->gb) << 5;   // constraint_set5_flag
305     skip_bits(&h->gb, 2);                             // reserved_zero_2bits
306     level_idc = get_bits(&h->gb, 8);
307     sps_id    = get_ue_golomb_31(&h->gb);
308
309     if (sps_id >= MAX_SPS_COUNT) {
310         av_log(h->avctx, AV_LOG_ERROR, "sps_id %u out of range\n", sps_id);
311         goto fail;
312     }
313
314     sps->sps_id               = sps_id;
315     sps->time_offset_length   = 24;
316     sps->profile_idc          = profile_idc;
317     sps->constraint_set_flags = constraint_set_flags;
318     sps->level_idc            = level_idc;
319     sps->full_range           = -1;
320
321     memset(sps->scaling_matrix4, 16, sizeof(sps->scaling_matrix4));
322     memset(sps->scaling_matrix8, 16, sizeof(sps->scaling_matrix8));
323     sps->scaling_matrix_present = 0;
324     sps->colorspace = 2; //AVCOL_SPC_UNSPECIFIED
325
326     if (sps->profile_idc == 100 ||  // High profile
327         sps->profile_idc == 110 ||  // High10 profile
328         sps->profile_idc == 122 ||  // High422 profile
329         sps->profile_idc == 244 ||  // High444 Predictive profile
330         sps->profile_idc ==  44 ||  // Cavlc444 profile
331         sps->profile_idc ==  83 ||  // Scalable Constrained High profile (SVC)
332         sps->profile_idc ==  86 ||  // Scalable High Intra profile (SVC)
333         sps->profile_idc == 118 ||  // Stereo High profile (MVC)
334         sps->profile_idc == 128 ||  // Multiview High profile (MVC)
335         sps->profile_idc == 138 ||  // Multiview Depth High profile (MVCD)
336         sps->profile_idc == 144) {  // old High444 profile
337         sps->chroma_format_idc = get_ue_golomb_31(&h->gb);
338         if (sps->chroma_format_idc > 3U) {
339             avpriv_request_sample(h->avctx, "chroma_format_idc %u",
340                                   sps->chroma_format_idc);
341             goto fail;
342         } else if (sps->chroma_format_idc == 3) {
343             sps->residual_color_transform_flag = get_bits1(&h->gb);
344             if (sps->residual_color_transform_flag) {
345                 av_log(h->avctx, AV_LOG_ERROR, "separate color planes are not supported\n");
346                 goto fail;
347             }
348         }
349         sps->bit_depth_luma   = get_ue_golomb(&h->gb) + 8;
350         sps->bit_depth_chroma = get_ue_golomb(&h->gb) + 8;
351         if (sps->bit_depth_chroma != sps->bit_depth_luma) {
352             avpriv_request_sample(h->avctx,
353                                   "Different chroma and luma bit depth");
354             goto fail;
355         }
356         if (sps->bit_depth_luma   < 8 || sps->bit_depth_luma   > 14 ||
357             sps->bit_depth_chroma < 8 || sps->bit_depth_chroma > 14) {
358             av_log(h->avctx, AV_LOG_ERROR, "illegal bit depth value (%d, %d)\n",
359                    sps->bit_depth_luma, sps->bit_depth_chroma);
360             goto fail;
361         }
362         sps->transform_bypass = get_bits1(&h->gb);
363         decode_scaling_matrices(h, sps, NULL, 1,
364                                 sps->scaling_matrix4, sps->scaling_matrix8);
365     } else {
366         sps->chroma_format_idc = 1;
367         sps->bit_depth_luma    = 8;
368         sps->bit_depth_chroma  = 8;
369     }
370
371     log2_max_frame_num_minus4 = get_ue_golomb(&h->gb);
372     if (log2_max_frame_num_minus4 < MIN_LOG2_MAX_FRAME_NUM - 4 ||
373         log2_max_frame_num_minus4 > MAX_LOG2_MAX_FRAME_NUM - 4) {
374         av_log(h->avctx, AV_LOG_ERROR,
375                "log2_max_frame_num_minus4 out of range (0-12): %d\n",
376                log2_max_frame_num_minus4);
377         goto fail;
378     }
379     sps->log2_max_frame_num = log2_max_frame_num_minus4 + 4;
380
381     sps->poc_type = get_ue_golomb_31(&h->gb);
382
383     if (sps->poc_type == 0) { // FIXME #define
384         unsigned t = get_ue_golomb(&h->gb);
385         if (t>12) {
386             av_log(h->avctx, AV_LOG_ERROR, "log2_max_poc_lsb (%d) is out of range\n", t);
387             goto fail;
388         }
389         sps->log2_max_poc_lsb = t + 4;
390     } else if (sps->poc_type == 1) { // FIXME #define
391         sps->delta_pic_order_always_zero_flag = get_bits1(&h->gb);
392         sps->offset_for_non_ref_pic           = get_se_golomb(&h->gb);
393         sps->offset_for_top_to_bottom_field   = get_se_golomb(&h->gb);
394         sps->poc_cycle_length                 = get_ue_golomb(&h->gb);
395
396         if ((unsigned)sps->poc_cycle_length >=
397             FF_ARRAY_ELEMS(sps->offset_for_ref_frame)) {
398             av_log(h->avctx, AV_LOG_ERROR,
399                    "poc_cycle_length overflow %d\n", sps->poc_cycle_length);
400             goto fail;
401         }
402
403         for (i = 0; i < sps->poc_cycle_length; i++)
404             sps->offset_for_ref_frame[i] = get_se_golomb(&h->gb);
405     } else if (sps->poc_type != 2) {
406         av_log(h->avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);
407         goto fail;
408     }
409
410     sps->ref_frame_count = get_ue_golomb_31(&h->gb);
411     if (h->avctx->codec_tag == MKTAG('S', 'M', 'V', '2'))
412         sps->ref_frame_count = FFMAX(2, sps->ref_frame_count);
413     if (sps->ref_frame_count > H264_MAX_PICTURE_COUNT - 2 ||
414         sps->ref_frame_count > 16U) {
415         av_log(h->avctx, AV_LOG_ERROR,
416                "too many reference frames %d\n", sps->ref_frame_count);
417         goto fail;
418     }
419     sps->gaps_in_frame_num_allowed_flag = get_bits1(&h->gb);
420     sps->mb_width                       = get_ue_golomb(&h->gb) + 1;
421     sps->mb_height                      = get_ue_golomb(&h->gb) + 1;
422     if ((unsigned)sps->mb_width  >= INT_MAX / 16 ||
423         (unsigned)sps->mb_height >= INT_MAX / 16 ||
424         av_image_check_size(16 * sps->mb_width,
425                             16 * sps->mb_height, 0, h->avctx)) {
426         av_log(h->avctx, AV_LOG_ERROR, "mb_width/height overflow\n");
427         goto fail;
428     }
429
430     sps->frame_mbs_only_flag = get_bits1(&h->gb);
431     if (!sps->frame_mbs_only_flag)
432         sps->mb_aff = get_bits1(&h->gb);
433     else
434         sps->mb_aff = 0;
435
436     sps->direct_8x8_inference_flag = get_bits1(&h->gb);
437
438 #ifndef ALLOW_INTERLACE
439     if (sps->mb_aff)
440         av_log(h->avctx, AV_LOG_ERROR,
441                "MBAFF support not included; enable it at compile-time.\n");
442 #endif
443     sps->crop = get_bits1(&h->gb);
444     if (sps->crop) {
445         unsigned int crop_left   = get_ue_golomb(&h->gb);
446         unsigned int crop_right  = get_ue_golomb(&h->gb);
447         unsigned int crop_top    = get_ue_golomb(&h->gb);
448         unsigned int crop_bottom = get_ue_golomb(&h->gb);
449         int width  = 16 * sps->mb_width;
450         int height = 16 * sps->mb_height * (2 - sps->frame_mbs_only_flag);
451
452         if (h->avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {
453             av_log(h->avctx, AV_LOG_DEBUG, "discarding sps cropping, original "
454                                            "values are l:%d r:%d t:%d b:%d\n",
455                    crop_left, crop_right, crop_top, crop_bottom);
456
457             sps->crop_left   =
458             sps->crop_right  =
459             sps->crop_top    =
460             sps->crop_bottom = 0;
461         } else {
462             int vsub   = (sps->chroma_format_idc == 1) ? 1 : 0;
463             int hsub   = (sps->chroma_format_idc == 1 ||
464                           sps->chroma_format_idc == 2) ? 1 : 0;
465             int step_x = 1 << hsub;
466             int step_y = (2 - sps->frame_mbs_only_flag) << vsub;
467
468             if (crop_left & (0x1F >> (sps->bit_depth_luma > 8)) &&
469                 !(h->avctx->flags & AV_CODEC_FLAG_UNALIGNED)) {
470                 crop_left &= ~(0x1F >> (sps->bit_depth_luma > 8));
471                 av_log(h->avctx, AV_LOG_WARNING,
472                        "Reducing left cropping to %d "
473                        "chroma samples to preserve alignment.\n",
474                        crop_left);
475             }
476
477             if (crop_left  > (unsigned)INT_MAX / 4 / step_x ||
478                 crop_right > (unsigned)INT_MAX / 4 / step_x ||
479                 crop_top   > (unsigned)INT_MAX / 4 / step_y ||
480                 crop_bottom> (unsigned)INT_MAX / 4 / step_y ||
481                 (crop_left + crop_right ) * step_x >= width ||
482                 (crop_top  + crop_bottom) * step_y >= height
483             ) {
484                 av_log(h->avctx, AV_LOG_ERROR, "crop values invalid %d %d %d %d / %d %d\n", crop_left, crop_right, crop_top, crop_bottom, width, height);
485                 goto fail;
486             }
487
488             sps->crop_left   = crop_left   * step_x;
489             sps->crop_right  = crop_right  * step_x;
490             sps->crop_top    = crop_top    * step_y;
491             sps->crop_bottom = crop_bottom * step_y;
492         }
493     } else {
494         sps->crop_left   =
495         sps->crop_right  =
496         sps->crop_top    =
497         sps->crop_bottom =
498         sps->crop        = 0;
499     }
500
501     sps->vui_parameters_present_flag = get_bits1(&h->gb);
502     if (sps->vui_parameters_present_flag) {
503         int ret = decode_vui_parameters(h, sps);
504         if (ret < 0)
505             goto fail;
506     }
507
508     if (get_bits_left(&h->gb) < 0) {
509         av_log(h->avctx, ignore_truncation ? AV_LOG_WARNING : AV_LOG_ERROR,
510                "Overread %s by %d bits\n", sps->vui_parameters_present_flag ? "VUI" : "SPS", -get_bits_left(&h->gb));
511         if (!ignore_truncation)
512             goto fail;
513     }
514
515     /* if the maximum delay is not stored in the SPS, derive it based on the
516      * level */
517     if (!sps->bitstream_restriction_flag) {
518         sps->num_reorder_frames = MAX_DELAYED_PIC_COUNT - 1;
519         for (i = 0; i < FF_ARRAY_ELEMS(level_max_dpb_mbs); i++) {
520             if (level_max_dpb_mbs[i][0] == sps->level_idc) {
521                 sps->num_reorder_frames = FFMIN(level_max_dpb_mbs[i][1] / (sps->mb_width * sps->mb_height),
522                                                 sps->num_reorder_frames);
523                 break;
524             }
525         }
526     }
527
528     if (!sps->sar.den)
529         sps->sar.den = 1;
530
531     if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
532         static const char csp[4][5] = { "Gray", "420", "422", "444" };
533         av_log(h->avctx, AV_LOG_DEBUG,
534                "sps:%u profile:%d/%d poc:%d ref:%d %dx%d %s %s crop:%u/%u/%u/%u %s %s %"PRId32"/%"PRId32" b%d reo:%d\n",
535                sps_id, sps->profile_idc, sps->level_idc,
536                sps->poc_type,
537                sps->ref_frame_count,
538                sps->mb_width, sps->mb_height,
539                sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),
540                sps->direct_8x8_inference_flag ? "8B8" : "",
541                sps->crop_left, sps->crop_right,
542                sps->crop_top, sps->crop_bottom,
543                sps->vui_parameters_present_flag ? "VUI" : "",
544                csp[sps->chroma_format_idc],
545                sps->timing_info_present_flag ? sps->num_units_in_tick : 0,
546                sps->timing_info_present_flag ? sps->time_scale : 0,
547                sps->bit_depth_luma,
548                sps->bitstream_restriction_flag ? sps->num_reorder_frames : -1
549                );
550     }
551     sps->new = 1;
552
553     av_free(h->sps_buffers[sps_id]);
554     h->sps_buffers[sps_id] = sps;
555
556     return 0;
557
558 fail:
559     av_free(sps);
560     return AVERROR_INVALIDDATA;
561 }
562
563 static void build_qp_table(PPS *pps, int t, int index, const int depth)
564 {
565     int i;
566     const int max_qp = 51 + 6 * (depth - 8);
567     for (i = 0; i < max_qp + 1; i++)
568         pps->chroma_qp_table[t][i] =
569             ff_h264_chroma_qp[depth - 8][av_clip(i + index, 0, max_qp)];
570 }
571
572 static int more_rbsp_data_in_pps(H264Context *h, PPS *pps)
573 {
574     const SPS *sps = h->sps_buffers[pps->sps_id];
575     int profile_idc = sps->profile_idc;
576
577     if ((profile_idc == 66 || profile_idc == 77 ||
578          profile_idc == 88) && (sps->constraint_set_flags & 7)) {
579         av_log(h->avctx, AV_LOG_VERBOSE,
580                "Current profile doesn't provide more RBSP data in PPS, skipping\n");
581         return 0;
582     }
583
584     return 1;
585 }
586
587 int ff_h264_decode_picture_parameter_set(H264Context *h, int bit_length)
588 {
589     const SPS *sps;
590     unsigned int pps_id = get_ue_golomb(&h->gb);
591     PPS *pps;
592     int qp_bd_offset;
593     int bits_left;
594     int ret;
595
596     if (pps_id >= MAX_PPS_COUNT) {
597         av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
598         return AVERROR_INVALIDDATA;
599     }
600
601     pps = av_mallocz(sizeof(PPS));
602     if (!pps)
603         return AVERROR(ENOMEM);
604     pps->data_size = h->gb.buffer_end - h->gb.buffer;
605     if (pps->data_size > sizeof(pps->data)) {
606         av_log(h->avctx, AV_LOG_WARNING, "Truncating likely oversized PPS\n");
607         pps->data_size = sizeof(pps->data);
608     }
609     memcpy(pps->data, h->gb.buffer, pps->data_size);
610     pps->sps_id = get_ue_golomb_31(&h->gb);
611     if ((unsigned)pps->sps_id >= MAX_SPS_COUNT ||
612         !h->sps_buffers[pps->sps_id]) {
613         av_log(h->avctx, AV_LOG_ERROR, "sps_id %u out of range\n", pps->sps_id);
614         ret = AVERROR_INVALIDDATA;
615         goto fail;
616     }
617     sps = h->sps_buffers[pps->sps_id];
618     if (sps->bit_depth_luma > 14) {
619         av_log(h->avctx, AV_LOG_ERROR,
620                "Invalid luma bit depth=%d\n",
621                sps->bit_depth_luma);
622         ret = AVERROR_INVALIDDATA;
623         goto fail;
624     } else if (sps->bit_depth_luma == 11 || sps->bit_depth_luma == 13) {
625         av_log(h->avctx, AV_LOG_ERROR,
626                "Unimplemented luma bit depth=%d\n",
627                sps->bit_depth_luma);
628         ret = AVERROR_PATCHWELCOME;
629         goto fail;
630     }
631
632     pps->cabac             = get_bits1(&h->gb);
633     pps->pic_order_present = get_bits1(&h->gb);
634     pps->slice_group_count = get_ue_golomb(&h->gb) + 1;
635     if (pps->slice_group_count > 1) {
636         pps->mb_slice_group_map_type = get_ue_golomb(&h->gb);
637         av_log(h->avctx, AV_LOG_ERROR, "FMO not supported\n");
638         switch (pps->mb_slice_group_map_type) {
639         case 0:
640 #if 0
641     |       for (i = 0; i <= num_slice_groups_minus1; i++)  |   |      |
642     |           run_length[i]                               |1  |ue(v) |
643 #endif
644             break;
645         case 2:
646 #if 0
647     |       for (i = 0; i < num_slice_groups_minus1; i++) { |   |      |
648     |           top_left_mb[i]                              |1  |ue(v) |
649     |           bottom_right_mb[i]                          |1  |ue(v) |
650     |       }                                               |   |      |
651 #endif
652             break;
653         case 3:
654         case 4:
655         case 5:
656 #if 0
657     |       slice_group_change_direction_flag               |1  |u(1)  |
658     |       slice_group_change_rate_minus1                  |1  |ue(v) |
659 #endif
660             break;
661         case 6:
662 #if 0
663     |       slice_group_id_cnt_minus1                       |1  |ue(v) |
664     |       for (i = 0; i <= slice_group_id_cnt_minus1; i++)|   |      |
665     |           slice_group_id[i]                           |1  |u(v)  |
666 #endif
667             break;
668         }
669     }
670     pps->ref_count[0] = get_ue_golomb(&h->gb) + 1;
671     pps->ref_count[1] = get_ue_golomb(&h->gb) + 1;
672     if (pps->ref_count[0] - 1 > 32 - 1 || pps->ref_count[1] - 1 > 32 - 1) {
673         av_log(h->avctx, AV_LOG_ERROR, "reference overflow (pps)\n");
674         ret = AVERROR_INVALIDDATA;
675         goto fail;
676     }
677
678     qp_bd_offset = 6 * (sps->bit_depth_luma - 8);
679
680     pps->weighted_pred                        = get_bits1(&h->gb);
681     pps->weighted_bipred_idc                  = get_bits(&h->gb, 2);
682     pps->init_qp                              = get_se_golomb(&h->gb) + 26 + qp_bd_offset;
683     pps->init_qs                              = get_se_golomb(&h->gb) + 26 + qp_bd_offset;
684     pps->chroma_qp_index_offset[0]            = get_se_golomb(&h->gb);
685     pps->deblocking_filter_parameters_present = get_bits1(&h->gb);
686     pps->constrained_intra_pred               = get_bits1(&h->gb);
687     pps->redundant_pic_cnt_present            = get_bits1(&h->gb);
688
689     pps->transform_8x8_mode = 0;
690     // contents of sps/pps can change even if id doesn't, so reinit
691     h->dequant_coeff_pps = -1;
692     memcpy(pps->scaling_matrix4, h->sps_buffers[pps->sps_id]->scaling_matrix4,
693            sizeof(pps->scaling_matrix4));
694     memcpy(pps->scaling_matrix8, h->sps_buffers[pps->sps_id]->scaling_matrix8,
695            sizeof(pps->scaling_matrix8));
696
697     bits_left = bit_length - get_bits_count(&h->gb);
698     if (bits_left > 0 && more_rbsp_data_in_pps(h, pps)) {
699         pps->transform_8x8_mode = get_bits1(&h->gb);
700         decode_scaling_matrices(h, h->sps_buffers[pps->sps_id], pps, 0,
701                                 pps->scaling_matrix4, pps->scaling_matrix8);
702         // second_chroma_qp_index_offset
703         pps->chroma_qp_index_offset[1] = get_se_golomb(&h->gb);
704     } else {
705         pps->chroma_qp_index_offset[1] = pps->chroma_qp_index_offset[0];
706     }
707
708     build_qp_table(pps, 0, pps->chroma_qp_index_offset[0],
709                    sps->bit_depth_luma);
710     build_qp_table(pps, 1, pps->chroma_qp_index_offset[1],
711                    sps->bit_depth_luma);
712     if (pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1])
713         pps->chroma_qp_diff = 1;
714
715     if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
716         av_log(h->avctx, AV_LOG_DEBUG,
717                "pps:%u sps:%u %s slice_groups:%d ref:%u/%u %s qp:%d/%d/%d/%d %s %s %s %s\n",
718                pps_id, pps->sps_id,
719                pps->cabac ? "CABAC" : "CAVLC",
720                pps->slice_group_count,
721                pps->ref_count[0], pps->ref_count[1],
722                pps->weighted_pred ? "weighted" : "",
723                pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1],
724                pps->deblocking_filter_parameters_present ? "LPAR" : "",
725                pps->constrained_intra_pred ? "CONSTR" : "",
726                pps->redundant_pic_cnt_present ? "REDU" : "",
727                pps->transform_8x8_mode ? "8x8DCT" : "");
728     }
729
730     av_free(h->pps_buffers[pps_id]);
731     h->pps_buffers[pps_id] = pps;
732     return 0;
733
734 fail:
735     av_free(pps);
736     return ret;
737 }