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