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