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