]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264_parser.c
imgconvert: cosmetics: Reshuffle defines to reduce ifdeffery
[ffmpeg] / libavcodec / h264_parser.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... parser
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 parser.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include "libavutil/attributes.h"
29 #include "parser.h"
30 #include "h264data.h"
31 #include "golomb.h"
32 #include "internal.h"
33 #include "mpegutils.h"
34
35 #include <assert.h>
36
37
38 static int h264_find_frame_end(H264Context *h, const uint8_t *buf,
39                                int buf_size)
40 {
41     int i;
42     uint32_t state;
43     ParseContext *pc = &h->parse_context;
44 //    mb_addr= pc->mb_addr - 1;
45     state = pc->state;
46     if (state > 13)
47         state = 7;
48
49     for (i = 0; i < buf_size; i++) {
50         if (state == 7) {
51             i += h->h264dsp.h264_find_start_code_candidate(buf + i, buf_size - i);
52             if (i < buf_size)
53                 state = 2;
54         } else if (state <= 2) {
55             if (buf[i] == 1)
56                 state ^= 5;            // 2->7, 1->4, 0->5
57             else if (buf[i])
58                 state = 7;
59             else
60                 state >>= 1;           // 2->1, 1->0, 0->0
61         } else if (state <= 5) {
62             int nalu_type = buf[i] & 0x1F;
63             if (nalu_type == NAL_SEI || nalu_type == NAL_SPS ||
64                 nalu_type == NAL_PPS || nalu_type == NAL_AUD) {
65                 if (pc->frame_start_found) {
66                     i++;
67                     goto found;
68                 }
69             } else if (nalu_type == NAL_SLICE || nalu_type == NAL_DPA ||
70                        nalu_type == NAL_IDR_SLICE) {
71                 if (pc->frame_start_found) {
72                     state += 8;
73                     continue;
74                 } else
75                     pc->frame_start_found = 1;
76             }
77             state = 7;
78         } else {
79             if (buf[i] & 0x80)
80                 goto found;
81             state = 7;
82         }
83     }
84     pc->state = state;
85     return END_NOT_FOUND;
86
87 found:
88     pc->state             = 7;
89     pc->frame_start_found = 0;
90     return i - (state & 5);
91 }
92
93 static int scan_mmco_reset(AVCodecParserContext *s)
94 {
95     H264Context *h = s->priv_data;
96
97     h->slice_type_nos = s->pict_type & 3;
98
99     if (h->pps.redundant_pic_cnt_present)
100         get_ue_golomb(&h->gb); // redundant_pic_count
101
102     if (ff_set_ref_count(h) < 0)
103         return AVERROR_INVALIDDATA;
104
105     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
106         int list;
107         for (list = 0; list < h->list_count; list++) {
108             if (get_bits1(&h->gb)) {
109                 int index;
110                 for (index = 0; ; index++) {
111                     unsigned int reordering_of_pic_nums_idc = get_ue_golomb_31(&h->gb);
112
113                     if (reordering_of_pic_nums_idc < 3)
114                         get_ue_golomb(&h->gb);
115                     else if (reordering_of_pic_nums_idc > 3) {
116                         av_log(h->avctx, AV_LOG_ERROR,
117                                "illegal reordering_of_pic_nums_idc %d\n",
118                                reordering_of_pic_nums_idc);
119                         return AVERROR_INVALIDDATA;
120                     } else
121                         break;
122
123                     if (index >= h->ref_count[list]) {
124                         av_log(h->avctx, AV_LOG_ERROR,
125                                "reference count %d overflow\n", index);
126                         return AVERROR_INVALIDDATA;
127                     }
128                 }
129             }
130         }
131     }
132
133     if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
134         (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B))
135         ff_pred_weight_table(h);
136
137     if (get_bits1(&h->gb)) { // adaptive_ref_pic_marking_mode_flag
138         int i;
139         for (i = 0; i < MAX_MMCO_COUNT; i++) {
140             MMCOOpcode opcode = get_ue_golomb_31(&h->gb);
141             if (opcode > (unsigned) MMCO_LONG) {
142                 av_log(h->avctx, AV_LOG_ERROR,
143                        "illegal memory management control operation %d\n",
144                        opcode);
145                 return AVERROR_INVALIDDATA;
146             }
147             if (opcode == MMCO_END)
148                return 0;
149             else if (opcode == MMCO_RESET)
150                 return 1;
151
152             if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG)
153                 get_ue_golomb(&h->gb);
154             if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||
155                 opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG)
156                 get_ue_golomb_31(&h->gb);
157         }
158     }
159
160     return 0;
161 }
162
163 /**
164  * Parse NAL units of found picture and decode some basic information.
165  *
166  * @param s parser context.
167  * @param avctx codec context.
168  * @param buf buffer with field/frame data.
169  * @param buf_size size of the buffer.
170  */
171 static inline int parse_nal_units(AVCodecParserContext *s,
172                                   AVCodecContext *avctx,
173                                   const uint8_t *buf, int buf_size)
174 {
175     H264Context *h         = s->priv_data;
176     const uint8_t *buf_end = buf + buf_size;
177     unsigned int pps_id;
178     unsigned int slice_type;
179     int state = -1, got_reset = 0;
180     const uint8_t *ptr;
181     int field_poc[2];
182
183     /* set some sane default values */
184     s->pict_type         = AV_PICTURE_TYPE_I;
185     s->key_frame         = 0;
186     s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;
187
188     h->avctx = avctx;
189     ff_h264_reset_sei(h);
190
191     if (!buf_size)
192         return 0;
193
194     for (;;) {
195         int src_length, dst_length, consumed;
196         buf = avpriv_find_start_code(buf, buf_end, &state);
197         if (buf >= buf_end)
198             break;
199         --buf;
200         src_length = buf_end - buf;
201         switch (state & 0x1f) {
202         case NAL_SLICE:
203         case NAL_IDR_SLICE:
204             // Do not walk the whole buffer just to decode slice header
205             if ((state & 0x1f) == NAL_IDR_SLICE || ((state >> 5) & 0x3) == 0) {
206                 /* IDR or disposable slice
207                  * No need to decode many bytes because MMCOs shall not be present. */
208                 if (src_length > 60)
209                     src_length = 60;
210             } else {
211                 /* To decode up to MMCOs */
212                 if (src_length > 1000)
213                     src_length = 1000;
214             }
215             break;
216         }
217         ptr = ff_h264_decode_nal(h, buf, &dst_length, &consumed, src_length);
218         if (ptr == NULL || dst_length < 0)
219             break;
220
221         init_get_bits(&h->gb, ptr, 8 * dst_length);
222         switch (h->nal_unit_type) {
223         case NAL_SPS:
224             ff_h264_decode_seq_parameter_set(h);
225             break;
226         case NAL_PPS:
227             ff_h264_decode_picture_parameter_set(h, h->gb.size_in_bits);
228             break;
229         case NAL_SEI:
230             ff_h264_decode_sei(h);
231             break;
232         case NAL_IDR_SLICE:
233             s->key_frame = 1;
234
235             h->prev_frame_num        = 0;
236             h->prev_frame_num_offset = 0;
237             h->prev_poc_msb          =
238             h->prev_poc_lsb          = 0;
239         /* fall through */
240         case NAL_SLICE:
241             get_ue_golomb(&h->gb);  // skip first_mb_in_slice
242             slice_type   = get_ue_golomb_31(&h->gb);
243             s->pict_type = golomb_to_pict_type[slice_type % 5];
244             if (h->sei_recovery_frame_cnt >= 0) {
245                 /* key frame, since recovery_frame_cnt is set */
246                 s->key_frame = 1;
247             }
248             pps_id = get_ue_golomb(&h->gb);
249             if (pps_id >= MAX_PPS_COUNT) {
250                 av_log(h->avctx, AV_LOG_ERROR,
251                        "pps_id %u out of range\n", pps_id);
252                 return -1;
253             }
254             if (!h->pps_buffers[pps_id]) {
255                 av_log(h->avctx, AV_LOG_ERROR,
256                        "non-existing PPS %u referenced\n", pps_id);
257                 return -1;
258             }
259             h->pps = *h->pps_buffers[pps_id];
260             if (!h->sps_buffers[h->pps.sps_id]) {
261                 av_log(h->avctx, AV_LOG_ERROR,
262                        "non-existing SPS %u referenced\n", h->pps.sps_id);
263                 return -1;
264             }
265             h->sps       = *h->sps_buffers[h->pps.sps_id];
266             h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
267
268             avctx->profile = ff_h264_get_profile(&h->sps);
269             avctx->level   = h->sps.level_idc;
270
271             if (h->sps.frame_mbs_only_flag) {
272                 h->picture_structure = PICT_FRAME;
273             } else {
274                 if (get_bits1(&h->gb)) { // field_pic_flag
275                     h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
276                 } else {
277                     h->picture_structure = PICT_FRAME;
278                 }
279             }
280
281             if (h->nal_unit_type == NAL_IDR_SLICE)
282                 get_ue_golomb(&h->gb); /* idr_pic_id */
283             if (h->sps.poc_type == 0) {
284                 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
285
286                 if (h->pps.pic_order_present == 1 &&
287                     h->picture_structure == PICT_FRAME)
288                     h->delta_poc_bottom = get_se_golomb(&h->gb);
289             }
290
291             if (h->sps.poc_type == 1 &&
292                 !h->sps.delta_pic_order_always_zero_flag) {
293                 h->delta_poc[0] = get_se_golomb(&h->gb);
294
295                 if (h->pps.pic_order_present == 1 &&
296                     h->picture_structure == PICT_FRAME)
297                     h->delta_poc[1] = get_se_golomb(&h->gb);
298             }
299
300             /* Decode POC of this picture.
301              * The prev_ values needed for decoding POC of the next picture are not set here. */
302             field_poc[0] = field_poc[1] = INT_MAX;
303             ff_init_poc(h, field_poc, &s->output_picture_number);
304
305             /* Continue parsing to check if MMCO_RESET is present.
306              * FIXME: MMCO_RESET could appear in non-first slice.
307              *        Maybe, we should parse all undisposable non-IDR slice of this
308              *        picture until encountering MMCO_RESET in a slice of it. */
309             if (h->nal_ref_idc && h->nal_unit_type != NAL_IDR_SLICE) {
310                 got_reset = scan_mmco_reset(s);
311                 if (got_reset < 0)
312                     return got_reset;
313             }
314
315             /* Set up the prev_ values for decoding POC of the next picture. */
316             h->prev_frame_num        = got_reset ? 0 : h->frame_num;
317             h->prev_frame_num_offset = got_reset ? 0 : h->frame_num_offset;
318             if (h->nal_ref_idc != 0) {
319                 if (!got_reset) {
320                     h->prev_poc_msb = h->poc_msb;
321                     h->prev_poc_lsb = h->poc_lsb;
322                 } else {
323                     h->prev_poc_msb = 0;
324                     h->prev_poc_lsb =
325                         h->picture_structure == PICT_BOTTOM_FIELD ? 0 : field_poc[0];
326                 }
327             }
328
329             if (h->sps.pic_struct_present_flag) {
330                 switch (h->sei_pic_struct) {
331                 case SEI_PIC_STRUCT_TOP_FIELD:
332                 case SEI_PIC_STRUCT_BOTTOM_FIELD:
333                     s->repeat_pict = 0;
334                     break;
335                 case SEI_PIC_STRUCT_FRAME:
336                 case SEI_PIC_STRUCT_TOP_BOTTOM:
337                 case SEI_PIC_STRUCT_BOTTOM_TOP:
338                     s->repeat_pict = 1;
339                     break;
340                 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
341                 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
342                     s->repeat_pict = 2;
343                     break;
344                 case SEI_PIC_STRUCT_FRAME_DOUBLING:
345                     s->repeat_pict = 3;
346                     break;
347                 case SEI_PIC_STRUCT_FRAME_TRIPLING:
348                     s->repeat_pict = 5;
349                     break;
350                 default:
351                     s->repeat_pict = h->picture_structure == PICT_FRAME ? 1 : 0;
352                     break;
353                 }
354             } else {
355                 s->repeat_pict = h->picture_structure == PICT_FRAME ? 1 : 0;
356             }
357
358             if (h->picture_structure == PICT_FRAME) {
359                 s->picture_structure = AV_PICTURE_STRUCTURE_FRAME;
360                 if (h->sps.pic_struct_present_flag) {
361                     switch (h->sei_pic_struct) {
362                     case SEI_PIC_STRUCT_TOP_BOTTOM:
363                     case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
364                         s->field_order = AV_FIELD_TT;
365                         break;
366                     case SEI_PIC_STRUCT_BOTTOM_TOP:
367                     case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
368                         s->field_order = AV_FIELD_BB;
369                         break;
370                     default:
371                         s->field_order = AV_FIELD_PROGRESSIVE;
372                         break;
373                     }
374                 } else {
375                     if (field_poc[0] < field_poc[1])
376                         s->field_order = AV_FIELD_TT;
377                     else if (field_poc[0] > field_poc[1])
378                         s->field_order = AV_FIELD_BB;
379                     else
380                         s->field_order = AV_FIELD_PROGRESSIVE;
381                 }
382             } else {
383                 if (h->picture_structure == PICT_TOP_FIELD)
384                     s->picture_structure = AV_PICTURE_STRUCTURE_TOP_FIELD;
385                 else
386                     s->picture_structure = AV_PICTURE_STRUCTURE_BOTTOM_FIELD;
387                 s->field_order = AV_FIELD_UNKNOWN;
388             }
389
390             return 0; /* no need to evaluate the rest */
391         }
392         buf += consumed;
393     }
394     /* didn't find a picture! */
395     av_log(h->avctx, AV_LOG_ERROR, "missing picture in access unit\n");
396     return -1;
397 }
398
399 static int h264_parse(AVCodecParserContext *s,
400                       AVCodecContext *avctx,
401                       const uint8_t **poutbuf, int *poutbuf_size,
402                       const uint8_t *buf, int buf_size)
403 {
404     H264Context *h   = s->priv_data;
405     ParseContext *pc = &h->parse_context;
406     int next;
407
408     if (!h->got_first) {
409         h->got_first = 1;
410         if (avctx->extradata_size) {
411             h->avctx = avctx;
412             // must be done like in the decoder.
413             // otherwise opening the parser, creating extradata,
414             // and then closing and opening again
415             // will cause has_b_frames to be always set.
416             // NB: estimate_timings_from_pts behaves exactly like this.
417             if (!avctx->has_b_frames)
418                 h->low_delay = 1;
419             ff_h264_decode_extradata(h);
420         }
421     }
422
423     if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
424         next = buf_size;
425     } else {
426         next = h264_find_frame_end(h, buf, buf_size);
427
428         if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
429             *poutbuf      = NULL;
430             *poutbuf_size = 0;
431             return buf_size;
432         }
433
434         if (next < 0 && next != END_NOT_FOUND) {
435             assert(pc->last_index + next >= 0);
436             h264_find_frame_end(h, &pc->buffer[pc->last_index + next], -next); // update state
437         }
438     }
439
440     parse_nal_units(s, avctx, buf, buf_size);
441
442     if (h->sei_cpb_removal_delay >= 0) {
443         s->dts_sync_point    = h->sei_buffering_period_present;
444         s->dts_ref_dts_delta = h->sei_cpb_removal_delay;
445         s->pts_dts_delta     = h->sei_dpb_output_delay;
446     } else {
447         s->dts_sync_point    = INT_MIN;
448         s->dts_ref_dts_delta = INT_MIN;
449         s->pts_dts_delta     = INT_MIN;
450     }
451
452     if (s->flags & PARSER_FLAG_ONCE) {
453         s->flags &= PARSER_FLAG_COMPLETE_FRAMES;
454     }
455
456     *poutbuf      = buf;
457     *poutbuf_size = buf_size;
458     return next;
459 }
460
461 static int h264_split(AVCodecContext *avctx,
462                       const uint8_t *buf, int buf_size)
463 {
464     int i;
465     uint32_t state = -1;
466     int has_sps    = 0;
467
468     for (i = 0; i <= buf_size; i++) {
469         if ((state & 0xFFFFFF1F) == 0x107)
470             has_sps = 1;
471         /*  if((state&0xFFFFFF1F) == 0x101 ||
472          *     (state&0xFFFFFF1F) == 0x102 ||
473          *     (state&0xFFFFFF1F) == 0x105) {
474          *  }
475          */
476         if ((state & 0xFFFFFF00) == 0x100 && (state & 0xFFFFFF1F) != 0x107 &&
477             (state & 0xFFFFFF1F) != 0x108 && (state & 0xFFFFFF1F) != 0x109) {
478             if (has_sps) {
479                 while (i > 4 && buf[i - 5] == 0)
480                     i--;
481                 return i - 4;
482             }
483         }
484         if (i < buf_size)
485             state = (state << 8) | buf[i];
486     }
487     return 0;
488 }
489
490 static void close(AVCodecParserContext *s)
491 {
492     H264Context *h   = s->priv_data;
493     ParseContext *pc = &h->parse_context;
494
495     av_free(pc->buffer);
496     ff_h264_free_context(h);
497 }
498
499 static av_cold int init(AVCodecParserContext *s)
500 {
501     H264Context *h = s->priv_data;
502     h->thread_context[0]   = h;
503     h->slice_context_count = 1;
504     ff_h264dsp_init(&h->h264dsp, 8, 1);
505     return 0;
506 }
507
508 AVCodecParser ff_h264_parser = {
509     .codec_ids      = { AV_CODEC_ID_H264 },
510     .priv_data_size = sizeof(H264Context),
511     .parser_init    = init,
512     .parser_parse   = h264_parse,
513     .parser_close   = close,
514     .split          = h264_split,
515 };