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