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