ef5da989344f202ef81fb1c676ea644b3e6e61f8
[ffmpeg.git] / 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
34 #include <assert.h>
35
36
37 static int h264_find_frame_end(H264Context *h, const uint8_t *buf,
38                                int buf_size)
39 {
40     int i;
41     uint32_t state;
42     ParseContext *pc = &h->parse_context;
43 //    mb_addr= pc->mb_addr - 1;
44     state = pc->state;
45     if (state > 13)
46         state = 7;
47
48     for (i = 0; i < buf_size; i++) {
49         if (state == 7) {
50             i += h->h264dsp.h264_find_start_code_candidate(buf + i, buf_size - i);
51             if (i < buf_size)
52                 state = 2;
53         } else if (state <= 2) {
54             if (buf[i] == 1)
55                 state ^= 5;            // 2->7, 1->4, 0->5
56             else if (buf[i])
57                 state = 7;
58             else
59                 state >>= 1;           // 2->1, 1->0, 0->0
60         } else if (state <= 5) {
61             int v = buf[i] & 0x1F;
62             if (v == 6 || v == 7 || v == 8 || v == 9) {
63                 if (pc->frame_start_found) {
64                     i++;
65                     goto found;
66                 }
67             } else if (v == 1 || v == 2 || v == 5) {
68                 if (pc->frame_start_found) {
69                     state += 8;
70                     continue;
71                 } else
72                     pc->frame_start_found = 1;
73             }
74             state = 7;
75         } else {
76             if (buf[i] & 0x80)
77                 goto found;
78             state = 7;
79         }
80     }
81     pc->state = state;
82     return END_NOT_FOUND;
83
84 found:
85     pc->state             = 7;
86     pc->frame_start_found = 0;
87     return i - (state & 5);
88 }
89
90 /**
91  * Parse NAL units of found picture and decode some basic information.
92  *
93  * @param s parser context.
94  * @param avctx codec context.
95  * @param buf buffer with field/frame data.
96  * @param buf_size size of the buffer.
97  */
98 static inline int parse_nal_units(AVCodecParserContext *s,
99                                   AVCodecContext *avctx,
100                                   const uint8_t *buf, int buf_size)
101 {
102     H264Context *h         = s->priv_data;
103     const uint8_t *buf_end = buf + buf_size;
104     unsigned int pps_id;
105     unsigned int slice_type;
106     int state = -1;
107     const uint8_t *ptr;
108     int field_poc[2];
109
110     /* set some sane default values */
111     s->pict_type         = AV_PICTURE_TYPE_I;
112     s->key_frame         = 0;
113     s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;
114
115     h->avctx                        = avctx;
116     h->sei_recovery_frame_cnt       = -1;
117     h->sei_dpb_output_delay         = 0;
118     h->sei_cpb_removal_delay        = -1;
119     h->sei_buffering_period_present = 0;
120
121     if (!buf_size)
122         return 0;
123
124     for (;;) {
125         int src_length, dst_length, consumed;
126         buf = avpriv_find_start_code(buf, buf_end, &state);
127         if (buf >= buf_end)
128             break;
129         --buf;
130         src_length = buf_end - buf;
131         switch (state & 0x1f) {
132         case NAL_SLICE:
133         case NAL_IDR_SLICE:
134             // Do not walk the whole buffer just to decode slice header
135             if (src_length > 20)
136                 src_length = 20;
137             break;
138         }
139         ptr = ff_h264_decode_nal(h, buf, &dst_length, &consumed, src_length);
140         if (ptr == NULL || dst_length < 0)
141             break;
142
143         init_get_bits(&h->gb, ptr, 8 * dst_length);
144         switch (h->nal_unit_type) {
145         case NAL_SPS:
146             ff_h264_decode_seq_parameter_set(h);
147             break;
148         case NAL_PPS:
149             ff_h264_decode_picture_parameter_set(h, h->gb.size_in_bits);
150             break;
151         case NAL_SEI:
152             ff_h264_decode_sei(h);
153             break;
154         case NAL_IDR_SLICE:
155             s->key_frame = 1;
156
157             h->prev_frame_num        = 0;
158             h->prev_frame_num_offset = 0;
159             h->prev_poc_msb          =
160             h->prev_poc_lsb          = 0;
161         /* fall through */
162         case NAL_SLICE:
163             get_ue_golomb(&h->gb);  // skip first_mb_in_slice
164             slice_type   = get_ue_golomb_31(&h->gb);
165             s->pict_type = golomb_to_pict_type[slice_type % 5];
166             if (h->sei_recovery_frame_cnt >= 0) {
167                 /* key frame, since recovery_frame_cnt is set */
168                 s->key_frame = 1;
169             }
170             pps_id = get_ue_golomb(&h->gb);
171             if (pps_id >= MAX_PPS_COUNT) {
172                 av_log(h->avctx, AV_LOG_ERROR,
173                        "pps_id out of range\n");
174                 return -1;
175             }
176             if (!h->pps_buffers[pps_id]) {
177                 av_log(h->avctx, AV_LOG_ERROR,
178                        "non-existing PPS referenced\n");
179                 return -1;
180             }
181             h->pps = *h->pps_buffers[pps_id];
182             if (!h->sps_buffers[h->pps.sps_id]) {
183                 av_log(h->avctx, AV_LOG_ERROR,
184                        "non-existing SPS referenced\n");
185                 return -1;
186             }
187             h->sps       = *h->sps_buffers[h->pps.sps_id];
188             h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
189
190             avctx->profile = ff_h264_get_profile(&h->sps);
191             avctx->level   = h->sps.level_idc;
192
193             if (h->sps.frame_mbs_only_flag) {
194                 h->picture_structure = PICT_FRAME;
195             } else {
196                 if (get_bits1(&h->gb)) { // field_pic_flag
197                     h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
198                 } else {
199                     h->picture_structure = PICT_FRAME;
200                 }
201             }
202
203             if (h->nal_unit_type == NAL_IDR_SLICE)
204                 get_ue_golomb(&h->gb); /* idr_pic_id */
205             if (h->sps.poc_type == 0) {
206                 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
207
208                 if (h->pps.pic_order_present == 1 &&
209                     h->picture_structure == PICT_FRAME)
210                     h->delta_poc_bottom = get_se_golomb(&h->gb);
211             }
212
213             if (h->sps.poc_type == 1 &&
214                 !h->sps.delta_pic_order_always_zero_flag) {
215                 h->delta_poc[0] = get_se_golomb(&h->gb);
216
217                 if (h->pps.pic_order_present == 1 &&
218                     h->picture_structure == PICT_FRAME)
219                     h->delta_poc[1] = get_se_golomb(&h->gb);
220             }
221
222             ff_init_poc(h, field_poc, &s->output_picture_number);
223
224             if (h->sps.pic_struct_present_flag) {
225                 switch (h->sei_pic_struct) {
226                 case SEI_PIC_STRUCT_TOP_FIELD:
227                 case SEI_PIC_STRUCT_BOTTOM_FIELD:
228                     s->repeat_pict = 0;
229                     break;
230                 case SEI_PIC_STRUCT_FRAME:
231                 case SEI_PIC_STRUCT_TOP_BOTTOM:
232                 case SEI_PIC_STRUCT_BOTTOM_TOP:
233                     s->repeat_pict = 1;
234                     break;
235                 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
236                 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
237                     s->repeat_pict = 2;
238                     break;
239                 case SEI_PIC_STRUCT_FRAME_DOUBLING:
240                     s->repeat_pict = 3;
241                     break;
242                 case SEI_PIC_STRUCT_FRAME_TRIPLING:
243                     s->repeat_pict = 5;
244                     break;
245                 default:
246                     s->repeat_pict = h->picture_structure == PICT_FRAME ? 1 : 0;
247                     break;
248                 }
249             } else {
250                 s->repeat_pict = h->picture_structure == PICT_FRAME ? 1 : 0;
251             }
252
253             if (h->picture_structure == PICT_FRAME) {
254                 s->picture_structure = AV_PICTURE_STRUCTURE_FRAME;
255                 if (h->sps.pic_struct_present_flag) {
256                     switch (h->sei_pic_struct) {
257                     case SEI_PIC_STRUCT_TOP_BOTTOM:
258                     case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
259                         s->field_order = AV_FIELD_TT;
260                         break;
261                     case SEI_PIC_STRUCT_BOTTOM_TOP:
262                     case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
263                         s->field_order = AV_FIELD_BB;
264                         break;
265                     default:
266                         s->field_order = AV_FIELD_PROGRESSIVE;
267                         break;
268                     }
269                 } else {
270                     if (field_poc[0] < field_poc[1])
271                         s->field_order = AV_FIELD_TT;
272                     else if (field_poc[0] > field_poc[1])
273                         s->field_order = AV_FIELD_BB;
274                     else
275                         s->field_order = AV_FIELD_PROGRESSIVE;
276                 }
277             } else {
278                 if (h->picture_structure == PICT_TOP_FIELD)
279                     s->picture_structure = AV_PICTURE_STRUCTURE_TOP_FIELD;
280                 else
281                     s->picture_structure = AV_PICTURE_STRUCTURE_BOTTOM_FIELD;
282                 s->field_order = AV_FIELD_UNKNOWN;
283             }
284
285             return 0; /* no need to evaluate the rest */
286         }
287         buf += consumed;
288     }
289     /* didn't find a picture! */
290     av_log(h->avctx, AV_LOG_ERROR, "missing picture in access unit\n");
291     return -1;
292 }
293
294 static int h264_parse(AVCodecParserContext *s,
295                       AVCodecContext *avctx,
296                       const uint8_t **poutbuf, int *poutbuf_size,
297                       const uint8_t *buf, int buf_size)
298 {
299     H264Context *h   = s->priv_data;
300     ParseContext *pc = &h->parse_context;
301     int next;
302
303     if (!h->got_first) {
304         h->got_first = 1;
305         if (avctx->extradata_size) {
306             h->avctx = avctx;
307             // must be done like in the decoder.
308             // otherwise opening the parser, creating extradata,
309             // and then closing and opening again
310             // will cause has_b_frames to be always set.
311             // NB: estimate_timings_from_pts behaves exactly like this.
312             if (!avctx->has_b_frames)
313                 h->low_delay = 1;
314             ff_h264_decode_extradata(h);
315         }
316     }
317
318     if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
319         next = buf_size;
320     } else {
321         next = h264_find_frame_end(h, buf, buf_size);
322
323         if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
324             *poutbuf      = NULL;
325             *poutbuf_size = 0;
326             return buf_size;
327         }
328
329         if (next < 0 && next != END_NOT_FOUND) {
330             assert(pc->last_index + next >= 0);
331             h264_find_frame_end(h, &pc->buffer[pc->last_index + next], -next); // update state
332         }
333     }
334
335     parse_nal_units(s, avctx, buf, buf_size);
336
337     if (h->sei_cpb_removal_delay >= 0) {
338         s->dts_sync_point    = h->sei_buffering_period_present;
339         s->dts_ref_dts_delta = h->sei_cpb_removal_delay;
340         s->pts_dts_delta     = h->sei_dpb_output_delay;
341     } else {
342         s->dts_sync_point    = INT_MIN;
343         s->dts_ref_dts_delta = INT_MIN;
344         s->pts_dts_delta     = INT_MIN;
345     }
346
347     if (s->flags & PARSER_FLAG_ONCE) {
348         s->flags &= PARSER_FLAG_COMPLETE_FRAMES;
349     }
350
351     *poutbuf      = buf;
352     *poutbuf_size = buf_size;
353     return next;
354 }
355
356 static int h264_split(AVCodecContext *avctx,
357                       const uint8_t *buf, int buf_size)
358 {
359     int i;
360     uint32_t state = -1;
361     int has_sps    = 0;
362
363     for (i = 0; i <= buf_size; i++) {
364         if ((state & 0xFFFFFF1F) == 0x107)
365             has_sps = 1;
366         /*  if((state&0xFFFFFF1F) == 0x101 ||
367          *     (state&0xFFFFFF1F) == 0x102 ||
368          *     (state&0xFFFFFF1F) == 0x105) {
369          *  }
370          */
371         if ((state & 0xFFFFFF00) == 0x100 && (state & 0xFFFFFF1F) != 0x107 &&
372             (state & 0xFFFFFF1F) != 0x108 && (state & 0xFFFFFF1F) != 0x109) {
373             if (has_sps) {
374                 while (i > 4 && buf[i - 5] == 0)
375                     i--;
376                 return i - 4;
377             }
378         }
379         if (i < buf_size)
380             state = (state << 8) | buf[i];
381     }
382     return 0;
383 }
384
385 static void close(AVCodecParserContext *s)
386 {
387     H264Context *h   = s->priv_data;
388     ParseContext *pc = &h->parse_context;
389
390     av_free(pc->buffer);
391     ff_h264_free_context(h);
392 }
393
394 static av_cold int init(AVCodecParserContext *s)
395 {
396     H264Context *h = s->priv_data;
397     h->thread_context[0]   = h;
398     h->slice_context_count = 1;
399     ff_h264dsp_init(&h->h264dsp, 8, 1);
400     return 0;
401 }
402
403 AVCodecParser ff_h264_parser = {
404     .codec_ids      = { AV_CODEC_ID_H264 },
405     .priv_data_size = sizeof(H264Context),
406     .parser_init    = init,
407     .parser_parse   = h264_parse,
408     .parser_close   = close,
409     .split          = h264_split,
410 };