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