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