a90ef6477d37fcbf29c4aa5672a17d9280f6d7b5
[libav.git] / libavcodec / h264.c
1 /*
2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
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 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
26 */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/stereo3d.h"
33 #include "libavutil/timer.h"
34 #include "internal.h"
35 #include "cabac.h"
36 #include "cabac_functions.h"
37 #include "error_resilience.h"
38 #include "avcodec.h"
39 #include "h264.h"
40 #include "h264data.h"
41 #include "h264chroma.h"
42 #include "h264_mvpred.h"
43 #include "golomb.h"
44 #include "mathops.h"
45 #include "me_cmp.h"
46 #include "mpegutils.h"
47 #include "profiles.h"
48 #include "rectangle.h"
49 #include "thread.h"
50
51 #include <assert.h>
52
53 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
54
55 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
56 int (*mv)[2][4][2],
57 int mb_x, int mb_y, int mb_intra, int mb_skipped)
58 {
59 H264Context *h = opaque;
60 H264SliceContext *sl = &h->slice_ctx[0];
61
62 sl->mb_x = mb_x;
63 sl->mb_y = mb_y;
64 sl->mb_xy = mb_x + mb_y * h->mb_stride;
65 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
66 assert(ref >= 0);
67 /* FIXME: It is possible albeit uncommon that slice references
68 * differ between slices. We take the easy approach and ignore
69 * it for now. If this turns out to have any relevance in
70 * practice then correct remapping should be added. */
71 if (ref >= sl->ref_count[0])
72 ref = 0;
73 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
74 2, 2, 2, ref, 1);
75 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
76 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
77 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
78 assert(!FRAME_MBAFF(h));
79 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
80 }
81
82 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
83 int y, int height)
84 {
85 AVCodecContext *avctx = h->avctx;
86 const AVFrame *src = h->cur_pic.f;
87 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
88 int vshift = desc->log2_chroma_h;
89 const int field_pic = h->picture_structure != PICT_FRAME;
90 if (field_pic) {
91 height <<= 1;
92 y <<= 1;
93 }
94
95 height = FFMIN(height, avctx->height - y);
96
97 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
98 return;
99
100 if (avctx->draw_horiz_band) {
101 int offset[AV_NUM_DATA_POINTERS];
102 int i;
103
104 offset[0] = y * src->linesize[0];
105 offset[1] =
106 offset[2] = (y >> vshift) * src->linesize[1];
107 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
108 offset[i] = 0;
109
110 emms_c();
111
112 avctx->draw_horiz_band(avctx, src, offset,
113 y, h->picture_structure, height);
114 }
115 }
116
117 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
118 const uint8_t *src,
119 int *dst_length, int *consumed, int length)
120 {
121 int i, si, di;
122 uint8_t *dst;
123
124 // src[0]&0x80; // forbidden bit
125 h->nal_ref_idc = src[0] >> 5;
126 h->nal_unit_type = src[0] & 0x1F;
127
128 src++;
129 length--;
130
131 #define STARTCODE_TEST \
132 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
133 if (src[i + 2] != 3) { \
134 /* startcode, so we must be past the end */ \
135 length = i; \
136 } \
137 break; \
138 }
139
140 #if HAVE_FAST_UNALIGNED
141 #define FIND_FIRST_ZERO \
142 if (i > 0 && !src[i]) \
143 i--; \
144 while (src[i]) \
145 i++
146
147 #if HAVE_FAST_64BIT
148 for (i = 0; i + 1 < length; i += 9) {
149 if (!((~AV_RN64A(src + i) &
150 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
151 0x8000800080008080ULL))
152 continue;
153 FIND_FIRST_ZERO;
154 STARTCODE_TEST;
155 i -= 7;
156 }
157 #else
158 for (i = 0; i + 1 < length; i += 5) {
159 if (!((~AV_RN32A(src + i) &
160 (AV_RN32A(src + i) - 0x01000101U)) &
161 0x80008080U))
162 continue;
163 FIND_FIRST_ZERO;
164 STARTCODE_TEST;
165 i -= 3;
166 }
167 #endif
168 #else
169 for (i = 0; i + 1 < length; i += 2) {
170 if (src[i])
171 continue;
172 if (i > 0 && src[i - 1] == 0)
173 i--;
174 STARTCODE_TEST;
175 }
176 #endif
177
178 if (i >= length - 1) { // no escaped 0
179 *dst_length = length;
180 *consumed = length + 1; // +1 for the header
181 return src;
182 }
183
184 av_fast_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size,
185 length + AV_INPUT_BUFFER_PADDING_SIZE);
186 dst = sl->rbsp_buffer;
187
188 if (!dst)
189 return NULL;
190
191 memcpy(dst, src, i);
192 si = di = i;
193 while (si + 2 < length) {
194 // remove escapes (very rare 1:2^22)
195 if (src[si + 2] > 3) {
196 dst[di++] = src[si++];
197 dst[di++] = src[si++];
198 } else if (src[si] == 0 && src[si + 1] == 0) {
199 if (src[si + 2] == 3) { // escape
200 dst[di++] = 0;
201 dst[di++] = 0;
202 si += 3;
203 continue;
204 } else // next start code
205 goto nsc;
206 }
207
208 dst[di++] = src[si++];
209 }
210 while (si < length)
211 dst[di++] = src[si++];
212
213 nsc:
214 memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
215
216 *dst_length = di;
217 *consumed = si + 1; // +1 for the header
218 /* FIXME store exact number of bits in the getbitcontext
219 * (it is needed for decoding) */
220 return dst;
221 }
222
223 /**
224 * Identify the exact end of the bitstream
225 * @return the length of the trailing, or 0 if damaged
226 */
227 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
228 {
229 int v = *src;
230 int r;
231
232 ff_tlog(h->avctx, "rbsp trailing %X\n", v);
233
234 for (r = 1; r < 9; r++) {
235 if (v & 1)
236 return r;
237 v >>= 1;
238 }
239 return 0;
240 }
241
242 void ff_h264_free_tables(H264Context *h)
243 {
244 int i;
245
246 av_freep(&h->intra4x4_pred_mode);
247 av_freep(&h->chroma_pred_mode_table);
248 av_freep(&h->cbp_table);
249 av_freep(&h->mvd_table[0]);
250 av_freep(&h->mvd_table[1]);
251 av_freep(&h->direct_table);
252 av_freep(&h->non_zero_count);
253 av_freep(&h->slice_table_base);
254 h->slice_table = NULL;
255 av_freep(&h->list_counts);
256
257 av_freep(&h->mb2b_xy);
258 av_freep(&h->mb2br_xy);
259
260 av_buffer_pool_uninit(&h->qscale_table_pool);
261 av_buffer_pool_uninit(&h->mb_type_pool);
262 av_buffer_pool_uninit(&h->motion_val_pool);
263 av_buffer_pool_uninit(&h->ref_index_pool);
264
265 for (i = 0; i < h->nb_slice_ctx; i++) {
266 H264SliceContext *sl = &h->slice_ctx[i];
267
268 av_freep(&sl->dc_val_base);
269 av_freep(&sl->er.mb_index2xy);
270 av_freep(&sl->er.error_status_table);
271 av_freep(&sl->er.er_temp_buffer);
272
273 av_freep(&sl->bipred_scratchpad);
274 av_freep(&sl->edge_emu_buffer);
275 av_freep(&sl->top_borders[0]);
276 av_freep(&sl->top_borders[1]);
277
278 sl->bipred_scratchpad_allocated = 0;
279 sl->edge_emu_buffer_allocated = 0;
280 sl->top_borders_allocated[0] = 0;
281 sl->top_borders_allocated[1] = 0;
282 }
283 }
284
285 int ff_h264_alloc_tables(H264Context *h)
286 {
287 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
288 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
289 int x, y;
290
291 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
292 row_mb_num * 8 * sizeof(uint8_t), fail)
293 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
294
295 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
296 big_mb_num * 48 * sizeof(uint8_t), fail)
297 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
298 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
299 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
300 big_mb_num * sizeof(uint16_t), fail)
301 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
302 big_mb_num * sizeof(uint8_t), fail)
303 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
304 16 * row_mb_num * sizeof(uint8_t), fail);
305 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
306 16 * row_mb_num * sizeof(uint8_t), fail);
307 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
308 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
309
310 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
311 4 * big_mb_num * sizeof(uint8_t), fail);
312 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
313 big_mb_num * sizeof(uint8_t), fail)
314
315 memset(h->slice_table_base, -1,
316 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
317 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
318
319 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
320 big_mb_num * sizeof(uint32_t), fail);
321 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
322 big_mb_num * sizeof(uint32_t), fail);
323 for (y = 0; y < h->mb_height; y++)
324 for (x = 0; x < h->mb_width; x++) {
325 const int mb_xy = x + y * h->mb_stride;
326 const int b_xy = 4 * x + 4 * y * h->b_stride;
327
328 h->mb2b_xy[mb_xy] = b_xy;
329 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
330 }
331
332 if (!h->dequant4_coeff[0])
333 h264_init_dequant_tables(h);
334
335 return 0;
336
337 fail:
338 ff_h264_free_tables(h);
339 return AVERROR(ENOMEM);
340 }
341
342 /**
343 * Init context
344 * Allocate buffers which are not shared amongst multiple threads.
345 */
346 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
347 {
348 ERContext *er = &sl->er;
349 int mb_array_size = h->mb_height * h->mb_stride;
350 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
351 int c_size = h->mb_stride * (h->mb_height + 1);
352 int yc_size = y_size + 2 * c_size;
353 int x, y, i;
354
355 sl->ref_cache[0][scan8[5] + 1] =
356 sl->ref_cache[0][scan8[7] + 1] =
357 sl->ref_cache[0][scan8[13] + 1] =
358 sl->ref_cache[1][scan8[5] + 1] =
359 sl->ref_cache[1][scan8[7] + 1] =
360 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
361
362 if (CONFIG_ERROR_RESILIENCE) {
363 /* init ER */
364 er->avctx = h->avctx;
365 er->decode_mb = h264_er_decode_mb;
366 er->opaque = h;
367 er->quarter_sample = 1;
368
369 er->mb_num = h->mb_num;
370 er->mb_width = h->mb_width;
371 er->mb_height = h->mb_height;
372 er->mb_stride = h->mb_stride;
373 er->b8_stride = h->mb_width * 2 + 1;
374
375 // error resilience code looks cleaner with this
376 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
377 (h->mb_num + 1) * sizeof(int), fail);
378
379 for (y = 0; y < h->mb_height; y++)
380 for (x = 0; x < h->mb_width; x++)
381 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
382
383 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
384 h->mb_stride + h->mb_width;
385
386 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
387 mb_array_size * sizeof(uint8_t), fail);
388
389 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
390 h->mb_height * h->mb_stride, fail);
391
392 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
393 yc_size * sizeof(int16_t), fail);
394 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
395 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
396 er->dc_val[2] = er->dc_val[1] + c_size;
397 for (i = 0; i < yc_size; i++)
398 sl->dc_val_base[i] = 1024;
399 }
400
401 return 0;
402
403 fail:
404 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
405 }
406
407 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
408 int parse_extradata);
409
410 int ff_h264_decode_extradata(H264Context *h)
411 {
412 AVCodecContext *avctx = h->avctx;
413 int ret;
414
415 if (avctx->extradata[0] == 1) {
416 int i, cnt, nalsize;
417 unsigned char *p = avctx->extradata;
418
419 h->is_avc = 1;
420
421 if (avctx->extradata_size < 7) {
422 av_log(avctx, AV_LOG_ERROR,
423 "avcC %d too short\n", avctx->extradata_size);
424 return AVERROR_INVALIDDATA;
425 }
426 /* sps and pps in the avcC always have length coded with 2 bytes,
427 * so put a fake nal_length_size = 2 while parsing them */
428 h->nal_length_size = 2;
429 // Decode sps from avcC
430 cnt = *(p + 5) & 0x1f; // Number of sps
431 p += 6;
432 for (i = 0; i < cnt; i++) {
433 nalsize = AV_RB16(p) + 2;
434 if (p - avctx->extradata + nalsize > avctx->extradata_size)
435 return AVERROR_INVALIDDATA;
436 ret = decode_nal_units(h, p, nalsize, 1);
437 if (ret < 0) {
438 av_log(avctx, AV_LOG_ERROR,
439 "Decoding sps %d from avcC failed\n", i);
440 return ret;
441 }
442 p += nalsize;
443 }
444 // Decode pps from avcC
445 cnt = *(p++); // Number of pps
446 for (i = 0; i < cnt; i++) {
447 nalsize = AV_RB16(p) + 2;
448 if (p - avctx->extradata + nalsize > avctx->extradata_size)
449 return AVERROR_INVALIDDATA;
450 ret = decode_nal_units(h, p, nalsize, 1);
451 if (ret < 0) {
452 av_log(avctx, AV_LOG_ERROR,
453 "Decoding pps %d from avcC failed\n", i);
454 return ret;
455 }
456 p += nalsize;
457 }
458 // Store right nal length size that will be used to parse all other nals
459 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
460 } else {
461 h->is_avc = 0;
462 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
463 if (ret < 0)
464 return ret;
465 }
466 return 0;
467 }
468
469 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
470 {
471 int i;
472
473 h->avctx = avctx;
474 h->dequant_coeff_pps = -1;
475
476 h->picture_structure = PICT_FRAME;
477 h->slice_context_count = 1;
478 h->workaround_bugs = avctx->workaround_bugs;
479 h->flags = avctx->flags;
480 h->prev_poc_msb = 1 << 16;
481 h->x264_build = -1;
482 h->recovery_frame = -1;
483 h->frame_recovered = 0;
484
485 h->next_outputed_poc = INT_MIN;
486 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
487 h->last_pocs[i] = INT_MIN;
488
489 ff_h264_reset_sei(h);
490
491 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
492
493 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
494 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
495 if (!h->slice_ctx) {
496 h->nb_slice_ctx = 0;
497 return AVERROR(ENOMEM);
498 }
499
500 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
501 h->DPB[i].f = av_frame_alloc();
502 if (!h->DPB[i].f)
503 return AVERROR(ENOMEM);
504 }
505
506 h->cur_pic.f = av_frame_alloc();
507 if (!h->cur_pic.f)
508 return AVERROR(ENOMEM);
509
510 for (i = 0; i < h->nb_slice_ctx; i++)
511 h->slice_ctx[i].h264 = h;
512
513 return 0;
514 }
515
516 static AVOnce h264_vlc_init = AV_ONCE_INIT;
517
518 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
519 {
520 H264Context *h = avctx->priv_data;
521 int ret;
522
523 ret = h264_init_context(avctx, h);
524 if (ret < 0)
525 return ret;
526
527 /* set defaults */
528 if (!avctx->has_b_frames)
529 h->low_delay = 1;
530
531 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
532 if (ret != 0) {
533 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
534 return AVERROR_UNKNOWN;
535 }
536
537 if (avctx->codec_id == AV_CODEC_ID_H264) {
538 if (avctx->ticks_per_frame == 1)
539 h->avctx->framerate.num *= 2;
540 avctx->ticks_per_frame = 2;
541 }
542
543 if (avctx->extradata_size > 0 && avctx->extradata) {
544 ret = ff_h264_decode_extradata(h);
545 if (ret < 0) {
546 ff_h264_free_context(h);
547 return ret;
548 }
549 }
550
551 if (h->sps.bitstream_restriction_flag &&
552 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
553 h->avctx->has_b_frames = h->sps.num_reorder_frames;
554 h->low_delay = 0;
555 }
556
557 avctx->internal->allocate_progress = 1;
558
559 if (h->enable_er) {
560 av_log(avctx, AV_LOG_WARNING,
561 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
562 "Use it at your own risk\n");
563 }
564
565 return 0;
566 }
567
568 static int decode_init_thread_copy(AVCodecContext *avctx)
569 {
570 H264Context *h = avctx->priv_data;
571 int ret;
572
573 if (!avctx->internal->is_copy)
574 return 0;
575
576 memset(h, 0, sizeof(*h));
577
578 ret = h264_init_context(avctx, h);
579 if (ret < 0)
580 return ret;
581
582 h->context_initialized = 0;
583
584 return 0;
585 }
586
587 /**
588 * Run setup operations that must be run after slice header decoding.
589 * This includes finding the next displayed frame.
590 *
591 * @param h h264 master context
592 * @param setup_finished enough NALs have been read that we can call
593 * ff_thread_finish_setup()
594 */
595 static void decode_postinit(H264Context *h, int setup_finished)
596 {
597 H264Picture *out = h->cur_pic_ptr;
598 H264Picture *cur = h->cur_pic_ptr;
599 int i, pics, out_of_order, out_idx;
600 int invalid = 0, cnt = 0;
601
602 h->cur_pic_ptr->f->pict_type = h->pict_type;
603
604 if (h->next_output_pic)
605 return;
606
607 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
608 /* FIXME: if we have two PAFF fields in one packet, we can't start
609 * the next thread here. If we have one field per packet, we can.
610 * The check in decode_nal_units() is not good enough to find this
611 * yet, so we assume the worst for now. */
612 // if (setup_finished)
613 // ff_thread_finish_setup(h->avctx);
614 return;
615 }
616
617 cur->f->interlaced_frame = 0;
618 cur->f->repeat_pict = 0;
619
620 /* Signal interlacing information externally. */
621 /* Prioritize picture timing SEI information over used
622 * decoding process if it exists. */
623
624 if (h->sps.pic_struct_present_flag) {
625 switch (h->sei_pic_struct) {
626 case SEI_PIC_STRUCT_FRAME:
627 break;
628 case SEI_PIC_STRUCT_TOP_FIELD:
629 case SEI_PIC_STRUCT_BOTTOM_FIELD:
630 cur->f->interlaced_frame = 1;
631 break;
632 case SEI_PIC_STRUCT_TOP_BOTTOM:
633 case SEI_PIC_STRUCT_BOTTOM_TOP:
634 if (FIELD_OR_MBAFF_PICTURE(h))
635 cur->f->interlaced_frame = 1;
636 else
637 // try to flag soft telecine progressive
638 cur->f->interlaced_frame = h->prev_interlaced_frame;
639 break;
640 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
641 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
642 /* Signal the possibility of telecined film externally
643 * (pic_struct 5,6). From these hints, let the applications
644 * decide if they apply deinterlacing. */
645 cur->f->repeat_pict = 1;
646 break;
647 case SEI_PIC_STRUCT_FRAME_DOUBLING:
648 cur->f->repeat_pict = 2;
649 break;
650 case SEI_PIC_STRUCT_FRAME_TRIPLING:
651 cur->f->repeat_pict = 4;
652 break;
653 }
654
655 if ((h->sei_ct_type & 3) &&
656 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
657 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
658 } else {
659 /* Derive interlacing flag from used decoding process. */
660 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
661 }
662 h->prev_interlaced_frame = cur->f->interlaced_frame;
663
664 if (cur->field_poc[0] != cur->field_poc[1]) {
665 /* Derive top_field_first from field pocs. */
666 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
667 } else {
668 if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
669 /* Use picture timing SEI information. Even if it is a
670 * information of a past frame, better than nothing. */
671 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
672 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
673 cur->f->top_field_first = 1;
674 else
675 cur->f->top_field_first = 0;
676 } else {
677 /* Most likely progressive */
678 cur->f->top_field_first = 0;
679 }
680 }
681
682 if (h->sei_frame_packing_present &&
683 h->frame_packing_arrangement_type >= 0 &&
684 h->frame_packing_arrangement_type <= 6 &&
685 h->content_interpretation_type > 0 &&
686 h->content_interpretation_type < 3) {
687 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
688 if (!stereo)
689 return;
690
691 switch (h->frame_packing_arrangement_type) {
692 case 0:
693 stereo->type = AV_STEREO3D_CHECKERBOARD;
694 break;
695 case 1:
696 stereo->type = AV_STEREO3D_COLUMNS;
697 break;
698 case 2:
699 stereo->type = AV_STEREO3D_LINES;
700 break;
701 case 3:
702 if (h->quincunx_subsampling)
703 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
704 else
705 stereo->type = AV_STEREO3D_SIDEBYSIDE;
706 break;
707 case 4:
708 stereo->type = AV_STEREO3D_TOPBOTTOM;
709 break;
710 case 5:
711 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
712 break;
713 case 6:
714 stereo->type = AV_STEREO3D_2D;
715 break;
716 }
717
718 if (h->content_interpretation_type == 2)
719 stereo->flags = AV_STEREO3D_FLAG_INVERT;
720 }
721
722 if (h->sei_display_orientation_present &&
723 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
724 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
725 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
726 AV_FRAME_DATA_DISPLAYMATRIX,
727 sizeof(int32_t) * 9);
728 if (!rotation)
729 return;
730
731 av_display_rotation_set((int32_t *)rotation->data, angle);
732 av_display_matrix_flip((int32_t *)rotation->data,
733 h->sei_hflip, h->sei_vflip);
734 }
735
736 if (h->sei_reguserdata_afd_present) {
737 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
738 sizeof(uint8_t));
739 if (!sd)
740 return;
741
742 *sd->data = h->active_format_description;
743 h->sei_reguserdata_afd_present = 0;
744 }
745
746 if (h->a53_caption) {
747 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
748 AV_FRAME_DATA_A53_CC,
749 h->a53_caption_size);
750 if (!sd)
751 return;
752
753 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
754 av_freep(&h->a53_caption);
755 h->a53_caption_size = 0;
756 }
757
758 // FIXME do something with unavailable reference frames
759
760 /* Sort B-frames into display order */
761 if (h->sps.bitstream_restriction_flag ||
762 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
763 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
764 }
765 h->low_delay = !h->avctx->has_b_frames;
766
767 pics = 0;
768 while (h->delayed_pic[pics])
769 pics++;
770
771 assert(pics <= MAX_DELAYED_PIC_COUNT);
772
773 h->delayed_pic[pics++] = cur;
774 if (cur->reference == 0)
775 cur->reference = DELAYED_PIC_REF;
776
777 /* Frame reordering. This code takes pictures from coding order and sorts
778 * them by their incremental POC value into display order. It supports POC
779 * gaps, MMCO reset codes and random resets.
780 * A "display group" can start either with a IDR frame (f.key_frame = 1),
781 * and/or can be closed down with a MMCO reset code. In sequences where
782 * there is no delay, we can't detect that (since the frame was already
783 * output to the user), so we also set h->mmco_reset to detect the MMCO
784 * reset code.
785 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
786 * we increase the delay between input and output. All frames affected by
787 * the lag (e.g. those that should have been output before another frame
788 * that we already returned to the user) will be dropped. This is a bug
789 * that we will fix later. */
790 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
791 cnt += out->poc < h->last_pocs[i];
792 invalid += out->poc == INT_MIN;
793 }
794 if (!h->mmco_reset && !cur->f->key_frame &&
795 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
796 h->mmco_reset = 2;
797 if (pics > 1)
798 h->delayed_pic[pics - 2]->mmco_reset = 2;
799 }
800 if (h->mmco_reset || cur->f->key_frame) {
801 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
802 h->last_pocs[i] = INT_MIN;
803 cnt = 0;
804 invalid = MAX_DELAYED_PIC_COUNT;
805 }
806 out = h->delayed_pic[0];
807 out_idx = 0;
808 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
809 h->delayed_pic[i] &&
810 !h->delayed_pic[i - 1]->mmco_reset &&
811 !h->delayed_pic[i]->f->key_frame;
812 i++)
813 if (h->delayed_pic[i]->poc < out->poc) {
814 out = h->delayed_pic[i];
815 out_idx = i;
816 }
817 if (h->avctx->has_b_frames == 0 &&
818 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
819 h->next_outputed_poc = INT_MIN;
820 out_of_order = !out->f->key_frame && !h->mmco_reset &&
821 (out->poc < h->next_outputed_poc);
822
823 if (h->sps.bitstream_restriction_flag &&
824 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
825 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
826 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
827 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
828 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
829 }
830 h->low_delay = 0;
831 } else if (h->low_delay &&
832 ((h->next_outputed_poc != INT_MIN &&
833 out->poc > h->next_outputed_poc + 2) ||
834 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
835 h->low_delay = 0;
836 h->avctx->has_b_frames++;
837 }
838
839 if (pics > h->avctx->has_b_frames) {
840 out->reference &= ~DELAYED_PIC_REF;
841 // for frame threading, the owner must be the second field's thread or
842 // else the first thread can release the picture and reuse it unsafely
843 for (i = out_idx; h->delayed_pic[i]; i++)
844 h->delayed_pic[i] = h->delayed_pic[i + 1];
845 }
846 memmove(h->last_pocs, &h->last_pocs[1],
847 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
848 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
849 if (!out_of_order && pics > h->avctx->has_b_frames) {
850 h->next_output_pic = out;
851 if (out->mmco_reset) {
852 if (out_idx > 0) {
853 h->next_outputed_poc = out->poc;
854 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
855 } else {
856 h->next_outputed_poc = INT_MIN;
857 }
858 } else {
859 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
860 h->next_outputed_poc = INT_MIN;
861 } else {
862 h->next_outputed_poc = out->poc;
863 }
864 }
865 h->mmco_reset = 0;
866 } else {
867 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
868 }
869
870 if (h->next_output_pic) {
871 if (h->next_output_pic->recovered) {
872 // We have reached an recovery point and all frames after it in
873 // display order are "recovered".
874 h->frame_recovered |= FRAME_RECOVERED_SEI;
875 }
876 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
877 }
878
879 if (setup_finished && !h->avctx->hwaccel) {
880 ff_thread_finish_setup(h->avctx);
881
882 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
883 h->setup_finished = 1;
884 }
885 }
886
887 /**
888 * instantaneous decoder refresh.
889 */
890 static void idr(H264Context *h)
891 {
892 ff_h264_remove_all_refs(h);
893 h->prev_frame_num =
894 h->prev_frame_num_offset =
895 h->prev_poc_msb =
896 h->prev_poc_lsb = 0;
897 }
898
899 /* forget old pics after a seek */
900 void ff_h264_flush_change(H264Context *h)
901 {
902 int i;
903 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
904 h->last_pocs[i] = INT_MIN;
905 h->next_outputed_poc = INT_MIN;
906 h->prev_interlaced_frame = 1;
907 idr(h);
908 if (h->cur_pic_ptr)
909 h->cur_pic_ptr->reference = 0;
910 h->first_field = 0;
911 ff_h264_reset_sei(h);
912 h->recovery_frame = -1;
913 h->frame_recovered = 0;
914 }
915
916 /* forget old pics after a seek */
917 static void flush_dpb(AVCodecContext *avctx)
918 {
919 H264Context *h = avctx->priv_data;
920 int i;
921
922 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
923
924 ff_h264_flush_change(h);
925
926 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
927 ff_h264_unref_picture(h, &h->DPB[i]);
928 h->cur_pic_ptr = NULL;
929 ff_h264_unref_picture(h, &h->cur_pic);
930
931 h->mb_y = 0;
932
933 ff_h264_free_tables(h);
934 h->context_initialized = 0;
935 }
936
937 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
938 {
939 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
940 int field_poc[2];
941
942 h->frame_num_offset = h->prev_frame_num_offset;
943 if (h->frame_num < h->prev_frame_num)
944 h->frame_num_offset += max_frame_num;
945
946 if (h->sps.poc_type == 0) {
947 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
948
949 if (h->poc_lsb < h->prev_poc_lsb &&
950 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
951 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
952 else if (h->poc_lsb > h->prev_poc_lsb &&
953 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
954 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
955 else
956 h->poc_msb = h->prev_poc_msb;
957 field_poc[0] =
958 field_poc[1] = h->poc_msb + h->poc_lsb;
959 if (h->picture_structure == PICT_FRAME)
960 field_poc[1] += h->delta_poc_bottom;
961 } else if (h->sps.poc_type == 1) {
962 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
963 int i;
964
965 if (h->sps.poc_cycle_length != 0)
966 abs_frame_num = h->frame_num_offset + h->frame_num;
967 else
968 abs_frame_num = 0;
969
970 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
971 abs_frame_num--;
972
973 expected_delta_per_poc_cycle = 0;
974 for (i = 0; i < h->sps.poc_cycle_length; i++)
975 // FIXME integrate during sps parse
976 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
977
978 if (abs_frame_num > 0) {
979 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
980 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
981
982 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
983 for (i = 0; i <= frame_num_in_poc_cycle; i++)
984 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
985 } else
986 expectedpoc = 0;
987
988 if (h->nal_ref_idc == 0)
989 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
990
991 field_poc[0] = expectedpoc + h->delta_poc[0];
992 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
993
994 if (h->picture_structure == PICT_FRAME)
995 field_poc[1] += h->delta_poc[1];
996 } else {
997 int poc = 2 * (h->frame_num_offset + h->frame_num);
998
999 if (!h->nal_ref_idc)
1000 poc--;
1001
1002 field_poc[0] = poc;
1003 field_poc[1] = poc;
1004 }
1005
1006 if (h->picture_structure != PICT_BOTTOM_FIELD)
1007 pic_field_poc[0] = field_poc[0];
1008 if (h->picture_structure != PICT_TOP_FIELD)
1009 pic_field_poc[1] = field_poc[1];
1010 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1011
1012 return 0;
1013 }
1014
1015 /**
1016 * Compute profile from profile_idc and constraint_set?_flags.
1017 *
1018 * @param sps SPS
1019 *
1020 * @return profile as defined by FF_PROFILE_H264_*
1021 */
1022 int ff_h264_get_profile(SPS *sps)
1023 {
1024 int profile = sps->profile_idc;
1025
1026 switch (sps->profile_idc) {
1027 case FF_PROFILE_H264_BASELINE:
1028 // constraint_set1_flag set to 1
1029 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1030 break;
1031 case FF_PROFILE_H264_HIGH_10:
1032 case FF_PROFILE_H264_HIGH_422:
1033 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1034 // constraint_set3_flag set to 1
1035 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1036 break;
1037 }
1038
1039 return profile;
1040 }
1041
1042 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1043 {
1044 int ref_count[2], list_count;
1045 int num_ref_idx_active_override_flag, max_refs;
1046
1047 // set defaults, might be overridden a few lines later
1048 ref_count[0] = h->pps.ref_count[0];
1049 ref_count[1] = h->pps.ref_count[1];
1050
1051 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1052 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1053 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1054 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1055
1056 if (num_ref_idx_active_override_flag) {
1057 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1058 if (ref_count[0] < 1)
1059 return AVERROR_INVALIDDATA;
1060 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1061 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1062 if (ref_count[1] < 1)
1063 return AVERROR_INVALIDDATA;
1064 }
1065 }
1066
1067 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1068 list_count = 2;
1069 else
1070 list_count = 1;
1071 } else {
1072 list_count = 0;
1073 ref_count[0] = ref_count[1] = 0;
1074 }
1075
1076 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1077
1078 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1079 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1080 sl->ref_count[0] = sl->ref_count[1] = 0;
1081 return AVERROR_INVALIDDATA;
1082 }
1083
1084 if (list_count != sl->list_count ||
1085 ref_count[0] != sl->ref_count[0] ||
1086 ref_count[1] != sl->ref_count[1]) {
1087 sl->ref_count[0] = ref_count[0];
1088 sl->ref_count[1] = ref_count[1];
1089 sl->list_count = list_count;
1090 return 1;
1091 }
1092
1093 return 0;
1094 }
1095
1096 static int find_start_code(const uint8_t *buf, int buf_size,
1097 int buf_index, int next_avc)
1098 {
1099 // start code prefix search
1100 for (; buf_index + 3 < next_avc; buf_index++)
1101 // This should always succeed in the first iteration.
1102 if (buf[buf_index] == 0 &&
1103 buf[buf_index + 1] == 0 &&
1104 buf[buf_index + 2] == 1)
1105 break;
1106
1107 if (buf_index + 3 >= buf_size)
1108 return buf_size;
1109
1110 return buf_index + 3;
1111 }
1112
1113 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1114 int buf_size, int *buf_index)
1115 {
1116 int i, nalsize = 0;
1117
1118 if (*buf_index >= buf_size - h->nal_length_size) {
1119 // the end of the buffer is reached, refill it.
1120 return AVERROR(EAGAIN);
1121 }
1122
1123 for (i = 0; i < h->nal_length_size; i++)
1124 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1125 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1126 av_log(h->avctx, AV_LOG_ERROR,
1127 "AVC: nal size %d\n", nalsize);
1128 return AVERROR_INVALIDDATA;
1129 }
1130 return nalsize;
1131 }
1132
1133 static int get_bit_length(H264Context *h, const uint8_t *buf,
1134 const uint8_t *ptr, int dst_length,
1135 int i, int next_avc)
1136 {
1137 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1138 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1139 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1140 h->workaround_bugs |= FF_BUG_TRUNCATED;
1141
1142 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1143 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1144 dst_length--;
1145
1146 if (!dst_length)
1147 return 0;
1148
1149 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1150 }
1151
1152 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1153 {
1154 int next_avc = h->is_avc ? 0 : buf_size;
1155 int nal_index = 0;
1156 int buf_index = 0;
1157 int nals_needed = 0;
1158
1159 while(1) {
1160 GetBitContext gb;
1161 int nalsize = 0;
1162 int dst_length, bit_length, consumed;
1163 const uint8_t *ptr;
1164
1165 if (buf_index >= next_avc) {
1166 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1167 if (nalsize < 0)
1168 break;
1169 next_avc = buf_index + nalsize;
1170 } else {
1171 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1172 if (buf_index >= buf_size)
1173 break;
1174 }
1175
1176 ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1177 next_avc - buf_index);
1178
1179 if (!ptr || dst_length < 0)
1180 return AVERROR_INVALIDDATA;
1181
1182 buf_index += consumed;
1183
1184 bit_length = get_bit_length(h, buf, ptr, dst_length,
1185 buf_index, next_avc);
1186 nal_index++;
1187
1188 /* packets can sometimes contain multiple PPS/SPS,
1189 * e.g. two PAFF field pictures in one packet, or a demuxer
1190 * which splits NALs strangely if so, when frame threading we
1191 * can't start the next thread until we've read all of them */
1192 switch (h->nal_unit_type) {
1193 case NAL_SPS:
1194 case NAL_PPS:
1195 nals_needed = nal_index;
1196 break;
1197 case NAL_DPA:
1198 case NAL_IDR_SLICE:
1199 case NAL_SLICE:
1200 init_get_bits(&gb, ptr, bit_length);
1201 if (!get_ue_golomb(&gb))
1202 nals_needed = nal_index;
1203 }
1204 }
1205
1206 return nals_needed;
1207 }
1208
1209 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1210 int parse_extradata)
1211 {
1212 AVCodecContext *const avctx = h->avctx;
1213 H264SliceContext *sl;
1214 int buf_index;
1215 unsigned context_count;
1216 int next_avc;
1217 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1218 int nal_index;
1219 int ret = 0;
1220
1221 h->max_contexts = h->slice_context_count;
1222 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1223 h->current_slice = 0;
1224 if (!h->first_field)
1225 h->cur_pic_ptr = NULL;
1226 ff_h264_reset_sei(h);
1227 }
1228
1229 if (avctx->active_thread_type & FF_THREAD_FRAME)
1230 nals_needed = get_last_needed_nal(h, buf, buf_size);
1231
1232 {
1233 buf_index = 0;
1234 context_count = 0;
1235 next_avc = h->is_avc ? 0 : buf_size;
1236 nal_index = 0;
1237 for (;;) {
1238 int consumed;
1239 int dst_length;
1240 int bit_length;
1241 const uint8_t *ptr;
1242 int nalsize = 0;
1243 int err;
1244
1245 if (buf_index >= next_avc) {
1246 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1247 if (nalsize < 0)
1248 break;
1249 next_avc = buf_index + nalsize;
1250 } else {
1251 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1252 if (buf_index >= buf_size)
1253 break;
1254 if (buf_index >= next_avc)
1255 continue;
1256 }
1257
1258 sl = &h->slice_ctx[context_count];
1259
1260 ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1261 &consumed, next_avc - buf_index);
1262 if (!ptr || dst_length < 0) {
1263 ret = -1;
1264 goto end;
1265 }
1266
1267 bit_length = get_bit_length(h, buf, ptr, dst_length,
1268 buf_index + consumed, next_avc);
1269
1270 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1271 av_log(h->avctx, AV_LOG_DEBUG,
1272 "NAL %d at %d/%d length %d\n",
1273 h->nal_unit_type, buf_index, buf_size, dst_length);
1274
1275 if (h->is_avc && (nalsize != consumed) && nalsize)
1276 av_log(h->avctx, AV_LOG_DEBUG,
1277 "AVC: Consumed only %d bytes instead of %d\n",
1278 consumed, nalsize);
1279
1280 buf_index += consumed;
1281 nal_index++;
1282
1283 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1284 h->nal_ref_idc == 0 &&
1285 h->nal_unit_type != NAL_SEI)
1286 continue;
1287
1288 again:
1289 /* Ignore every NAL unit type except PPS and SPS during extradata
1290 * parsing. Decoding slices is not possible in codec init
1291 * with frame-mt */
1292 if (parse_extradata && HAVE_THREADS &&
1293 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1294 (h->nal_unit_type != NAL_PPS &&
1295 h->nal_unit_type != NAL_SPS)) {
1296 if (h->nal_unit_type < NAL_AUD ||
1297 h->nal_unit_type > NAL_AUXILIARY_SLICE)
1298 av_log(avctx, AV_LOG_INFO,
1299 "Ignoring NAL unit %d during extradata parsing\n",
1300 h->nal_unit_type);
1301 h->nal_unit_type = NAL_FF_IGNORE;
1302 }
1303 err = 0;
1304 switch (h->nal_unit_type) {
1305 case NAL_IDR_SLICE:
1306 if (h->nal_unit_type != NAL_IDR_SLICE) {
1307 av_log(h->avctx, AV_LOG_ERROR,
1308 "Invalid mix of idr and non-idr slices\n");
1309 ret = -1;
1310 goto end;
1311 }
1312 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1313 case NAL_SLICE:
1314 init_get_bits(&sl->gb, ptr, bit_length);
1315
1316 if ((err = ff_h264_decode_slice_header(h, sl)))
1317 break;
1318
1319 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1320 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1321 ((1 << h->sps.log2_max_frame_num) - 1);
1322 }
1323
1324 h->cur_pic_ptr->f->key_frame |=
1325 (h->nal_unit_type == NAL_IDR_SLICE) ||
1326 (h->sei_recovery_frame_cnt >= 0);
1327
1328 if (h->nal_unit_type == NAL_IDR_SLICE ||
1329 h->recovery_frame == h->frame_num) {
1330 h->recovery_frame = -1;
1331 h->cur_pic_ptr->recovered = 1;
1332 }
1333 // If we have an IDR, all frames after it in decoded order are
1334 // "recovered".
1335 if (h->nal_unit_type == NAL_IDR_SLICE)
1336 h->frame_recovered |= FRAME_RECOVERED_IDR;
1337 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1338
1339 if (h->current_slice == 1) {
1340 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1341 decode_postinit(h, nal_index >= nals_needed);
1342
1343 if (h->avctx->hwaccel &&
1344 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1345 return ret;
1346 }
1347
1348 if (sl->redundant_pic_count == 0 &&
1349 (avctx->skip_frame < AVDISCARD_NONREF ||
1350 h->nal_ref_idc) &&
1351 (avctx->skip_frame < AVDISCARD_BIDIR ||
1352 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1353 (avctx->skip_frame < AVDISCARD_NONKEY ||
1354 h->cur_pic_ptr->f->key_frame) &&
1355 avctx->skip_frame < AVDISCARD_ALL) {
1356 if (avctx->hwaccel) {
1357 ret = avctx->hwaccel->decode_slice(avctx,
1358 &buf[buf_index - consumed],
1359 consumed);
1360 if (ret < 0)
1361 return ret;
1362 } else
1363 context_count++;
1364 }
1365 break;
1366 case NAL_DPA:
1367 case NAL_DPB:
1368 case NAL_DPC:
1369 avpriv_request_sample(avctx, "data partitioning");
1370 ret = AVERROR(ENOSYS);
1371 goto end;
1372 break;
1373 case NAL_SEI:
1374 init_get_bits(&h->gb, ptr, bit_length);
1375 ret = ff_h264_decode_sei(h);
1376 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1377 goto end;
1378 break;
1379 case NAL_SPS:
1380 init_get_bits(&h->gb, ptr, bit_length);
1381 ret = ff_h264_decode_seq_parameter_set(h);
1382 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
1383 av_log(h->avctx, AV_LOG_DEBUG,
1384 "SPS decoding failure, trying again with the complete NAL\n");
1385 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
1386 8 * (nalsize - 1));
1387 ff_h264_decode_seq_parameter_set(h);
1388 }
1389
1390 break;
1391 case NAL_PPS:
1392 init_get_bits(&h->gb, ptr, bit_length);
1393 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1394 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1395 goto end;
1396 break;
1397 case NAL_AUD:
1398 case NAL_END_SEQUENCE:
1399 case NAL_END_STREAM:
1400 case NAL_FILLER_DATA:
1401 case NAL_SPS_EXT:
1402 case NAL_AUXILIARY_SLICE:
1403 break;
1404 case NAL_FF_IGNORE:
1405 break;
1406 default:
1407 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1408 h->nal_unit_type, bit_length);
1409 }
1410
1411 if (context_count == h->max_contexts) {
1412 ret = ff_h264_execute_decode_slices(h, context_count);
1413 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1414 goto end;
1415 context_count = 0;
1416 }
1417
1418 if (err < 0) {
1419 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1420 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1421 } else if (err == 1) {
1422 /* Slice could not be decoded in parallel mode, restart. Note
1423 * that rbsp_buffer is not transferred, but since we no longer
1424 * run in parallel mode this should not be an issue. */
1425 sl = &h->slice_ctx[0];
1426 goto again;
1427 }
1428 }
1429 }
1430 if (context_count) {
1431 ret = ff_h264_execute_decode_slices(h, context_count);
1432 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1433 goto end;
1434 }
1435
1436 ret = 0;
1437 end:
1438 /* clean up */
1439 if (h->cur_pic_ptr && !h->droppable) {
1440 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1441 h->picture_structure == PICT_BOTTOM_FIELD);
1442 }
1443
1444 return (ret < 0) ? ret : buf_index;
1445 }
1446
1447 /**
1448 * Return the number of bytes consumed for building the current frame.
1449 */
1450 static int get_consumed_bytes(int pos, int buf_size)
1451 {
1452 if (pos == 0)
1453 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1454 if (pos + 10 > buf_size)
1455 pos = buf_size; // oops ;)
1456
1457 return pos;
1458 }
1459
1460 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1461 {
1462 int i;
1463 int ret = av_frame_ref(dst, src);
1464 if (ret < 0)
1465 return ret;
1466
1467 if (!h->sps.crop)
1468 return 0;
1469
1470 for (i = 0; i < 3; i++) {
1471 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1472 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1473 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1474 (h->sps.crop_top >> vshift) * dst->linesize[i];
1475 dst->data[i] += off;
1476 }
1477 return 0;
1478 }
1479
1480 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1481 int *got_frame, AVPacket *avpkt)
1482 {
1483 const uint8_t *buf = avpkt->data;
1484 int buf_size = avpkt->size;
1485 H264Context *h = avctx->priv_data;
1486 AVFrame *pict = data;
1487 int buf_index = 0;
1488 int ret;
1489
1490 h->flags = avctx->flags;
1491 h->setup_finished = 0;
1492
1493 /* end of stream, output what is still in the buffers */
1494 out:
1495 if (buf_size == 0) {
1496 H264Picture *out;
1497 int i, out_idx;
1498
1499 h->cur_pic_ptr = NULL;
1500
1501 // FIXME factorize this with the output code below
1502 out = h->delayed_pic[0];
1503 out_idx = 0;
1504 for (i = 1;
1505 h->delayed_pic[i] &&
1506 !h->delayed_pic[i]->f->key_frame &&
1507 !h->delayed_pic[i]->mmco_reset;
1508 i++)
1509 if (h->delayed_pic[i]->poc < out->poc) {
1510 out = h->delayed_pic[i];
1511 out_idx = i;
1512 }
1513
1514 for (i = out_idx; h->delayed_pic[i]; i++)
1515 h->delayed_pic[i] = h->delayed_pic[i + 1];
1516
1517 if (out) {
1518 ret = output_frame(h, pict, out->f);
1519 if (ret < 0)
1520 return ret;
1521 *got_frame = 1;
1522 }
1523
1524 return buf_index;
1525 }
1526
1527 buf_index = decode_nal_units(h, buf, buf_size, 0);
1528 if (buf_index < 0)
1529 return AVERROR_INVALIDDATA;
1530
1531 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1532 buf_size = 0;
1533 goto out;
1534 }
1535
1536 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1537 if (avctx->skip_frame >= AVDISCARD_NONREF)
1538 return 0;
1539 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1540 return AVERROR_INVALIDDATA;
1541 }
1542
1543 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1544 (h->mb_y >= h->mb_height && h->mb_height)) {
1545 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1546 decode_postinit(h, 1);
1547
1548 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1549
1550 *got_frame = 0;
1551 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1552 h->next_output_pic->recovered)) {
1553 if (!h->next_output_pic->recovered)
1554 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1555
1556 ret = output_frame(h, pict, h->next_output_pic->f);
1557 if (ret < 0)
1558 return ret;
1559 *got_frame = 1;
1560 }
1561 }
1562
1563 assert(pict->buf[0] || !*got_frame);
1564
1565 return get_consumed_bytes(buf_index, buf_size);
1566 }
1567
1568 av_cold void ff_h264_free_context(H264Context *h)
1569 {
1570 int i;
1571
1572 ff_h264_free_tables(h);
1573
1574 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1575 ff_h264_unref_picture(h, &h->DPB[i]);
1576 av_frame_free(&h->DPB[i].f);
1577 }
1578
1579 h->cur_pic_ptr = NULL;
1580
1581 for (i = 0; i < h->nb_slice_ctx; i++)
1582 av_freep(&h->slice_ctx[i].rbsp_buffer);
1583 av_freep(&h->slice_ctx);
1584 h->nb_slice_ctx = 0;
1585
1586 for (i = 0; i < MAX_SPS_COUNT; i++)
1587 av_freep(h->sps_buffers + i);
1588
1589 for (i = 0; i < MAX_PPS_COUNT; i++)
1590 av_freep(h->pps_buffers + i);
1591 }
1592
1593 static av_cold int h264_decode_end(AVCodecContext *avctx)
1594 {
1595 H264Context *h = avctx->priv_data;
1596
1597 ff_h264_free_context(h);
1598
1599 ff_h264_unref_picture(h, &h->cur_pic);
1600 av_frame_free(&h->cur_pic.f);
1601
1602 return 0;
1603 }
1604
1605 #define OFFSET(x) offsetof(H264Context, x)
1606 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1607 static const AVOption h264_options[] = {
1608 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1609 { NULL },
1610 };
1611
1612 static const AVClass h264_class = {
1613 .class_name = "h264",
1614 .item_name = av_default_item_name,
1615 .option = h264_options,
1616 .version = LIBAVUTIL_VERSION_INT,
1617 };
1618
1619 AVCodec ff_h264_decoder = {
1620 .name = "h264",
1621 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1622 .type = AVMEDIA_TYPE_VIDEO,
1623 .id = AV_CODEC_ID_H264,
1624 .priv_data_size = sizeof(H264Context),
1625 .init = ff_h264_decode_init,
1626 .close = h264_decode_end,
1627 .decode = h264_decode_frame,
1628 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1629 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1630 AV_CODEC_CAP_FRAME_THREADS,
1631 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1632 .flush = flush_dpb,
1633 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1634 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1635 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1636 .priv_class = &h264_class,
1637 };