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