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