]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264_parse.c
qsv: Add ability to create a session from a device
[ffmpeg] / libavcodec / h264_parse.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include "bytestream.h"
20 #include "get_bits.h"
21 #include "golomb.h"
22 #include "h264.h"
23 #include "h264dec.h"
24 #include "h264_parse.h"
25 #include "h264_ps.h"
26
27 int ff_h264_pred_weight_table(GetBitContext *gb, const SPS *sps,
28                               const int *ref_count, int slice_type_nos,
29                               H264PredWeightTable *pwt,
30                               int picture_structure, void *logctx)
31 {
32     int list, i, j;
33     int luma_def, chroma_def;
34
35     pwt->use_weight             = 0;
36     pwt->use_weight_chroma      = 0;
37     pwt->luma_log2_weight_denom = get_ue_golomb(gb);
38     if (sps->chroma_format_idc)
39         pwt->chroma_log2_weight_denom = get_ue_golomb(gb);
40
41     if (pwt->luma_log2_weight_denom > 7U) {
42         av_log(logctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", pwt->luma_log2_weight_denom);
43         pwt->luma_log2_weight_denom = 0;
44     }
45     if (pwt->chroma_log2_weight_denom > 7U) {
46         av_log(logctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", pwt->chroma_log2_weight_denom);
47         pwt->chroma_log2_weight_denom = 0;
48     }
49
50     luma_def   = 1 << pwt->luma_log2_weight_denom;
51     chroma_def = 1 << pwt->chroma_log2_weight_denom;
52
53     for (list = 0; list < 2; list++) {
54         pwt->luma_weight_flag[list]   = 0;
55         pwt->chroma_weight_flag[list] = 0;
56         for (i = 0; i < ref_count[list]; i++) {
57             int luma_weight_flag, chroma_weight_flag;
58
59             luma_weight_flag = get_bits1(gb);
60             if (luma_weight_flag) {
61                 pwt->luma_weight[i][list][0] = get_se_golomb(gb);
62                 pwt->luma_weight[i][list][1] = get_se_golomb(gb);
63                 if ((int8_t)pwt->luma_weight[i][list][0] != pwt->luma_weight[i][list][0] ||
64                     (int8_t)pwt->luma_weight[i][list][1] != pwt->luma_weight[i][list][1])
65                     goto out_range_weight;
66                 if (pwt->luma_weight[i][list][0] != luma_def ||
67                     pwt->luma_weight[i][list][1] != 0) {
68                     pwt->use_weight             = 1;
69                     pwt->luma_weight_flag[list] = 1;
70                 }
71             } else {
72                 pwt->luma_weight[i][list][0] = luma_def;
73                 pwt->luma_weight[i][list][1] = 0;
74             }
75
76             if (sps->chroma_format_idc) {
77                 chroma_weight_flag = get_bits1(gb);
78                 if (chroma_weight_flag) {
79                     int j;
80                     for (j = 0; j < 2; j++) {
81                         pwt->chroma_weight[i][list][j][0] = get_se_golomb(gb);
82                         pwt->chroma_weight[i][list][j][1] = get_se_golomb(gb);
83                         if ((int8_t)pwt->chroma_weight[i][list][j][0] != pwt->chroma_weight[i][list][j][0] ||
84                             (int8_t)pwt->chroma_weight[i][list][j][1] != pwt->chroma_weight[i][list][j][1])
85                             goto out_range_weight;
86                         if (pwt->chroma_weight[i][list][j][0] != chroma_def ||
87                             pwt->chroma_weight[i][list][j][1] != 0) {
88                             pwt->use_weight_chroma        = 1;
89                             pwt->chroma_weight_flag[list] = 1;
90                         }
91                     }
92                 } else {
93                     int j;
94                     for (j = 0; j < 2; j++) {
95                         pwt->chroma_weight[i][list][j][0] = chroma_def;
96                         pwt->chroma_weight[i][list][j][1] = 0;
97                     }
98                 }
99             }
100
101             // for MBAFF
102             if (picture_structure == PICT_FRAME) {
103                 pwt->luma_weight[16 + 2 * i][list][0] = pwt->luma_weight[16 + 2 * i + 1][list][0] = pwt->luma_weight[i][list][0];
104                 pwt->luma_weight[16 + 2 * i][list][1] = pwt->luma_weight[16 + 2 * i + 1][list][1] = pwt->luma_weight[i][list][1];
105                 for (j = 0; j < 2; j++) {
106                     pwt->chroma_weight[16 + 2 * i][list][j][0] = pwt->chroma_weight[16 + 2 * i + 1][list][j][0] = pwt->chroma_weight[i][list][j][0];
107                     pwt->chroma_weight[16 + 2 * i][list][j][1] = pwt->chroma_weight[16 + 2 * i + 1][list][j][1] = pwt->chroma_weight[i][list][j][1];
108                 }
109             }
110         }
111         if (slice_type_nos != AV_PICTURE_TYPE_B)
112             break;
113     }
114     pwt->use_weight = pwt->use_weight || pwt->use_weight_chroma;
115     return 0;
116 out_range_weight:
117     avpriv_request_sample(logctx, "Out of range weight\n");
118     return AVERROR_INVALIDDATA;
119 }
120
121 /**
122  * Check if the top & left blocks are available if needed and
123  * change the dc mode so it only uses the available blocks.
124  */
125 int ff_h264_check_intra4x4_pred_mode(int8_t *pred_mode_cache, void *logctx,
126                                      int top_samples_available, int left_samples_available)
127 {
128     static const int8_t top[12] = {
129         -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
130     };
131     static const int8_t left[12] = {
132         0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
133     };
134     int i;
135
136     if (!(top_samples_available & 0x8000)) {
137         for (i = 0; i < 4; i++) {
138             int status = top[pred_mode_cache[scan8[0] + i]];
139             if (status < 0) {
140                 av_log(logctx, AV_LOG_ERROR,
141                        "top block unavailable for requested intra mode %d\n",
142                        status);
143                 return AVERROR_INVALIDDATA;
144             } else if (status) {
145                 pred_mode_cache[scan8[0] + i] = status;
146             }
147         }
148     }
149
150     if ((left_samples_available & 0x8888) != 0x8888) {
151         static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
152         for (i = 0; i < 4; i++)
153             if (!(left_samples_available & mask[i])) {
154                 int status = left[pred_mode_cache[scan8[0] + 8 * i]];
155                 if (status < 0) {
156                     av_log(logctx, AV_LOG_ERROR,
157                            "left block unavailable for requested intra4x4 mode %d\n",
158                            status);
159                     return AVERROR_INVALIDDATA;
160                 } else if (status) {
161                     pred_mode_cache[scan8[0] + 8 * i] = status;
162                 }
163             }
164     }
165
166     return 0;
167 }
168
169 /**
170  * Check if the top & left blocks are available if needed and
171  * change the dc mode so it only uses the available blocks.
172  */
173 int ff_h264_check_intra_pred_mode(void *logctx, int top_samples_available,
174                                   int left_samples_available,
175                                   int mode, int is_chroma)
176 {
177     static const int8_t top[4]  = { LEFT_DC_PRED8x8, 1, -1, -1 };
178     static const int8_t left[5] = { TOP_DC_PRED8x8, -1,  2, -1, DC_128_PRED8x8 };
179
180     if (mode > 3U) {
181         av_log(logctx, AV_LOG_ERROR,
182                "out of range intra chroma pred mode\n");
183         return AVERROR_INVALIDDATA;
184     }
185
186     if (!(top_samples_available & 0x8000)) {
187         mode = top[mode];
188         if (mode < 0) {
189             av_log(logctx, AV_LOG_ERROR,
190                    "top block unavailable for requested intra mode\n");
191             return AVERROR_INVALIDDATA;
192         }
193     }
194
195     if ((left_samples_available & 0x8080) != 0x8080) {
196         mode = left[mode];
197         if (mode < 0) {
198             av_log(logctx, AV_LOG_ERROR,
199                    "left block unavailable for requested intra mode\n");
200             return AVERROR_INVALIDDATA;
201         }
202         if (is_chroma && (left_samples_available & 0x8080)) {
203             // mad cow disease mode, aka MBAFF + constrained_intra_pred
204             mode = ALZHEIMER_DC_L0T_PRED8x8 +
205                    (!(left_samples_available & 0x8000)) +
206                    2 * (mode == DC_128_PRED8x8);
207         }
208     }
209
210     return mode;
211 }
212
213 int ff_h264_parse_ref_count(int *plist_count, int ref_count[2],
214                             GetBitContext *gb, const PPS *pps,
215                             int slice_type_nos, int picture_structure, void *logctx)
216 {
217     int list_count;
218     int num_ref_idx_active_override_flag;
219
220     // set defaults, might be overridden a few lines later
221     ref_count[0] = pps->ref_count[0];
222     ref_count[1] = pps->ref_count[1];
223
224     if (slice_type_nos != AV_PICTURE_TYPE_I) {
225         unsigned max[2];
226         max[0] = max[1] = picture_structure == PICT_FRAME ? 15 : 31;
227
228         num_ref_idx_active_override_flag = get_bits1(gb);
229
230         if (num_ref_idx_active_override_flag) {
231             ref_count[0] = get_ue_golomb(gb) + 1;
232             if (slice_type_nos == AV_PICTURE_TYPE_B) {
233                 ref_count[1] = get_ue_golomb(gb) + 1;
234             } else
235                 // full range is spec-ok in this case, even for frames
236                 ref_count[1] = 1;
237         }
238
239         if (ref_count[0] - 1 > max[0] || ref_count[1] - 1 > max[1]) {
240             av_log(logctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n",
241                    ref_count[0] - 1, max[0], ref_count[1] - 1, max[1]);
242             ref_count[0] = ref_count[1] = 0;
243             *plist_count = 0;
244             goto fail;
245         }
246
247         if (slice_type_nos == AV_PICTURE_TYPE_B)
248             list_count = 2;
249         else
250             list_count = 1;
251     } else {
252         list_count   = 0;
253         ref_count[0] = ref_count[1] = 0;
254     }
255
256     *plist_count = list_count;
257
258     return 0;
259 fail:
260     *plist_count = 0;
261     ref_count[0] = 0;
262     ref_count[1] = 0;
263     return AVERROR_INVALIDDATA;
264 }
265
266 int ff_h264_init_poc(int pic_field_poc[2], int *pic_poc,
267                      const SPS *sps, H264POCContext *pc,
268                      int picture_structure, int nal_ref_idc)
269 {
270     const int max_frame_num = 1 << sps->log2_max_frame_num;
271     int field_poc[2];
272
273     pc->frame_num_offset = pc->prev_frame_num_offset;
274     if (pc->frame_num < pc->prev_frame_num)
275         pc->frame_num_offset += max_frame_num;
276
277     if (sps->poc_type == 0) {
278         const int max_poc_lsb = 1 << sps->log2_max_poc_lsb;
279
280         if (pc->poc_lsb < pc->prev_poc_lsb &&
281             pc->prev_poc_lsb - pc->poc_lsb >= max_poc_lsb / 2)
282             pc->poc_msb = pc->prev_poc_msb + max_poc_lsb;
283         else if (pc->poc_lsb > pc->prev_poc_lsb &&
284                  pc->prev_poc_lsb - pc->poc_lsb < -max_poc_lsb / 2)
285             pc->poc_msb = pc->prev_poc_msb - max_poc_lsb;
286         else
287             pc->poc_msb = pc->prev_poc_msb;
288         field_poc[0] =
289         field_poc[1] = pc->poc_msb + pc->poc_lsb;
290         if (picture_structure == PICT_FRAME)
291             field_poc[1] += pc->delta_poc_bottom;
292     } else if (sps->poc_type == 1) {
293         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
294         int i;
295
296         if (sps->poc_cycle_length != 0)
297             abs_frame_num = pc->frame_num_offset + pc->frame_num;
298         else
299             abs_frame_num = 0;
300
301         if (nal_ref_idc == 0 && abs_frame_num > 0)
302             abs_frame_num--;
303
304         expected_delta_per_poc_cycle = 0;
305         for (i = 0; i < sps->poc_cycle_length; i++)
306             // FIXME integrate during sps parse
307             expected_delta_per_poc_cycle += sps->offset_for_ref_frame[i];
308
309         if (abs_frame_num > 0) {
310             int poc_cycle_cnt          = (abs_frame_num - 1) / sps->poc_cycle_length;
311             int frame_num_in_poc_cycle = (abs_frame_num - 1) % sps->poc_cycle_length;
312
313             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
314             for (i = 0; i <= frame_num_in_poc_cycle; i++)
315                 expectedpoc = expectedpoc + sps->offset_for_ref_frame[i];
316         } else
317             expectedpoc = 0;
318
319         if (nal_ref_idc == 0)
320             expectedpoc = expectedpoc + sps->offset_for_non_ref_pic;
321
322         field_poc[0] = expectedpoc + pc->delta_poc[0];
323         field_poc[1] = field_poc[0] + sps->offset_for_top_to_bottom_field;
324
325         if (picture_structure == PICT_FRAME)
326             field_poc[1] += pc->delta_poc[1];
327     } else {
328         int poc = 2 * (pc->frame_num_offset + pc->frame_num);
329
330         if (!nal_ref_idc)
331             poc--;
332
333         field_poc[0] = poc;
334         field_poc[1] = poc;
335     }
336
337     if (picture_structure != PICT_BOTTOM_FIELD)
338         pic_field_poc[0] = field_poc[0];
339     if (picture_structure != PICT_TOP_FIELD)
340         pic_field_poc[1] = field_poc[1];
341     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
342
343     return 0;
344 }
345
346 static int decode_extradata_ps(const uint8_t *data, int size, H264ParamSets *ps,
347                                int is_avc, void *logctx)
348 {
349     H2645Packet pkt = { 0 };
350     int i, ret = 0;
351
352     ret = ff_h2645_packet_split(&pkt, data, size, logctx, is_avc, 2, AV_CODEC_ID_H264, 1);
353     if (ret < 0) {
354         ret = 0;
355         goto fail;
356     }
357
358     for (i = 0; i < pkt.nb_nals; i++) {
359         H2645NAL *nal = &pkt.nals[i];
360         switch (nal->type) {
361         case H264_NAL_SPS:
362             ret = ff_h264_decode_seq_parameter_set(&nal->gb, logctx, ps, 0);
363             if (ret < 0)
364                 goto fail;
365             break;
366         case H264_NAL_PPS:
367             ret = ff_h264_decode_picture_parameter_set(&nal->gb, logctx, ps,
368                                                        nal->size_bits);
369             if (ret < 0)
370                 goto fail;
371             break;
372         default:
373             av_log(logctx, AV_LOG_VERBOSE, "Ignoring NAL type %d in extradata\n",
374                    nal->type);
375             break;
376         }
377     }
378
379 fail:
380     ff_h2645_packet_uninit(&pkt);
381     return ret;
382 }
383
384 /* There are (invalid) samples in the wild with mp4-style extradata, where the
385  * parameter sets are stored unescaped (i.e. as RBSP).
386  * This function catches the parameter set decoding failure and tries again
387  * after escaping it */
388 static int decode_extradata_ps_mp4(const uint8_t *buf, int buf_size, H264ParamSets *ps,
389                                    int err_recognition, void *logctx)
390 {
391     int ret;
392
393     ret = decode_extradata_ps(buf, buf_size, ps, 1, logctx);
394     if (ret < 0 && !(err_recognition & AV_EF_EXPLODE)) {
395         GetByteContext gbc;
396         PutByteContext pbc;
397         uint8_t *escaped_buf;
398         int escaped_buf_size;
399
400         av_log(logctx, AV_LOG_WARNING,
401                "SPS decoding failure, trying again after escaping the NAL\n");
402
403         if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
404             return AVERROR(ERANGE);
405         escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
406         escaped_buf = av_mallocz(escaped_buf_size);
407         if (!escaped_buf)
408             return AVERROR(ENOMEM);
409
410         bytestream2_init(&gbc, buf, buf_size);
411         bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
412
413         while (bytestream2_get_bytes_left(&gbc)) {
414             if (bytestream2_get_bytes_left(&gbc) >= 3 &&
415                 bytestream2_peek_be24(&gbc) <= 3) {
416                 bytestream2_put_be24(&pbc, 3);
417                 bytestream2_skip(&gbc, 2);
418             } else
419                 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
420         }
421
422         escaped_buf_size = bytestream2_tell_p(&pbc);
423         AV_WB16(escaped_buf, escaped_buf_size - 2);
424
425         ret = decode_extradata_ps(escaped_buf, escaped_buf_size, ps, 1, logctx);
426         av_freep(&escaped_buf);
427         if (ret < 0)
428             return ret;
429     }
430
431     return 0;
432 }
433
434 int ff_h264_decode_extradata(const uint8_t *data, int size, H264ParamSets *ps,
435                              int *is_avc, int *nal_length_size,
436                              int err_recognition, void *logctx)
437 {
438     int ret;
439
440     if (!data || size <= 0)
441         return -1;
442
443     if (data[0] == 1) {
444         int i, cnt, nalsize;
445         const uint8_t *p = data;
446
447         *is_avc = 1;
448
449         if (size < 7) {
450             av_log(logctx, AV_LOG_ERROR, "avcC %d too short\n", size);
451             return AVERROR_INVALIDDATA;
452         }
453
454         // Decode sps from avcC
455         cnt = *(p + 5) & 0x1f; // Number of sps
456         p  += 6;
457         for (i = 0; i < cnt; i++) {
458             nalsize = AV_RB16(p) + 2;
459             if (nalsize > size - (p - data))
460                 return AVERROR_INVALIDDATA;
461             ret = decode_extradata_ps_mp4(p, nalsize, ps, err_recognition, logctx);
462             if (ret < 0) {
463                 av_log(logctx, AV_LOG_ERROR,
464                        "Decoding sps %d from avcC failed\n", i);
465                 return ret;
466             }
467             p += nalsize;
468         }
469         // Decode pps from avcC
470         cnt = *(p++); // Number of pps
471         for (i = 0; i < cnt; i++) {
472             nalsize = AV_RB16(p) + 2;
473             if (nalsize > size - (p - data))
474                 return AVERROR_INVALIDDATA;
475             ret = decode_extradata_ps_mp4(p, nalsize, ps, err_recognition, logctx);
476             if (ret < 0) {
477                 av_log(logctx, AV_LOG_ERROR,
478                        "Decoding pps %d from avcC failed\n", i);
479                 return ret;
480             }
481             p += nalsize;
482         }
483         // Store right nal length size that will be used to parse all other nals
484         *nal_length_size = (data[4] & 0x03) + 1;
485     } else {
486         *is_avc = 0;
487         ret = decode_extradata_ps(data, size, ps, 0, logctx);
488         if (ret < 0)
489             return ret;
490     }
491     return size;
492 }
493
494 /**
495  * Compute profile from profile_idc and constraint_set?_flags.
496  *
497  * @param sps SPS
498  *
499  * @return profile as defined by FF_PROFILE_H264_*
500  */
501 int ff_h264_get_profile(const SPS *sps)
502 {
503     int profile = sps->profile_idc;
504
505     switch (sps->profile_idc) {
506     case FF_PROFILE_H264_BASELINE:
507         // constraint_set1_flag set to 1
508         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
509         break;
510     case FF_PROFILE_H264_HIGH_10:
511     case FF_PROFILE_H264_HIGH_422:
512     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
513         // constraint_set3_flag set to 1
514         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
515         break;
516     }
517
518     return profile;
519 }