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