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