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