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