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