libavutil: Make avpriv_open a library-internal function on msvcrt
[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"
40e5d31b 30#include "internal.h"
55b9ef18
DB
31#include "cabac.h"
32#include "cabac_functions.h"
0da71265 33#include "dsputil.h"
5f401b7b 34#include "error_resilience.h"
0da71265
MN
35#include "avcodec.h"
36#include "mpegvideo.h"
26b4fe82 37#include "h264.h"
0da71265 38#include "h264data.h"
79dad2a9 39#include "h264chroma.h"
188d3c51 40#include "h264_mvpred.h"
0da71265 41#include "golomb.h"
199436b9 42#include "mathops.h"
626464fb 43#include "rectangle.h"
75d5156a 44#include "svq3.h"
6a9c8594 45#include "thread.h"
0da71265 46
e5d40372 47// #undef NDEBUG
0da71265
MN
48#include <assert.h>
49
0becb078
DB
50const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
51
e5d40372
DB
52static const uint8_t rem6[QP_MAX_NUM + 1] = {
53 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
54 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
55 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
acd8d10f
PI
56};
57
e5d40372
DB
58static const uint8_t div6[QP_MAX_NUM + 1] = {
59 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
60 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
61 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
acd8d10f
PI
62};
63
8d061989
RB
64static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
65#if CONFIG_H264_DXVA2_HWACCEL
66 AV_PIX_FMT_DXVA2_VLD,
67#endif
68#if CONFIG_H264_VAAPI_HWACCEL
69 AV_PIX_FMT_VAAPI_VLD,
70#endif
71#if CONFIG_H264_VDA_HWACCEL
72 AV_PIX_FMT_VDA_VLD,
73#endif
74#if CONFIG_H264_VDPAU_HWACCEL
75 AV_PIX_FMT_VDPAU,
76#endif
77 AV_PIX_FMT_YUV420P,
78 AV_PIX_FMT_NONE
79};
80
d65522e8 81static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
78bc4d69 82#if CONFIG_H264_DXVA2_HWACCEL
716d413c 83 AV_PIX_FMT_DXVA2_VLD,
78bc4d69
RDC
84#endif
85#if CONFIG_H264_VAAPI_HWACCEL
716d413c 86 AV_PIX_FMT_VAAPI_VLD,
78bc4d69
RDC
87#endif
88#if CONFIG_H264_VDA_HWACCEL
716d413c 89 AV_PIX_FMT_VDA_VLD,
78bc4d69
RDC
90#endif
91#if CONFIG_H264_VDPAU_HWACCEL
ec0e9200 92 AV_PIX_FMT_VDPAU,
78bc4d69 93#endif
716d413c
AK
94 AV_PIX_FMT_YUVJ420P,
95 AV_PIX_FMT_NONE
0435fb16
BC
96};
97
54974c62
AK
98static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
99 int (*mv)[2][4][2],
100 int mb_x, int mb_y, int mb_intra, int mb_skipped)
101{
16c22122 102 H264Context *h = opaque;
54974c62 103
2c541554
AK
104 h->mb_x = mb_x;
105 h->mb_y = mb_y;
106 h->mb_xy = mb_x + mb_y * h->mb_stride;
54974c62
AK
107 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
108 assert(ref >= 0);
109 /* FIXME: It is possible albeit uncommon that slice references
110 * differ between slices. We take the easy approach and ignore
111 * it for now. If this turns out to have any relevance in
112 * practice then correct remapping should be added. */
113 if (ref >= h->ref_count[0])
114 ref = 0;
759001c5 115 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
54974c62
AK
116 2, 2, 2, ref, 1);
117 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
118 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
2c541554 119 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
7bece9b2 120 assert(!FRAME_MBAFF(h));
54974c62
AK
121 ff_h264_hl_decode_mb(h);
122}
123
2c541554
AK
124void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
125{
64e43869
RB
126 AVCodecContext *avctx = h->avctx;
127 Picture *cur = &h->cur_pic;
128 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
129 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
130 int vshift = desc->log2_chroma_h;
131 const int field_pic = h->picture_structure != PICT_FRAME;
132 if (field_pic) {
133 height <<= 1;
16c22122 134 y <<= 1;
64e43869
RB
135 }
136
137 height = FFMIN(height, avctx->height - y);
138
139 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
140 return;
141
142 if (avctx->draw_horiz_band) {
143 AVFrame *src;
144 int offset[AV_NUM_DATA_POINTERS];
145 int i;
146
147 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
16c22122 148 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
64e43869
RB
149 src = &cur->f;
150 else if (last)
151 src = &last->f;
152 else
153 return;
154
155 offset[0] = y * src->linesize[0];
156 offset[1] =
157 offset[2] = (y >> vshift) * src->linesize[1];
158 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
159 offset[i] = 0;
160
161 emms_c();
162
163 avctx->draw_horiz_band(avctx, src, offset,
164 y, h->picture_structure, height);
165 }
2c541554
AK
166}
167
759001c5 168static void unref_picture(H264Context *h, Picture *pic)
2c541554 169{
759001c5 170 int off = offsetof(Picture, tf) + sizeof(pic->tf);
2c541554
AK
171 int i;
172
759001c5
AK
173 if (!pic->f.data[0])
174 return;
175
176 ff_thread_release_buffer(h->avctx, &pic->tf);
177 av_buffer_unref(&pic->hwaccel_priv_buf);
2c541554 178
759001c5
AK
179 av_buffer_unref(&pic->qscale_table_buf);
180 av_buffer_unref(&pic->mb_type_buf);
2c541554 181 for (i = 0; i < 2; i++) {
759001c5
AK
182 av_buffer_unref(&pic->motion_val_buf[i]);
183 av_buffer_unref(&pic->ref_index_buf[i]);
2c541554 184 }
759001c5
AK
185
186 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
2c541554
AK
187}
188
189static void release_unused_pictures(H264Context *h, int remove_current)
190{
191 int i;
192
193 /* release non reference frames */
759001c5
AK
194 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
195 if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
2c541554 196 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
759001c5 197 unref_picture(h, &h->DPB[i]);
2c541554
AK
198 }
199 }
200}
201
759001c5
AK
202static int ref_picture(H264Context *h, Picture *dst, Picture *src)
203{
204 int ret, i;
205
206 av_assert0(!dst->f.buf[0]);
207 av_assert0(src->f.buf[0]);
208
209 src->tf.f = &src->f;
210 dst->tf.f = &dst->f;
211 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
212 if (ret < 0)
213 goto fail;
214
759001c5
AK
215 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
216 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
217 if (!dst->qscale_table_buf || !dst->mb_type_buf)
218 goto fail;
219 dst->qscale_table = src->qscale_table;
220 dst->mb_type = src->mb_type;
221
16c22122 222 for (i = 0; i < 2; i++) {
759001c5
AK
223 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
224 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
225 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
226 goto fail;
227 dst->motion_val[i] = src->motion_val[i];
228 dst->ref_index[i] = src->ref_index[i];
229 }
230
231 if (src->hwaccel_picture_private) {
232 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
233 if (!dst->hwaccel_priv_buf)
234 goto fail;
235 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
236 }
237
238 for (i = 0; i < 2; i++)
239 dst->field_poc[i] = src->field_poc[i];
240
241 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
242 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
243
16c22122
DB
244 dst->poc = src->poc;
245 dst->frame_num = src->frame_num;
246 dst->mmco_reset = src->mmco_reset;
247 dst->pic_id = src->pic_id;
248 dst->long_ref = src->long_ref;
249 dst->mbaff = src->mbaff;
250 dst->field_picture = src->field_picture;
251 dst->needs_realloc = src->needs_realloc;
252 dst->reference = src->reference;
759001c5
AK
253
254 return 0;
255fail:
256 unref_picture(h, dst);
257 return ret;
258}
259
2c541554
AK
260static int alloc_scratch_buffers(H264Context *h, int linesize)
261{
262 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
263
264 if (h->bipred_scratchpad)
265 return 0;
266
267 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
268 // edge emu needs blocksize + filter length - 1
269 // (= 21x21 for h264)
270 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
271 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
272
273 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
274 av_freep(&h->bipred_scratchpad);
275 av_freep(&h->edge_emu_buffer);
276 av_freep(&h->me.scratchpad);
277 return AVERROR(ENOMEM);
278 }
279
280 h->me.temp = h->me.scratchpad;
281
282 return 0;
283}
284
759001c5 285static int init_table_pools(H264Context *h)
2c541554
AK
286{
287 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
288 const int mb_array_size = h->mb_stride * h->mb_height;
289 const int b4_stride = h->mb_width * 4 + 1;
290 const int b4_array_size = b4_stride * h->mb_height * 4;
759001c5
AK
291
292 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
293 av_buffer_allocz);
294 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
295 sizeof(uint32_t), av_buffer_allocz);
296 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
297 sizeof(int16_t), av_buffer_allocz);
298 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
299
300 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
301 !h->ref_index_pool) {
302 av_buffer_pool_uninit(&h->qscale_table_pool);
303 av_buffer_pool_uninit(&h->mb_type_pool);
304 av_buffer_pool_uninit(&h->motion_val_pool);
305 av_buffer_pool_uninit(&h->ref_index_pool);
306 return AVERROR(ENOMEM);
307 }
308
309 return 0;
310}
311
312static int alloc_picture(H264Context *h, Picture *pic)
313{
2c541554
AK
314 int i, ret = 0;
315
316 av_assert0(!pic->f.data[0]);
317
9c9ede44
HL
318 pic->tf.f = &pic->f;
319 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
320 AV_GET_BUFFER_FLAG_REF : 0);
321 if (ret < 0)
322 goto fail;
323
324 h->linesize = pic->f.linesize[0];
325 h->uvlinesize = pic->f.linesize[1];
326
2c541554
AK
327 if (h->avctx->hwaccel) {
328 const AVHWAccel *hwaccel = h->avctx->hwaccel;
759001c5 329 av_assert0(!pic->hwaccel_picture_private);
2c541554 330 if (hwaccel->priv_data_size) {
759001c5
AK
331 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
332 if (!pic->hwaccel_priv_buf)
2c541554 333 return AVERROR(ENOMEM);
759001c5 334 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
2c541554
AK
335 }
336 }
2c541554 337
759001c5
AK
338 if (!h->qscale_table_pool) {
339 ret = init_table_pools(h);
340 if (ret < 0)
341 goto fail;
342 }
2c541554 343
759001c5
AK
344 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
345 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
346 if (!pic->qscale_table_buf || !pic->mb_type_buf)
347 goto fail;
2c541554 348
759001c5
AK
349 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
350 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
351
352 for (i = 0; i < 2; i++) {
353 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
354 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
355 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
356 goto fail;
2c541554 357
759001c5
AK
358 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
359 pic->ref_index[i] = pic->ref_index_buf[i]->data;
360 }
2c541554
AK
361
362 return 0;
363fail:
759001c5 364 unref_picture(h, pic);
2c541554
AK
365 return (ret < 0) ? ret : AVERROR(ENOMEM);
366}
367
368static inline int pic_is_unused(H264Context *h, Picture *pic)
369{
370 if (pic->f.data[0] == NULL)
371 return 1;
759001c5
AK
372 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
373 return 1;
2c541554
AK
374 return 0;
375}
376
377static int find_unused_picture(H264Context *h)
378{
379 int i;
380
759001c5 381 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
2c541554
AK
382 if (pic_is_unused(h, &h->DPB[i]))
383 break;
384 }
759001c5 385 if (i == MAX_PICTURE_COUNT)
2c541554
AK
386 return AVERROR_INVALIDDATA;
387
388 if (h->DPB[i].needs_realloc) {
389 h->DPB[i].needs_realloc = 0;
759001c5 390 unref_picture(h, &h->DPB[i]);
2c541554
AK
391 }
392
393 return i;
394}
395
0da71265 396/**
58c42af7
DB
397 * Check if the top & left blocks are available if needed and
398 * change the dc mode so it only uses the available blocks.
0da71265 399 */
e5d40372
DB
400int ff_h264_check_intra4x4_pred_mode(H264Context *h)
401{
e5d40372
DB
402 static const int8_t top[12] = {
403 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
404 };
405 static const int8_t left[12] = {
406 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
407 };
2bedc0e8
MN
408 int i;
409
e5d40372
DB
410 if (!(h->top_samples_available & 0x8000)) {
411 for (i = 0; i < 4; i++) {
412 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
413 if (status < 0) {
2c541554 414 av_log(h->avctx, AV_LOG_ERROR,
e5d40372 415 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
2c541554 416 status, h->mb_x, h->mb_y);
2bedc0e8 417 return -1;
e5d40372
DB
418 } else if (status) {
419 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
2bedc0e8
MN
420 }
421 }
422 }
423
e5d40372
DB
424 if ((h->left_samples_available & 0x8888) != 0x8888) {
425 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
426 for (i = 0; i < 4; i++)
427 if (!(h->left_samples_available & mask[i])) {
428 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
429 if (status < 0) {
2c541554 430 av_log(h->avctx, AV_LOG_ERROR,
e5d40372 431 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
2c541554 432 status, h->mb_x, h->mb_y);
2bedc0e8 433 return -1;
e5d40372
DB
434 } else if (status) {
435 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
2bedc0e8
MN
436 }
437 }
2bedc0e8
MN
438 }
439
440 return 0;
e5d40372 441} // FIXME cleanup like ff_h264_check_intra_pred_mode
2bedc0e8
MN
442
443/**
58c42af7
DB
444 * Check if the top & left blocks are available if needed and
445 * change the dc mode so it only uses the available blocks.
2bedc0e8 446 */
e5d40372
DB
447int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
448{
e5d40372
DB
449 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
450 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
451
452 if (mode > 6U) {
2c541554 453 av_log(h->avctx, AV_LOG_ERROR,
e5d40372 454 "out of range intra chroma pred mode at %d %d\n",
2c541554 455 h->mb_x, h->mb_y);
7440fe83 456 return -1;
5175b937 457 }
115329f1 458
e5d40372
DB
459 if (!(h->top_samples_available & 0x8000)) {
460 mode = top[mode];
461 if (mode < 0) {
2c541554 462 av_log(h->avctx, AV_LOG_ERROR,
e5d40372 463 "top block unavailable for requested intra mode at %d %d\n",
2c541554 464 h->mb_x, h->mb_y);
0da71265
MN
465 return -1;
466 }
467 }
115329f1 468
e5d40372
DB
469 if ((h->left_samples_available & 0x8080) != 0x8080) {
470 mode = left[mode];
471 if (is_chroma && (h->left_samples_available & 0x8080)) {
472 // mad cow disease mode, aka MBAFF + constrained_intra_pred
473 mode = ALZHEIMER_DC_L0T_PRED8x8 +
474 (!(h->left_samples_available & 0x8000)) +
475 2 * (mode == DC_128_PRED8x8);
d1d10e91 476 }
e5d40372 477 if (mode < 0) {
2c541554 478 av_log(h->avctx, AV_LOG_ERROR,
e5d40372 479 "left block unavailable for requested intra mode at %d %d\n",
2c541554 480 h->mb_x, h->mb_y);
0da71265 481 return -1;
115329f1 482 }
0da71265
MN
483 }
484
485 return mode;
486}
487
e5d40372
DB
488const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
489 int *dst_length, int *consumed, int length)
490{
0da71265
MN
491 int i, si, di;
492 uint8_t *dst;
24456882 493 int bufidx;
0da71265 494
e5d40372
DB
495 // src[0]&0x80; // forbidden bit
496 h->nal_ref_idc = src[0] >> 5;
497 h->nal_unit_type = src[0] & 0x1F;
0da71265 498
e5d40372
DB
499 src++;
500 length--;
e08715d3 501
58db34aa 502#define STARTCODE_TEST \
16c22122
DB
503 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
504 if (src[i + 2] != 3) { \
505 /* startcode, so we must be past the end */ \
506 length = i; \
507 } \
508 break; \
509 }
510
b250f9c6 511#if HAVE_FAST_UNALIGNED
58db34aa 512#define FIND_FIRST_ZERO \
16c22122
DB
513 if (i > 0 && !src[i]) \
514 i--; \
515 while (src[i]) \
516 i++
517
e5d40372 518#if HAVE_FAST_64BIT
e5d40372
DB
519 for (i = 0; i + 1 < length; i += 9) {
520 if (!((~AV_RN64A(src + i) &
521 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
522 0x8000800080008080ULL))
58db34aa
RB
523 continue;
524 FIND_FIRST_ZERO;
525 STARTCODE_TEST;
526 i -= 7;
527 }
e5d40372 528#else
e5d40372
DB
529 for (i = 0; i + 1 < length; i += 5) {
530 if (!((~AV_RN32A(src + i) &
531 (AV_RN32A(src + i) - 0x01000101U)) &
532 0x80008080U))
e08715d3 533 continue;
58db34aa
RB
534 FIND_FIRST_ZERO;
535 STARTCODE_TEST;
536 i -= 3;
537 }
538#endif
e08715d3 539#else
e5d40372
DB
540 for (i = 0; i + 1 < length; i += 2) {
541 if (src[i])
542 continue;
543 if (i > 0 && src[i - 1] == 0)
544 i--;
58db34aa 545 STARTCODE_TEST;
0da71265 546 }
58db34aa 547#endif
0da71265 548
e5d40372
DB
549 if (i >= length - 1) { // no escaped 0
550 *dst_length = length;
551 *consumed = length + 1; // +1 for the header
115329f1 552 return src;
0da71265
MN
553 }
554
e5d40372
DB
555 // use second escape buffer for inter data
556 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
557 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
558 length + FF_INPUT_BUFFER_PADDING_SIZE);
559 dst = h->rbsp_buffer[bufidx];
0da71265 560
e5d40372 561 if (dst == NULL)
ac658be5 562 return NULL;
ac658be5 563
593af7cd 564 memcpy(dst, src, i);
e5d40372
DB
565 si = di = i;
566 while (si + 2 < length) {
567 // remove escapes (very rare 1:2^22)
568 if (src[si + 2] > 3) {
569 dst[di++] = src[si++];
570 dst[di++] = src[si++];
571 } else if (src[si] == 0 && src[si + 1] == 0) {
572 if (src[si + 2] == 3) { // escape
573 dst[di++] = 0;
574 dst[di++] = 0;
575 si += 3;
c8470cc1 576 continue;
e5d40372 577 } else // next start code
593af7cd 578 goto nsc;
0da71265
MN
579 }
580
e5d40372 581 dst[di++] = src[si++];
0da71265 582 }
e5d40372
DB
583 while (si < length)
584 dst[di++] = src[si++];
0da71265 585
16c22122 586nsc:
e5d40372 587 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
d4369630 588
e5d40372
DB
589 *dst_length = di;
590 *consumed = si + 1; // +1 for the header
591 /* FIXME store exact number of bits in the getbitcontext
592 * (it is needed for decoding) */
0da71265
MN
593 return dst;
594}
595
85297319
DEP
596/**
597 * Identify the exact end of the bitstream
598 * @return the length of the trailing, or 0 if damaged
599 */
b691fd7a 600static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
e5d40372
DB
601{
602 int v = *src;
0da71265
MN
603 int r;
604
2c541554 605 tprintf(h->avctx, "rbsp trailing %X\n", v);
0da71265 606
e5d40372
DB
607 for (r = 1; r < 9; r++) {
608 if (v & 1)
609 return r;
610 v >>= 1;
0da71265
MN
611 }
612 return 0;
613}
614
e5d40372
DB
615static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
616 int height, int y_offset, int list)
617{
16c22122 618 int raw_my = h->mv_cache[list][scan8[n]][1];
fb845ffd
RB
619 int filter_height_up = (raw_my & 3) ? 2 : 0;
620 int filter_height_down = (raw_my & 3) ? 3 : 0;
16c22122
DB
621 int full_my = (raw_my >> 2) + y_offset;
622 int top = full_my - filter_height_up;
623 int bottom = full_my + filter_height_down + height;
6a9c8594
AS
624
625 return FFMAX(abs(top), bottom);
626}
627
e5d40372
DB
628static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
629 int height, int y_offset, int list0,
630 int list1, int *nrefs)
631{
6a9c8594
AS
632 int my;
633
da6be8fc 634 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
6a9c8594 635
e5d40372
DB
636 if (list0) {
637 int ref_n = h->ref_cache[0][scan8[n]];
638 Picture *ref = &h->ref_list[0][ref_n];
6a9c8594
AS
639
640 // Error resilience puts the current picture in the ref list.
641 // Don't try to wait on these as it will cause a deadlock.
642 // Fields can wait on each other, though.
16c22122 643 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
759001c5 644 (ref->reference & 3) != h->picture_structure) {
6a9c8594 645 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
e5d40372
DB
646 if (refs[0][ref_n] < 0)
647 nrefs[0] += 1;
6a9c8594
AS
648 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
649 }
650 }
651
e5d40372
DB
652 if (list1) {
653 int ref_n = h->ref_cache[1][scan8[n]];
654 Picture *ref = &h->ref_list[1][ref_n];
6a9c8594 655
759001c5
AK
656 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
657 (ref->reference & 3) != h->picture_structure) {
6a9c8594 658 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
e5d40372
DB
659 if (refs[1][ref_n] < 0)
660 nrefs[1] += 1;
6a9c8594
AS
661 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
662 }
663 }
664}
665
666/**
667 * Wait until all reference frames are available for MC operations.
668 *
669 * @param h the H264 context
670 */
e5d40372
DB
671static void await_references(H264Context *h)
672{
e5d40372 673 const int mb_xy = h->mb_xy;
759001c5 674 const int mb_type = h->cur_pic.mb_type[mb_xy];
6a9c8594 675 int refs[2][48];
e5d40372 676 int nrefs[2] = { 0 };
6a9c8594
AS
677 int ref, list;
678
679 memset(refs, -1, sizeof(refs));
680
e5d40372 681 if (IS_16X16(mb_type)) {
6a9c8594 682 get_lowest_part_y(h, refs, 0, 16, 0,
e5d40372
DB
683 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
684 } else if (IS_16X8(mb_type)) {
6a9c8594 685 get_lowest_part_y(h, refs, 0, 8, 0,
e5d40372 686 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
6a9c8594 687 get_lowest_part_y(h, refs, 8, 8, 8,
e5d40372
DB
688 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
689 } else if (IS_8X16(mb_type)) {
6a9c8594 690 get_lowest_part_y(h, refs, 0, 16, 0,
e5d40372 691 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
6a9c8594 692 get_lowest_part_y(h, refs, 4, 16, 0,
e5d40372
DB
693 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
694 } else {
6a9c8594
AS
695 int i;
696
697 assert(IS_8X8(mb_type));
698
e5d40372
DB
699 for (i = 0; i < 4; i++) {
700 const int sub_mb_type = h->sub_mb_type[i];
701 const int n = 4 * i;
702 int y_offset = (i & 2) << 2;
703
704 if (IS_SUB_8X8(sub_mb_type)) {
705 get_lowest_part_y(h, refs, n, 8, y_offset,
706 IS_DIR(sub_mb_type, 0, 0),
707 IS_DIR(sub_mb_type, 0, 1),
708 nrefs);
709 } else if (IS_SUB_8X4(sub_mb_type)) {
710 get_lowest_part_y(h, refs, n, 4, y_offset,
711 IS_DIR(sub_mb_type, 0, 0),
712 IS_DIR(sub_mb_type, 0, 1),
713 nrefs);
714 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
715 IS_DIR(sub_mb_type, 0, 0),
716 IS_DIR(sub_mb_type, 0, 1),
717 nrefs);
718 } else if (IS_SUB_4X8(sub_mb_type)) {
719 get_lowest_part_y(h, refs, n, 8, y_offset,
720 IS_DIR(sub_mb_type, 0, 0),
721 IS_DIR(sub_mb_type, 0, 1),
722 nrefs);
723 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
724 IS_DIR(sub_mb_type, 0, 0),
725 IS_DIR(sub_mb_type, 0, 1),
726 nrefs);
727 } else {
6a9c8594
AS
728 int j;
729 assert(IS_SUB_4X4(sub_mb_type));
e5d40372
DB
730 for (j = 0; j < 4; j++) {
731 int sub_y_offset = y_offset + 2 * (j & 2);
732 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
733 IS_DIR(sub_mb_type, 0, 0),
734 IS_DIR(sub_mb_type, 0, 1),
735 nrefs);
6a9c8594
AS
736 }
737 }
738 }
739 }
740
e5d40372
DB
741 for (list = h->list_count - 1; list >= 0; list--)
742 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
6a9c8594 743 int row = refs[list][ref];
e5d40372
DB
744 if (row >= 0) {
745 Picture *ref_pic = &h->ref_list[list][ref];
759001c5 746 int ref_field = ref_pic->reference - 1;
6a9c8594 747 int ref_field_picture = ref_pic->field_picture;
2c541554 748 int pic_height = 16 * h->mb_height >> ref_field_picture;
6a9c8594 749
82313eaa 750 row <<= MB_MBAFF(h);
6a9c8594
AS
751 nrefs[list]--;
752
7fa00653 753 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
759001c5 754 ff_thread_await_progress(&ref_pic->tf,
e5d40372
DB
755 FFMIN((row >> 1) - !(row & 1),
756 pic_height - 1),
757 1);
759001c5 758 ff_thread_await_progress(&ref_pic->tf,
e5d40372
DB
759 FFMIN((row >> 1), pic_height - 1),
760 0);
7fa00653 761 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
759001c5 762 ff_thread_await_progress(&ref_pic->tf,
e5d40372
DB
763 FFMIN(row * 2 + ref_field,
764 pic_height - 1),
765 0);
7fa00653 766 } else if (FIELD_PICTURE(h)) {
759001c5 767 ff_thread_await_progress(&ref_pic->tf,
e5d40372
DB
768 FFMIN(row, pic_height - 1),
769 ref_field);
770 } else {
759001c5 771 ff_thread_await_progress(&ref_pic->tf,
e5d40372
DB
772 FFMIN(row, pic_height - 1),
773 0);
6a9c8594
AS
774 }
775 }
776 }
66c6b5e2 777}
66c6b5e2 778
e5d40372
DB
779static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
780 int n, int square, int height,
781 int delta, int list,
782 uint8_t *dest_y, uint8_t *dest_cb,
783 uint8_t *dest_cr,
784 int src_x_offset, int src_y_offset,
785 qpel_mc_func *qpix_op,
786 h264_chroma_mc_func chroma_op,
787 int pixel_shift, int chroma_idc)
05fb63f5 788{
e5d40372
DB
789 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
790 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
791 const int luma_xy = (mx & 3) + ((my & 3) << 2);
792 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
793 uint8_t *src_y = pic->f.data[0] + offset;
794 uint8_t *src_cb, *src_cr;
fae6fd5b
RB
795 int extra_width = 0;
796 int extra_height = 0;
e5d40372
DB
797 int emu = 0;
798 const int full_mx = mx >> 2;
799 const int full_my = my >> 2;
2c541554 800 const int pic_width = 16 * h->mb_width;
da6be8fc 801 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
229d263c 802 int ysh;
115329f1 803
e5d40372
DB
804 if (mx & 7)
805 extra_width -= 3;
806 if (my & 7)
807 extra_height -= 3;
808
809 if (full_mx < 0 - extra_width ||
810 full_my < 0 - extra_height ||
811 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
812 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
2c541554 813 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
8c53d39e
RB
814 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
815 h->mb_linesize,
816 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
817 full_my - 2, pic_width, pic_height);
2c541554 818 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
e5d40372
DB
819 emu = 1;
820 }
821
822 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
823 if (!square)
5d18eaad 824 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
115329f1 825
2c541554 826 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
e5d40372 827 return;
7b442ad9 828
e5d40372 829 if (chroma_idc == 3 /* yuv444 */) {
657ccb5a 830 src_cb = pic->f.data[1] + offset;
e5d40372 831 if (emu) {
2c541554 832 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
8c53d39e
RB
833 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
834 h->mb_linesize,
835 16 + 5, 16 + 5 /*FIXME*/,
836 full_mx - 2, full_my - 2,
837 pic_width, pic_height);
2c541554 838 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
c90b9442 839 }
e5d40372
DB
840 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
841 if (!square)
c90b9442 842 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
c90b9442 843
657ccb5a 844 src_cr = pic->f.data[2] + offset;
e5d40372 845 if (emu) {
2c541554 846 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
8c53d39e
RB
847 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
848 h->mb_linesize,
849 16 + 5, 16 + 5 /*FIXME*/,
850 full_mx - 2, full_my - 2,
851 pic_width, pic_height);
2c541554 852 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
c90b9442 853 }
e5d40372
DB
854 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
855 if (!square)
c90b9442 856 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
c90b9442
JGG
857 return;
858 }
859
05fb63f5 860 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
da6be8fc 861 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
5d18eaad 862 // chroma offset when predicting from a field of opposite parity
759001c5 863 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
e5d40372 864 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
5d18eaad 865 }
229d263c 866
e5d40372
DB
867 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
868 (my >> ysh) * h->mb_uvlinesize;
869 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
870 (my >> ysh) * h->mb_uvlinesize;
5d18eaad 871
e5d40372 872 if (emu) {
2c541554 873 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
8c53d39e
RB
874 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
875 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
2c541554 876 src_cb = h->edge_emu_buffer;
0da71265 877 }
e5d40372
DB
878 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
879 height >> (chroma_idc == 1 /* yuv420 */),
880 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
0da71265 881
e5d40372 882 if (emu) {
2c541554 883 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
8c53d39e
RB
884 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
885 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
2c541554 886 src_cr = h->edge_emu_buffer;
0da71265 887 }
05fb63f5 888 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
e5d40372 889 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
0da71265
MN
890}
891
e5d40372
DB
892static av_always_inline void mc_part_std(H264Context *h, int n, int square,
893 int height, int delta,
894 uint8_t *dest_y, uint8_t *dest_cb,
895 uint8_t *dest_cr,
896 int x_offset, int y_offset,
897 qpel_mc_func *qpix_put,
898 h264_chroma_mc_func chroma_put,
899 qpel_mc_func *qpix_avg,
900 h264_chroma_mc_func chroma_avg,
901 int list0, int list1,
902 int pixel_shift, int chroma_idc)
05fb63f5 903{
e5d40372
DB
904 qpel_mc_func *qpix_op = qpix_put;
905 h264_chroma_mc_func chroma_op = chroma_put;
115329f1 906
e5d40372 907 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
05fb63f5 908 if (chroma_idc == 3 /* yuv444 */) {
e5d40372
DB
909 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
910 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
05fb63f5 911 } else if (chroma_idc == 2 /* yuv422 */) {
e5d40372
DB
912 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
913 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
914 } else { /* yuv420 */
915 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
916 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
c90b9442 917 }
2c541554 918 x_offset += 8 * h->mb_x;
da6be8fc 919 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
115329f1 920
e5d40372
DB
921 if (list0) {
922 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
c2d33742 923 mc_dir_part(h, ref, n, square, height, delta, 0,
e5d40372
DB
924 dest_y, dest_cb, dest_cr, x_offset, y_offset,
925 qpix_op, chroma_op, pixel_shift, chroma_idc);
0da71265 926
e5d40372
DB
927 qpix_op = qpix_avg;
928 chroma_op = chroma_avg;
0da71265
MN
929 }
930
e5d40372
DB
931 if (list1) {
932 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
c2d33742 933 mc_dir_part(h, ref, n, square, height, delta, 1,
e5d40372
DB
934 dest_y, dest_cb, dest_cr, x_offset, y_offset,
935 qpix_op, chroma_op, pixel_shift, chroma_idc);
0da71265
MN
936 }
937}
938
e5d40372
DB
939static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
940 int height, int delta,
941 uint8_t *dest_y, uint8_t *dest_cb,
942 uint8_t *dest_cr,
943 int x_offset, int y_offset,
944 qpel_mc_func *qpix_put,
945 h264_chroma_mc_func chroma_put,
946 h264_weight_func luma_weight_op,
947 h264_weight_func chroma_weight_op,
948 h264_biweight_func luma_weight_avg,
949 h264_biweight_func chroma_weight_avg,
950 int list0, int list1,
951 int pixel_shift, int chroma_idc)
952{
c2d33742 953 int chroma_height;
9f2d1b4f 954
e5d40372 955 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
05fb63f5 956 if (chroma_idc == 3 /* yuv444 */) {
e5d40372 957 chroma_height = height;
c90b9442 958 chroma_weight_avg = luma_weight_avg;
e5d40372
DB
959 chroma_weight_op = luma_weight_op;
960 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
961 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
05fb63f5 962 } else if (chroma_idc == 2 /* yuv422 */) {
c2d33742 963 chroma_height = height;
e5d40372
DB
964 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
965 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
966 } else { /* yuv420 */
c2d33742 967 chroma_height = height >> 1;
e5d40372
DB
968 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
969 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
c90b9442 970 }
2c541554 971 x_offset += 8 * h->mb_x;
da6be8fc 972 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
115329f1 973
e5d40372 974 if (list0 && list1) {
9f2d1b4f
LM
975 /* don't optimize for luma-only case, since B-frames usually
976 * use implicit weights => chroma too. */
a394959b
JG
977 uint8_t *tmp_cb = h->bipred_scratchpad;
978 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
979 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
e5d40372
DB
980 int refn0 = h->ref_cache[0][scan8[n]];
981 int refn1 = h->ref_cache[1][scan8[n]];
9f2d1b4f 982
c2d33742 983 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
9f2d1b4f 984 dest_y, dest_cb, dest_cr,
05fb63f5
RB
985 x_offset, y_offset, qpix_put, chroma_put,
986 pixel_shift, chroma_idc);
c2d33742 987 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
9f2d1b4f 988 tmp_y, tmp_cb, tmp_cr,
05fb63f5
RB
989 x_offset, y_offset, qpix_put, chroma_put,
990 pixel_shift, chroma_idc);
9f2d1b4f 991
e5d40372 992 if (h->use_weight == 2) {
2c541554 993 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
9f2d1b4f 994 int weight1 = 64 - weight0;
e5d40372
DB
995 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
996 height, 5, weight0, weight1, 0);
c2d33742
RB
997 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
998 chroma_height, 5, weight0, weight1, 0);
999 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1000 chroma_height, 5, weight0, weight1, 0);
e5d40372
DB
1001 } else {
1002 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1003 h->luma_log2_weight_denom,
1004 h->luma_weight[refn0][0][0],
1005 h->luma_weight[refn1][1][0],
1006 h->luma_weight[refn0][0][1] +
1007 h->luma_weight[refn1][1][1]);
1008 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1009 h->chroma_log2_weight_denom,
1010 h->chroma_weight[refn0][0][0][0],
1011 h->chroma_weight[refn1][1][0][0],
1012 h->chroma_weight[refn0][0][0][1] +
1013 h->chroma_weight[refn1][1][0][1]);
1014 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1015 h->chroma_log2_weight_denom,
1016 h->chroma_weight[refn0][0][1][0],
1017 h->chroma_weight[refn1][1][1][0],
1018 h->chroma_weight[refn0][0][1][1] +
1019 h->chroma_weight[refn1][1][1][1]);
9f2d1b4f 1020 }
e5d40372
DB
1021 } else {
1022 int list = list1 ? 1 : 0;
1023 int refn = h->ref_cache[list][scan8[n]];
1024 Picture *ref = &h->ref_list[list][refn];
c2d33742 1025 mc_dir_part(h, ref, n, square, height, delta, list,
9f2d1b4f 1026 dest_y, dest_cb, dest_cr, x_offset, y_offset,
05fb63f5 1027 qpix_put, chroma_put, pixel_shift, chroma_idc);
9f2d1b4f 1028
e5d40372
DB
1029 luma_weight_op(dest_y, h->mb_linesize, height,
1030 h->luma_log2_weight_denom,
1031 h->luma_weight[refn][list][0],
1032 h->luma_weight[refn][list][1]);
1033 if (h->use_weight_chroma) {
1034 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1035 h->chroma_log2_weight_denom,
1036 h->chroma_weight[refn][list][0][0],
1037 h->chroma_weight[refn][list][0][1]);
1038 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1039 h->chroma_log2_weight_denom,
1040 h->chroma_weight[refn][list][1][0],
1041 h->chroma_weight[refn][list][1][1]);
9f2d1b4f
LM
1042 }
1043 }
1044}
1045
e5d40372
DB
1046static av_always_inline void prefetch_motion(H264Context *h, int list,
1047 int pixel_shift, int chroma_idc)
27209bb1 1048{
513fbd8e
LM
1049 /* fetch pixels for estimated mv 4 macroblocks ahead
1050 * optimized for 64byte cache lines */
513fbd8e 1051 const int refn = h->ref_cache[list][scan8[0]];
e5d40372 1052 if (refn >= 0) {
2c541554
AK
1053 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1054 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
657ccb5a 1055 uint8_t **src = h->ref_list[list][refn].f.data;
e5d40372 1056 int off = (mx << pixel_shift) +
2c541554 1057 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
e5d40372 1058 (64 << pixel_shift);
2c541554 1059 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
05fb63f5 1060 if (chroma_idc == 3 /* yuv444 */) {
2c541554
AK
1061 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1062 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
e5d40372
DB
1063 } else {
1064 off = ((mx >> 1) << pixel_shift) +
2c541554 1065 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
e5d40372 1066 (64 << pixel_shift);
2c541554 1067 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
c90b9442 1068 }
513fbd8e
LM
1069 }
1070}
1071
e5d40372
DB
1072static void free_tables(H264Context *h, int free_rbsp)
1073{
7978debd 1074 int i;
afebe2f7 1075 H264Context *hx;
6a9c8594 1076
0da71265 1077 av_freep(&h->intra4x4_pred_mode);
e5017ab8
LA
1078 av_freep(&h->chroma_pred_mode_table);
1079 av_freep(&h->cbp_table);
9e528114
LA
1080 av_freep(&h->mvd_table[0]);
1081 av_freep(&h->mvd_table[1]);
5ad984c9 1082 av_freep(&h->direct_table);
0da71265
MN
1083 av_freep(&h->non_zero_count);
1084 av_freep(&h->slice_table_base);
e5d40372 1085 h->slice_table = NULL;
c988f975 1086 av_freep(&h->list_counts);
e5017ab8 1087
0da71265 1088 av_freep(&h->mb2b_xy);
d43c1922 1089 av_freep(&h->mb2br_xy);
9f2d1b4f 1090
759001c5
AK
1091 av_buffer_pool_uninit(&h->qscale_table_pool);
1092 av_buffer_pool_uninit(&h->mb_type_pool);
1093 av_buffer_pool_uninit(&h->motion_val_pool);
1094 av_buffer_pool_uninit(&h->ref_index_pool);
1095
1096 if (free_rbsp && h->DPB) {
1097 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1098 unref_picture(h, &h->DPB[i]);
2c541554 1099 av_freep(&h->DPB);
2c541554 1100 } else if (h->DPB) {
759001c5 1101 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2c541554
AK
1102 h->DPB[i].needs_realloc = 1;
1103 }
1104
1105 h->cur_pic_ptr = NULL;
1106
e5d40372 1107 for (i = 0; i < MAX_THREADS; i++) {
afebe2f7 1108 hx = h->thread_context[i];
e5d40372
DB
1109 if (!hx)
1110 continue;
afebe2f7
1111 av_freep(&hx->top_borders[1]);
1112 av_freep(&hx->top_borders[0]);
a394959b 1113 av_freep(&hx->bipred_scratchpad);
2c541554
AK
1114 av_freep(&hx->edge_emu_buffer);
1115 av_freep(&hx->dc_val_base);
1116 av_freep(&hx->me.scratchpad);
1117 av_freep(&hx->er.mb_index2xy);
1118 av_freep(&hx->er.error_status_table);
1119 av_freep(&hx->er.er_temp_buffer);
1120 av_freep(&hx->er.mbintra_table);
1121 av_freep(&hx->er.mbskip_table);
1122
e5d40372 1123 if (free_rbsp) {
fcb7e535
RB
1124 av_freep(&hx->rbsp_buffer[1]);
1125 av_freep(&hx->rbsp_buffer[0]);
1126 hx->rbsp_buffer_size[0] = 0;
1127 hx->rbsp_buffer_size[1] = 0;
91078926 1128 }
e5d40372
DB
1129 if (i)
1130 av_freep(&h->thread_context[i]);
afebe2f7 1131 }
0da71265
MN
1132}
1133
e5d40372
DB
1134static void init_dequant8_coeff_table(H264Context *h)
1135{
1136 int i, j, q, x;
1137 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
239ea04c 1138
e5d40372 1139 for (i = 0; i < 6; i++) {
c90b9442 1140 h->dequant8_coeff[i] = h->dequant8_buffer[i];
e5d40372
DB
1141 for (j = 0; j < i; j++)
1142 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1143 64 * sizeof(uint8_t))) {
c90b9442
JGG
1144 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1145 break;
1146 }
e5d40372 1147 if (j < i)
c90b9442 1148 continue;
239ea04c 1149
e5d40372 1150 for (q = 0; q < max_qp + 1; q++) {
d9ec210b 1151 int shift = div6[q];
e5d40372
DB
1152 int idx = rem6[q];
1153 for (x = 0; x < 64; x++)
1154 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1155 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1156 h->pps.scaling_matrix8[i][x]) << shift;
239ea04c
LM
1157 }
1158 }
1159}
1160
e5d40372
DB
1161static void init_dequant4_coeff_table(H264Context *h)
1162{
1163 int i, j, q, x;
1164 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1165 for (i = 0; i < 6; i++) {
239ea04c 1166 h->dequant4_coeff[i] = h->dequant4_buffer[i];
e5d40372
DB
1167 for (j = 0; j < i; j++)
1168 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1169 16 * sizeof(uint8_t))) {
239ea04c
LM
1170 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1171 break;
1172 }
e5d40372 1173 if (j < i)
239ea04c
LM
1174 continue;
1175
e5d40372 1176 for (q = 0; q < max_qp + 1; q++) {
d9ec210b 1177 int shift = div6[q] + 2;
e5d40372
DB
1178 int idx = rem6[q];
1179 for (x = 0; x < 16; x++)
1180 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1181 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1182 h->pps.scaling_matrix4[i][x]) << shift;
239ea04c
LM
1183 }
1184 }
1185}
1186
e5d40372
DB
1187static void init_dequant_tables(H264Context *h)
1188{
1189 int i, x;
239ea04c 1190 init_dequant4_coeff_table(h);
e5d40372 1191 if (h->pps.transform_8x8_mode)
239ea04c 1192 init_dequant8_coeff_table(h);
e5d40372
DB
1193 if (h->sps.transform_bypass) {
1194 for (i = 0; i < 6; i++)
1195 for (x = 0; x < 16; x++)
1196 h->dequant4_coeff[i][0][x] = 1 << 6;
1197 if (h->pps.transform_8x8_mode)
1198 for (i = 0; i < 6; i++)
1199 for (x = 0; x < 64; x++)
1200 h->dequant8_coeff[i][0][x] = 1 << 6;
239ea04c
LM
1201 }
1202}
1203
e5d40372
DB
1204int ff_h264_alloc_tables(H264Context *h)
1205{
16c22122
DB
1206 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1207 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
2c541554 1208 int x, y, i;
e5d40372 1209
2c541554 1210 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
e5d40372 1211 row_mb_num * 8 * sizeof(uint8_t), fail)
2c541554 1212 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
e5d40372 1213 big_mb_num * 48 * sizeof(uint8_t), fail)
2c541554
AK
1214 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1215 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1216 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
e5d40372 1217 big_mb_num * sizeof(uint16_t), fail)
2c541554 1218 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
e5d40372 1219 big_mb_num * sizeof(uint8_t), fail)
2c541554 1220 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
e5d40372 1221 16 * row_mb_num * sizeof(uint8_t), fail);
2c541554 1222 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
e5d40372 1223 16 * row_mb_num * sizeof(uint8_t), fail);
2c541554 1224 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
e5d40372 1225 4 * big_mb_num * sizeof(uint8_t), fail);
2c541554 1226 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
e5d40372
DB
1227 big_mb_num * sizeof(uint8_t), fail)
1228
1229 memset(h->slice_table_base, -1,
2c541554
AK
1230 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1231 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
e5d40372 1232
2c541554 1233 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
e5d40372 1234 big_mb_num * sizeof(uint32_t), fail);
2c541554 1235 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
e5d40372 1236 big_mb_num * sizeof(uint32_t), fail);
2c541554
AK
1237 for (y = 0; y < h->mb_height; y++)
1238 for (x = 0; x < h->mb_width; x++) {
1239 const int mb_xy = x + y * h->mb_stride;
e5d40372
DB
1240 const int b_xy = 4 * x + 4 * y * h->b_stride;
1241
1242 h->mb2b_xy[mb_xy] = b_xy;
2c541554 1243 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
0da71265 1244 }
9f2d1b4f 1245
e5d40372 1246 if (!h->dequant4_coeff[0])
56edbd81
LM
1247 init_dequant_tables(h);
1248
2c541554 1249 if (!h->DPB) {
759001c5 1250 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
2c541554
AK
1251 if (!h->DPB)
1252 return AVERROR(ENOMEM);
759001c5 1253 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2c541554
AK
1254 avcodec_get_frame_defaults(&h->DPB[i].f);
1255 avcodec_get_frame_defaults(&h->cur_pic.f);
1256 }
1257
0da71265 1258 return 0;
e5d40372 1259
0da71265 1260fail:
91078926 1261 free_tables(h, 1);
0da71265
MN
1262 return -1;
1263}
1264
afebe2f7
1265/**
1266 * Mimic alloc_tables(), but for every context thread.
1267 */
e5d40372
DB
1268static void clone_tables(H264Context *dst, H264Context *src, int i)
1269{
2c541554 1270 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
e5d40372
DB
1271 dst->non_zero_count = src->non_zero_count;
1272 dst->slice_table = src->slice_table;
1273 dst->cbp_table = src->cbp_table;
1274 dst->mb2b_xy = src->mb2b_xy;
1275 dst->mb2br_xy = src->mb2br_xy;
1276 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
2c541554
AK
1277 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1278 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
e5d40372
DB
1279 dst->direct_table = src->direct_table;
1280 dst->list_counts = src->list_counts;
2c541554
AK
1281 dst->DPB = src->DPB;
1282 dst->cur_pic_ptr = src->cur_pic_ptr;
1283 dst->cur_pic = src->cur_pic;
a394959b 1284 dst->bipred_scratchpad = NULL;
2c541554
AK
1285 dst->edge_emu_buffer = NULL;
1286 dst->me.scratchpad = NULL;
1287 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
e5d40372 1288 src->sps.chroma_format_idc);
afebe2f7
1289}
1290
1291/**
1292 * Init context
1293 * Allocate buffers which are not shared amongst multiple threads.
1294 */
e5d40372
DB
1295static int context_init(H264Context *h)
1296{
2c541554
AK
1297 ERContext *er = &h->er;
1298 int mb_array_size = h->mb_height * h->mb_stride;
1299 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1300 int c_size = h->mb_stride * (h->mb_height + 1);
1301 int yc_size = y_size + 2 * c_size;
1302 int x, y, i;
1303
1304 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1305 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1306 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1307 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
e5d40372
DB
1308
1309 h->ref_cache[0][scan8[5] + 1] =
1310 h->ref_cache[0][scan8[7] + 1] =
1311 h->ref_cache[0][scan8[13] + 1] =
1312 h->ref_cache[1][scan8[5] + 1] =
1313 h->ref_cache[1][scan8[7] + 1] =
1314 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
145061a1 1315
0b499c9b
RB
1316 if (CONFIG_ERROR_RESILIENCE) {
1317 /* init ER */
1318 er->avctx = h->avctx;
1319 er->dsp = &h->dsp;
1320 er->decode_mb = h264_er_decode_mb;
1321 er->opaque = h;
1322 er->quarter_sample = 1;
1323
1324 er->mb_num = h->mb_num;
1325 er->mb_width = h->mb_width;
1326 er->mb_height = h->mb_height;
1327 er->mb_stride = h->mb_stride;
1328 er->b8_stride = h->mb_width * 2 + 1;
2c541554 1329
0b499c9b
RB
1330 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1331 fail); // error ressilience code looks cleaner with this
1332 for (y = 0; y < h->mb_height; y++)
1333 for (x = 0; x < h->mb_width; x++)
1334 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
2c541554 1335
0b499c9b 1336 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
16c22122 1337 h->mb_stride + h->mb_width;
2c541554 1338
0b499c9b
RB
1339 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1340 mb_array_size * sizeof(uint8_t), fail);
2c541554 1341
0b499c9b
RB
1342 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1343 memset(er->mbintra_table, 1, mb_array_size);
2c541554 1344
0b499c9b 1345 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
2c541554 1346
0b499c9b
RB
1347 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1348 fail);
1349
1350 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1351 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1352 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1353 er->dc_val[2] = er->dc_val[1] + c_size;
1354 for (i = 0; i < yc_size; i++)
1355 h->dc_val_base[i] = 1024;
1356 }
54974c62 1357
afebe2f7 1358 return 0;
e5d40372 1359
afebe2f7
1360fail:
1361 return -1; // free_tables will clean up for us
1362}
1363
61c6eef5
JG
1364static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1365 int parse_extradata);
9855b2e3 1366
05e95319
HC
1367int ff_h264_decode_extradata(H264Context *h)
1368{
2c541554 1369 AVCodecContext *avctx = h->avctx;
9855b2e3 1370
e5d40372 1371 if (avctx->extradata[0] == 1) {
9855b2e3
MN
1372 int i, cnt, nalsize;
1373 unsigned char *p = avctx->extradata;
1374
1375 h->is_avc = 1;
1376
e5d40372 1377 if (avctx->extradata_size < 7) {
9855b2e3
MN
1378 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1379 return -1;
1380 }
1381 /* sps and pps in the avcC always have length coded with 2 bytes,
e5d40372 1382 * so put a fake nal_length_size = 2 while parsing them */
9855b2e3
MN
1383 h->nal_length_size = 2;
1384 // Decode sps from avcC
e5d40372
DB
1385 cnt = *(p + 5) & 0x1f; // Number of sps
1386 p += 6;
9855b2e3
MN
1387 for (i = 0; i < cnt; i++) {
1388 nalsize = AV_RB16(p) + 2;
d1186ff7
LA
1389 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1390 return -1;
61c6eef5 1391 if (decode_nal_units(h, p, nalsize, 1) < 0) {
e5d40372
DB
1392 av_log(avctx, AV_LOG_ERROR,
1393 "Decoding sps %d from avcC failed\n", i);
9855b2e3
MN
1394 return -1;
1395 }
1396 p += nalsize;
1397 }
1398 // Decode pps from avcC
1399 cnt = *(p++); // Number of pps
1400 for (i = 0; i < cnt; i++) {
1401 nalsize = AV_RB16(p) + 2;
d1186ff7
LA
1402 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1403 return -1;
61c6eef5 1404 if (decode_nal_units(h, p, nalsize, 1) < 0) {
e5d40372
DB
1405 av_log(avctx, AV_LOG_ERROR,
1406 "Decoding pps %d from avcC failed\n", i);
9855b2e3
MN
1407 return -1;
1408 }
1409 p += nalsize;
1410 }
e5d40372 1411 // Now store right nal length size, that will be used to parse all other nals
0c17beba 1412 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
9855b2e3
MN
1413 } else {
1414 h->is_avc = 0;
61c6eef5 1415 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1) < 0)
9855b2e3
MN
1416 return -1;
1417 }
05e95319
HC
1418 return 0;
1419}
1420
e5d40372
DB
1421av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1422{
1423 H264Context *h = avctx->priv_data;
ea2bb12e 1424 int i;
05e95319 1425
2c541554 1426 h->avctx = avctx;
48d0fd2d 1427
48d0fd2d
AK
1428 h->bit_depth_luma = 8;
1429 h->chroma_format_idc = 1;
1430
1431 ff_h264dsp_init(&h->h264dsp, 8, 1);
1432 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1433 ff_h264qpel_init(&h->h264qpel, 8);
1434 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1435
1436 h->dequant_coeff_pps = -1;
1437
1438 /* needed so that IDCT permutation is known early */
85deb51a
RB
1439 if (CONFIG_ERROR_RESILIENCE)
1440 ff_dsputil_init(&h->dsp, h->avctx);
48d0fd2d
AK
1441 ff_videodsp_init(&h->vdsp, 8);
1442
1443 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1444 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
05e95319 1445
2c541554 1446 h->picture_structure = PICT_FRAME;
2c541554
AK
1447 h->slice_context_count = 1;
1448 h->workaround_bugs = avctx->workaround_bugs;
1449 h->flags = avctx->flags;
05e95319 1450
e5d40372
DB
1451 /* set defaults */
1452 // s->decode_mb = ff_h263_decode_mb;
e5d40372 1453 if (!avctx->has_b_frames)
2c541554 1454 h->low_delay = 1;
05e95319
HC
1455
1456 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1457
1458 ff_h264_decode_init_vlc();
1459
16c22122 1460 h->pixel_shift = 0;
19a0729b 1461 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
6e3ef511 1462
05e95319 1463 h->thread_context[0] = h;
e5d40372 1464 h->outputed_poc = h->next_outputed_poc = INT_MIN;
ea2bb12e
RB
1465 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1466 h->last_pocs[i] = INT_MIN;
e5d40372
DB
1467 h->prev_poc_msb = 1 << 16;
1468 h->x264_build = -1;
05e95319 1469 ff_h264_reset_sei(h);
36ef5369 1470 if (avctx->codec_id == AV_CODEC_ID_H264) {
e5d40372 1471 if (avctx->ticks_per_frame == 1)
2c541554 1472 h->avctx->time_base.den *= 2;
05e95319
HC
1473 avctx->ticks_per_frame = 2;
1474 }
1475
e5d40372 1476 if (avctx->extradata_size > 0 && avctx->extradata &&
05e95319
HC
1477 ff_h264_decode_extradata(h))
1478 return -1;
1479
e5d40372 1480 if (h->sps.bitstream_restriction_flag &&
2c541554
AK
1481 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1482 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1483 h->low_delay = 0;
db8cb47d 1484 }
9855b2e3 1485
759001c5
AK
1486 avctx->internal->allocate_progress = 1;
1487
0da71265
MN
1488 return 0;
1489}
1490
e5d40372 1491#define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
2c541554
AK
1492#undef REBASE_PICTURE
1493#define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1494 ((pic && pic >= old_ctx->DPB && \
16c22122
DB
1495 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1496 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
e5d40372
DB
1497
1498static void copy_picture_range(Picture **to, Picture **from, int count,
2c541554
AK
1499 H264Context *new_base,
1500 H264Context *old_base)
6a9c8594
AS
1501{
1502 int i;
1503
e5d40372 1504 for (i = 0; i < count; i++) {
6a9c8594 1505 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
2c541554 1506 IN_RANGE(from[i], old_base->DPB,
759001c5 1507 sizeof(Picture) * MAX_PICTURE_COUNT) ||
6a9c8594
AS
1508 !from[i]));
1509 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1510 }
1511}
1512
1513static void copy_parameter_set(void **to, void **from, int count, int size)
1514{
1515 int i;
1516
e5d40372
DB
1517 for (i = 0; i < count; i++) {
1518 if (to[i] && !from[i])
1519 av_freep(&to[i]);
1520 else if (from[i] && !to[i])
1521 to[i] = av_malloc(size);
6a9c8594 1522
e5d40372
DB
1523 if (from[i])
1524 memcpy(to[i], from[i], size);
6a9c8594
AS
1525 }
1526}
1527
e5d40372
DB
1528static int decode_init_thread_copy(AVCodecContext *avctx)
1529{
1530 H264Context *h = avctx->priv_data;
6a9c8594 1531
f3a29b75
JR
1532 if (!avctx->internal->is_copy)
1533 return 0;
6a9c8594
AS
1534 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1535 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1536
2c541554 1537 h->context_initialized = 0;
0eae920c 1538
6a9c8594
AS
1539 return 0;
1540}
1541
e5d40372
DB
1542#define copy_fields(to, from, start_field, end_field) \
1543 memcpy(&to->start_field, &from->start_field, \
1544 (char *)&to->end_field - (char *)&to->start_field)
1545
9e696d2e
JG
1546static int h264_slice_header_init(H264Context *, int);
1547
1548static int h264_set_parameter_from_sps(H264Context *h);
1549
e5d40372
DB
1550static int decode_update_thread_context(AVCodecContext *dst,
1551 const AVCodecContext *src)
1552{
1553 H264Context *h = dst->priv_data, *h1 = src->priv_data;
2c541554
AK
1554 int inited = h->context_initialized, err = 0;
1555 int context_reinitialized = 0;
759001c5 1556 int i, ret;
6a9c8594 1557
2c541554 1558 if (dst == src || !h1->context_initialized)
e5d40372 1559 return 0;
6a9c8594 1560
9e696d2e 1561 if (inited &&
16c22122
DB
1562 (h->width != h1->width ||
1563 h->height != h1->height ||
1564 h->mb_width != h1->mb_width ||
1565 h->mb_height != h1->mb_height ||
9e696d2e
JG
1566 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1567 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1568 h->sps.colorspace != h1->sps.colorspace)) {
1569
a157c7f2
JG
1570 /* set bits_per_raw_sample to the previous value. the check for changed
1571 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1572 * the current value */
1573 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1574
9e696d2e
JG
1575 av_freep(&h->bipred_scratchpad);
1576
2c541554
AK
1577 h->width = h1->width;
1578 h->height = h1->height;
1579 h->mb_height = h1->mb_height;
1580 h->mb_width = h1->mb_width;
1581 h->mb_num = h1->mb_num;
1582 h->mb_stride = h1->mb_stride;
9e696d2e
JG
1583 h->b_stride = h1->b_stride;
1584
1585 if ((err = h264_slice_header_init(h, 1)) < 0) {
2c541554 1586 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
9e696d2e
JG
1587 return err;
1588 }
2c541554 1589 context_reinitialized = 1;
9e696d2e 1590
2c541554 1591 /* update linesize on resize. The decoder doesn't
25408b2a 1592 * necessarily call h264_frame_start in the new thread */
2c541554
AK
1593 h->linesize = h1->linesize;
1594 h->uvlinesize = h1->uvlinesize;
9e696d2e
JG
1595
1596 /* copy block_offset since frame_start may not be called */
1597 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
9e696d2e
JG
1598 }
1599
e5d40372
DB
1600 if (!inited) {
1601 for (i = 0; i < MAX_SPS_COUNT; i++)
6a9c8594
AS
1602 av_freep(h->sps_buffers + i);
1603
e5d40372 1604 for (i = 0; i < MAX_PPS_COUNT; i++)
6a9c8594
AS
1605 av_freep(h->pps_buffers + i);
1606
2c541554 1607 memcpy(h, h1, sizeof(*h1));
6a9c8594
AS
1608 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1609 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
2c541554
AK
1610 memset(&h->er, 0, sizeof(h->er));
1611 memset(&h->me, 0, sizeof(h->me));
e8cafd27
MS
1612 memset(&h->mb, 0, sizeof(h->mb));
1613 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1614 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
2c541554
AK
1615 h->context_initialized = 0;
1616
759001c5
AK
1617 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1618 avcodec_get_frame_defaults(&h->cur_pic.f);
1619 h->cur_pic.tf.f = &h->cur_pic.f;
2c541554 1620
16c22122
DB
1621 h->avctx = dst;
1622 h->DPB = NULL;
759001c5 1623 h->qscale_table_pool = NULL;
16c22122
DB
1624 h->mb_type_pool = NULL;
1625 h->ref_index_pool = NULL;
1626 h->motion_val_pool = NULL;
2c541554 1627
bac3ab13
DB
1628 if (ff_h264_alloc_tables(h) < 0) {
1629 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1630 return AVERROR(ENOMEM);
1631 }
6a9c8594
AS
1632 context_init(h);
1633
e5d40372
DB
1634 for (i = 0; i < 2; i++) {
1635 h->rbsp_buffer[i] = NULL;
6a9c8594
AS
1636 h->rbsp_buffer_size[i] = 0;
1637 }
a394959b 1638 h->bipred_scratchpad = NULL;
2c541554 1639 h->edge_emu_buffer = NULL;
6a9c8594
AS
1640
1641 h->thread_context[0] = h;
1642
2c541554 1643 h->context_initialized = 1;
6a9c8594
AS
1644 }
1645
2c541554
AK
1646 h->avctx->coded_height = h1->avctx->coded_height;
1647 h->avctx->coded_width = h1->avctx->coded_width;
1648 h->avctx->width = h1->avctx->width;
1649 h->avctx->height = h1->avctx->height;
1650 h->coded_picture_number = h1->coded_picture_number;
1651 h->first_field = h1->first_field;
1652 h->picture_structure = h1->picture_structure;
1653 h->qscale = h1->qscale;
1654 h->droppable = h1->droppable;
1655 h->data_partitioning = h1->data_partitioning;
1656 h->low_delay = h1->low_delay;
1657
759001c5
AK
1658 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1659 unref_picture(h, &h->DPB[i]);
1660 if (h1->DPB[i].f.data[0] &&
1661 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1662 return ret;
1663 }
2c541554 1664
16c22122 1665 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
759001c5
AK
1666 unref_picture(h, &h->cur_pic);
1667 if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1668 return ret;
2c541554
AK
1669
1670 h->workaround_bugs = h1->workaround_bugs;
1671 h->low_delay = h1->low_delay;
1672 h->droppable = h1->droppable;
1673
a394959b
JG
1674 /* frame_start may not be called for the next thread (if it's decoding
1675 * a bottom field) so this has to be allocated here */
2c541554
AK
1676 err = alloc_scratch_buffers(h, h1->linesize);
1677 if (err < 0)
1678 return err;
a394959b 1679
e5d40372
DB
1680 // extradata/NAL handling
1681 h->is_avc = h1->is_avc;
6a9c8594 1682
e5d40372
DB
1683 // SPS/PPS
1684 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1685 MAX_SPS_COUNT, sizeof(SPS));
1686 h->sps = h1->sps;
1687 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1688 MAX_PPS_COUNT, sizeof(PPS));
1689 h->pps = h1->pps;
6a9c8594 1690
e5d40372
DB
1691 // Dequantization matrices
1692 // FIXME these are big - can they be only copied when PPS changes?
6a9c8594
AS
1693 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1694
e5d40372
DB
1695 for (i = 0; i < 6; i++)
1696 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1697 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
6a9c8594 1698
e5d40372
DB
1699 for (i = 0; i < 6; i++)
1700 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1701 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
6a9c8594
AS
1702
1703 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1704
e5d40372 1705 // POC timing
6a9c8594
AS
1706 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1707
e5d40372 1708 // reference lists
6a9c8594
AS
1709 copy_fields(h, h1, short_ref, cabac_init_idc);
1710
2c541554
AK
1711 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1712 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
e5d40372 1713 copy_picture_range(h->delayed_pic, h1->delayed_pic,
2c541554 1714 MAX_DELAYED_PIC_COUNT + 2, h, h1);
6a9c8594
AS
1715
1716 h->last_slice_type = h1->last_slice_type;
1717
2c541554
AK
1718 if (context_reinitialized)
1719 h264_set_parameter_from_sps(h);
1720
1721 if (!h->cur_pic_ptr)
e5d40372 1722 return 0;
6a9c8594 1723
2c541554 1724 if (!h->droppable) {
12fe7594 1725 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
e5d40372
DB
1726 h->prev_poc_msb = h->poc_msb;
1727 h->prev_poc_lsb = h->poc_lsb;
6a9c8594 1728 }
e5d40372
DB
1729 h->prev_frame_num_offset = h->frame_num_offset;
1730 h->prev_frame_num = h->frame_num;
1731 h->outputed_poc = h->next_outputed_poc;
6a9c8594 1732
12fe7594 1733 return err;
6a9c8594
AS
1734}
1735
25408b2a 1736static int h264_frame_start(H264Context *h)
e5d40372 1737{
2c541554
AK
1738 Picture *pic;
1739 int i, ret;
6e3ef511 1740 const int pixel_shift = h->pixel_shift;
0da71265 1741
2c541554
AK
1742 release_unused_pictures(h, 1);
1743 h->cur_pic_ptr = NULL;
1744
1745 i = find_unused_picture(h);
1746 if (i < 0) {
1747 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1748 return i;
1749 }
1750 pic = &h->DPB[i];
1751
16c22122 1752 pic->reference = h->droppable ? 0 : h->picture_structure;
2c541554
AK
1753 pic->f.coded_picture_number = h->coded_picture_number++;
1754 pic->field_picture = h->picture_structure != PICT_FRAME;
3a22d7fa 1755 /*
2c541554
AK
1756 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1757 * in later.
3a22d7fa
JD
1758 * See decode_nal_units().
1759 */
2c541554
AK
1760 pic->f.key_frame = 0;
1761 pic->mmco_reset = 0;
1762
1763 if ((ret = alloc_picture(h, pic)) < 0)
1764 return ret;
1765
1766 h->cur_pic_ptr = pic;
759001c5
AK
1767 unref_picture(h, &h->cur_pic);
1768 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1769 return ret;
2c541554 1770
0b499c9b
RB
1771 if (CONFIG_ERROR_RESILIENCE)
1772 ff_er_frame_start(&h->er);
0da71265 1773
2c541554 1774 assert(h->linesize && h->uvlinesize);
0da71265 1775
e5d40372 1776 for (i = 0; i < 16; i++) {
2c541554
AK
1777 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1778 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
0da71265 1779 }
e5d40372
DB
1780 for (i = 0; i < 16; i++) {
1781 h->block_offset[16 + i] =
2c541554 1782 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
e5d40372 1783 h->block_offset[48 + 16 + i] =
2c541554 1784 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
0da71265
MN
1785 }
1786
934b0821
LM
1787 /* can't be in alloc_tables because linesize isn't known there.
1788 * FIXME: redo bipred weight to not require extra buffer? */
2c541554
AK
1789 for (i = 0; i < h->slice_context_count; i++)
1790 if (h->thread_context[i]) {
1791 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1792 if (ret < 0)
1793 return ret;
1794 }
e5d40372
DB
1795
1796 /* Some macroblocks can be accessed before they're available in case
1797 * of lost slices, MBAFF or threading. */
1798 memset(h->slice_table, -1,
2c541554 1799 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
e5d40372
DB
1800
1801 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1802 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1803
1804 /* We mark the current picture as non-reference after allocating it, so
1805 * that if we break out due to an error it can be released automatically
1806 * in the next ff_MPV_frame_start().
f08fefc4
AK
1807 */
1808 h->cur_pic_ptr->reference = 0;
357282c6 1809
2c541554 1810 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
6a9c8594
AS
1811
1812 h->next_output_pic = NULL;
1813
2c541554 1814 assert(h->cur_pic_ptr->long_ref == 0);
357282c6 1815
af8aa846 1816 return 0;
0da71265
MN
1817}
1818
6a9c8594 1819/**
e5d40372
DB
1820 * Run setup operations that must be run after slice header decoding.
1821 * This includes finding the next displayed frame.
1822 *
1823 * @param h h264 master context
1824 * @param setup_finished enough NALs have been read that we can call
1825 * ff_thread_finish_setup()
1826 */
1827static void decode_postinit(H264Context *h, int setup_finished)
1828{
2c541554
AK
1829 Picture *out = h->cur_pic_ptr;
1830 Picture *cur = h->cur_pic_ptr;
6a9c8594 1831 int i, pics, out_of_order, out_idx;
adedd840 1832 int invalid = 0, cnt = 0;
6a9c8594 1833
16c22122 1834 h->cur_pic_ptr->f.pict_type = h->pict_type;
6a9c8594 1835
e5d40372
DB
1836 if (h->next_output_pic)
1837 return;
6a9c8594 1838
e5d40372
DB
1839 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1840 /* FIXME: if we have two PAFF fields in one packet, we can't start
1841 * the next thread here. If we have one field per packet, we can.
1842 * The check in decode_nal_units() is not good enough to find this
1843 * yet, so we assume the worst for now. */
1844 // if (setup_finished)
2c541554 1845 // ff_thread_finish_setup(h->avctx);
6a9c8594
AS
1846 return;
1847 }
1848
657ccb5a
DB
1849 cur->f.interlaced_frame = 0;
1850 cur->f.repeat_pict = 0;
6a9c8594
AS
1851
1852 /* Signal interlacing information externally. */
e5d40372
DB
1853 /* Prioritize picture timing SEI information over used
1854 * decoding process if it exists. */
6a9c8594 1855
e5d40372
DB
1856 if (h->sps.pic_struct_present_flag) {
1857 switch (h->sei_pic_struct) {
6a9c8594
AS
1858 case SEI_PIC_STRUCT_FRAME:
1859 break;
1860 case SEI_PIC_STRUCT_TOP_FIELD:
1861 case SEI_PIC_STRUCT_BOTTOM_FIELD:
657ccb5a 1862 cur->f.interlaced_frame = 1;
6a9c8594
AS
1863 break;
1864 case SEI_PIC_STRUCT_TOP_BOTTOM:
1865 case SEI_PIC_STRUCT_BOTTOM_TOP:
a6931d8e 1866 if (FIELD_OR_MBAFF_PICTURE(h))
657ccb5a 1867 cur->f.interlaced_frame = 1;
6a9c8594
AS
1868 else
1869 // try to flag soft telecine progressive
657ccb5a 1870 cur->f.interlaced_frame = h->prev_interlaced_frame;
6a9c8594
AS
1871 break;
1872 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1873 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
e5d40372
DB
1874 /* Signal the possibility of telecined film externally
1875 * (pic_struct 5,6). From these hints, let the applications
1876 * decide if they apply deinterlacing. */
657ccb5a 1877 cur->f.repeat_pict = 1;
6a9c8594
AS
1878 break;
1879 case SEI_PIC_STRUCT_FRAME_DOUBLING:
657ccb5a 1880 cur->f.repeat_pict = 2;
6a9c8594
AS
1881 break;
1882 case SEI_PIC_STRUCT_FRAME_TRIPLING:
657ccb5a 1883 cur->f.repeat_pict = 4;
6a9c8594
AS
1884 break;
1885 }
1886
e5d40372
DB
1887 if ((h->sei_ct_type & 3) &&
1888 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
657ccb5a 1889 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
e5d40372 1890 } else {
6a9c8594 1891 /* Derive interlacing flag from used decoding process. */
a6931d8e 1892 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
6a9c8594 1893 }
657ccb5a 1894 h->prev_interlaced_frame = cur->f.interlaced_frame;
6a9c8594 1895
e5d40372 1896 if (cur->field_poc[0] != cur->field_poc[1]) {
6a9c8594 1897 /* Derive top_field_first from field pocs. */
657ccb5a 1898 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
e5d40372 1899 } else {
657ccb5a 1900 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
e5d40372
DB
1901 /* Use picture timing SEI information. Even if it is a
1902 * information of a past frame, better than nothing. */
1903 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1904 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
657ccb5a 1905 cur->f.top_field_first = 1;
6a9c8594 1906 else
657ccb5a 1907 cur->f.top_field_first = 0;
e5d40372 1908 } else {
6a9c8594 1909 /* Most likely progressive */
657ccb5a 1910 cur->f.top_field_first = 0;
6a9c8594
AS
1911 }
1912 }
1913
e5d40372 1914 // FIXME do something with unavailable reference frames
6a9c8594
AS
1915
1916 /* Sort B-frames into display order */
1917
e5d40372 1918 if (h->sps.bitstream_restriction_flag &&
2c541554
AK
1919 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1920 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1921 h->low_delay = 0;
6a9c8594
AS
1922 }
1923
2c541554 1924 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
e5d40372 1925 !h->sps.bitstream_restriction_flag) {
2c541554
AK
1926 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1927 h->low_delay = 0;
6a9c8594
AS
1928 }
1929
1930 pics = 0;
e5d40372
DB
1931 while (h->delayed_pic[pics])
1932 pics++;
6a9c8594
AS
1933
1934 assert(pics <= MAX_DELAYED_PIC_COUNT);
1935
1936 h->delayed_pic[pics++] = cur;
759001c5
AK
1937 if (cur->reference == 0)
1938 cur->reference = DELAYED_PIC_REF;
6a9c8594 1939
adedd840
RB
1940 /* Frame reordering. This code takes pictures from coding order and sorts
1941 * them by their incremental POC value into display order. It supports POC
1942 * gaps, MMCO reset codes and random resets.
1943 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1944 * and/or can be closed down with a MMCO reset code. In sequences where
1945 * there is no delay, we can't detect that (since the frame was already
1946 * output to the user), so we also set h->mmco_reset to detect the MMCO
1947 * reset code.
2c541554 1948 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
adedd840
RB
1949 * we increase the delay between input and output. All frames affected by
1950 * the lag (e.g. those that should have been output before another frame
1951 * that we already returned to the user) will be dropped. This is a bug
1952 * that we will fix later. */
1953 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1954 cnt += out->poc < h->last_pocs[i];
1955 invalid += out->poc == INT_MIN;
1956 }
e5d40372
DB
1957 if (!h->mmco_reset && !cur->f.key_frame &&
1958 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
adedd840
RB
1959 h->mmco_reset = 2;
1960 if (pics > 1)
1961 h->delayed_pic[pics - 2]->mmco_reset = 2;
1962 }
1963 if (h->mmco_reset || cur->f.key_frame) {
1964 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1965 h->last_pocs[i] = INT_MIN;
1966 cnt = 0;
1967 invalid = MAX_DELAYED_PIC_COUNT;
1968 }
e5d40372 1969 out = h->delayed_pic[0];
6a9c8594 1970 out_idx = 0;
e5d40372
DB
1971 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1972 h->delayed_pic[i] &&
1973 !h->delayed_pic[i - 1]->mmco_reset &&
1974 !h->delayed_pic[i]->f.key_frame;
1975 i++)
1976 if (h->delayed_pic[i]->poc < out->poc) {
1977 out = h->delayed_pic[i];
6a9c8594
AS
1978 out_idx = i;
1979 }
2c541554 1980 if (h->avctx->has_b_frames == 0 &&
e5d40372 1981 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
adedd840 1982 h->next_outputed_poc = INT_MIN;
e5d40372
DB
1983 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1984 (out->poc < h->next_outputed_poc);
6a9c8594 1985
e5d40372 1986 if (h->sps.bitstream_restriction_flag &&
2c541554
AK
1987 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1988 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1989 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
ea2bb12e 1990 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
2c541554 1991 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
ea2bb12e 1992 }
2c541554
AK
1993 h->low_delay = 0;
1994 } else if (h->low_delay &&
e5d40372
DB
1995 ((h->next_outputed_poc != INT_MIN &&
1996 out->poc > h->next_outputed_poc + 2) ||
ea2bb12e 1997 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
2c541554
AK
1998 h->low_delay = 0;
1999 h->avctx->has_b_frames++;
6a9c8594
AS
2000 }
2001
2c541554 2002 if (pics > h->avctx->has_b_frames) {
759001c5 2003 out->reference &= ~DELAYED_PIC_REF;
e5d40372
DB
2004 // for frame threading, the owner must be the second field's thread or
2005 // else the first thread can release the picture and reuse it unsafely
e5d40372
DB
2006 for (i = out_idx; h->delayed_pic[i]; i++)
2007 h->delayed_pic[i] = h->delayed_pic[i + 1];
2008 }
2009 memmove(h->last_pocs, &h->last_pocs[1],
2010 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
adedd840 2011 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
2c541554 2012 if (!out_of_order && pics > h->avctx->has_b_frames) {
6a9c8594 2013 h->next_output_pic = out;
adedd840
RB
2014 if (out->mmco_reset) {
2015 if (out_idx > 0) {
e5d40372 2016 h->next_outputed_poc = out->poc;
adedd840
RB
2017 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
2018 } else {
2019 h->next_outputed_poc = INT_MIN;
2020 }
2021 } else {
0b4c3232
RB
2022 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
2023 h->next_outputed_poc = INT_MIN;
2024 } else {
2025 h->next_outputed_poc = out->poc;
2026 }
adedd840
RB
2027 }
2028 h->mmco_reset = 0;
e5d40372 2029 } else {
2c541554 2030 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
6a9c8594
AS
2031 }
2032
05fa79b8 2033 if (setup_finished && !h->avctx->hwaccel)
2c541554 2034 ff_thread_finish_setup(h->avctx);
6a9c8594
AS
2035}
2036
76741b0e
BC
2037static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2038 uint8_t *src_cb, uint8_t *src_cr,
e5d40372
DB
2039 int linesize, int uvlinesize,
2040 int simple)
76741b0e 2041{
0b69d625 2042 uint8_t *top_border;
5f7f9719 2043 int top_idx = 1;
6e3ef511 2044 const int pixel_shift = h->pixel_shift;
23e85be5 2045 int chroma444 = CHROMA444(h);
e962bd08 2046 int chroma422 = CHROMA422(h);
115329f1 2047
e5d40372 2048 src_y -= linesize;
53c05b1e
MN
2049 src_cb -= uvlinesize;
2050 src_cr -= uvlinesize;
2051
7bece9b2 2052 if (!simple && FRAME_MBAFF(h)) {
2c541554 2053 if (h->mb_y & 1) {
82313eaa 2054 if (!MB_MBAFF(h)) {
2c541554 2055 top_border = h->top_borders[0][h->mb_x];
e5d40372 2056 AV_COPY128(top_border, src_y + 15 * linesize);
6e3ef511 2057 if (pixel_shift)
e5d40372 2058 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2c541554 2059 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
e5d40372
DB
2060 if (chroma444) {
2061 if (pixel_shift) {
2062 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2063 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2064 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2065 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
c90b9442 2066 } else {
e5d40372
DB
2067 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2068 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
c90b9442 2069 }
e5d40372 2070 } else if (chroma422) {
76741b0e 2071 if (pixel_shift) {
e5d40372
DB
2072 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2073 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
76741b0e 2074 } else {
e5d40372
DB
2075 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2076 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
76741b0e 2077 }
6e3ef511 2078 } else {
c90b9442 2079 if (pixel_shift) {
e5d40372
DB
2080 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2081 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
c90b9442 2082 } else {
e5d40372
DB
2083 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2084 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
c90b9442 2085 }
6e3ef511 2086 }
5f7f9719
MN
2087 }
2088 }
82313eaa 2089 } else if (MB_MBAFF(h)) {
c988f975 2090 top_idx = 0;
e5d40372 2091 } else
c988f975 2092 return;
5f7f9719
MN
2093 }
2094
2c541554 2095 top_border = h->top_borders[top_idx][h->mb_x];
09f21198 2096 /* There are two lines saved, the line above the top macroblock
e5d40372
DB
2097 * of a pair, and the line above the bottom macroblock. */
2098 AV_COPY128(top_border, src_y + 16 * linesize);
6e3ef511 2099 if (pixel_shift)
e5d40372
DB
2100 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2101
2c541554 2102 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
e5d40372
DB
2103 if (chroma444) {
2104 if (pixel_shift) {
2105 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2106 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2107 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2108 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
c90b9442 2109 } else {
e5d40372
DB
2110 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2111 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
c90b9442 2112 }
e5d40372 2113 } else if (chroma422) {
76741b0e 2114 if (pixel_shift) {
e5d40372
DB
2115 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2116 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
76741b0e 2117 } else {
e5d40372
DB
2118 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2119 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
76741b0e 2120 }
6e3ef511 2121 } else {
c90b9442 2122 if (pixel_shift) {
e5d40372
DB
2123 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2124 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
c90b9442 2125 } else {
e5d40372
DB
2126 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2127 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
c90b9442 2128 }
6e3ef511 2129 }
53c05b1e
MN
2130 }
2131}
2132
bbdd52ed 2133static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
e5d40372
DB
2134 uint8_t *src_cb, uint8_t *src_cr,
2135 int linesize, int uvlinesize,
2136 int xchg, int chroma444,
2137 int simple, int pixel_shift)
2138{
4e987f82 2139 int deblock_topleft;
b69378e2 2140 int deblock_top;
5f7f9719 2141 int top_idx = 1;
1e4f1c56
AS
2142 uint8_t *top_border_m1;
2143 uint8_t *top_border;
5f7f9719 2144
7bece9b2 2145 if (!simple && FRAME_MBAFF(h)) {
2c541554 2146 if (h->mb_y & 1) {
82313eaa 2147 if (!MB_MBAFF(h))
c988f975 2148 return;
e5d40372 2149 } else {
82313eaa 2150 top_idx = MB_MBAFF(h) ? 0 : 1;
5f7f9719 2151 }
5f7f9719 2152 }
b69378e2 2153
e5d40372 2154 if (h->deblocking_filter == 2) {
2c541554 2155 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
4e987f82 2156 deblock_top = h->top_type;
b69378e2 2157 } else {
2c541554 2158 deblock_topleft = (h->mb_x > 0);
da6be8fc 2159 deblock_top = (h->mb_y > !!MB_FIELD(h));
b69378e2 2160 }
53c05b1e 2161
e5d40372 2162 src_y -= linesize + 1 + pixel_shift;
6e3ef511
OA
2163 src_cb -= uvlinesize + 1 + pixel_shift;
2164 src_cr -= uvlinesize + 1 + pixel_shift;
53c05b1e 2165
2c541554
AK
2166 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2167 top_border = h->top_borders[top_idx][h->mb_x];
1e4f1c56 2168
e5d40372
DB
2169#define XCHG(a, b, xchg) \
2170 if (pixel_shift) { \
2171 if (xchg) { \
2172 AV_SWAP64(b + 0, a + 0); \
2173 AV_SWAP64(b + 8, a + 8); \
2174 } else { \
2175 AV_COPY128(b, a); \
2176 } \
2177 } else if (xchg) \
2178 AV_SWAP64(b, a); \
2179 else \
2180 AV_COPY64(b, a);
2181
2182 if (deblock_top) {
2183 if (deblock_topleft) {
2184 XCHG(top_border_m1 + (8 << pixel_shift),
2185 src_y - (7 << pixel_shift), 1);
c988f975 2186 }
6e3ef511
OA
2187 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2188 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2c541554
AK
2189 if (h->mb_x + 1 < h->mb_width) {
2190 XCHG(h->top_borders[top_idx][h->mb_x + 1],
e5d40372 2191 src_y + (17 << pixel_shift), 1);
43efd19a 2192 }
53c05b1e 2193 }
2c541554 2194 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
e5d40372
DB
2195 if (chroma444) {
2196 if (deblock_topleft) {
c90b9442
JGG
2197 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2198 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2199 }
2200 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2201 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2202 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2203 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2c541554
AK
2204 if (h->mb_x + 1 < h->mb_width) {
2205 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2206 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
c90b9442
JGG
2207 }
2208 } else {
e5d40372
DB
2209 if (deblock_top) {
2210 if (deblock_topleft) {
c90b9442
JGG
2211 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2212 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2213 }
e5d40372
DB
2214 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2215 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
c988f975 2216 }
53c05b1e 2217 }
53c05b1e
MN
2218 }
2219}
2220
88bd7fdc 2221static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
e5d40372
DB
2222 int index)
2223{
6e3ef511 2224 if (high_bit_depth) {
e5d40372 2225 return AV_RN32A(((int32_t *)mb) + index);
6e3ef511
OA
2226 } else
2227 return AV_RN16A(mb + index);
2228}
2229
88bd7fdc 2230static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
e5d40372
DB
2231 int index, int value)
2232{
6e3ef511 2233 if (high_bit_depth) {
e5d40372 2234 AV_WN32A(((int32_t *)mb) + index, value);
6e3ef511
OA
2235 } else
2236 AV_WN16A(mb + index, value);
2237}
2238
e5d40372
DB
2239static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2240 int mb_type, int is_h264,
2241 int simple,
2242 int transform_bypass,
2243 int pixel_shift,
2244 int *block_offset,
2245 int linesize,
2246 uint8_t *dest_y, int p)
c90b9442 2247{
88bd7fdc
DB
2248 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2249 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
c90b9442 2250 int i;
2c541554 2251 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
e5d40372
DB
2252 block_offset += 16 * p;
2253 if (IS_INTRA4x4(mb_type)) {
2491f9ee
AK
2254 if (IS_8x8DCT(mb_type)) {
2255 if (transform_bypass) {
16c22122
DB
2256 idct_dc_add =
2257 idct_add = h->h264dsp.h264_add_pixels8_clear;
2491f9ee
AK
2258 } else {
2259 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2260 idct_add = h->h264dsp.h264_idct8_add;
2261 }
2262 for (i = 0; i < 16; i += 4) {
2263 uint8_t *const ptr = dest_y + block_offset[i];
2264 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2265 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2266 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
e5d40372 2267 } else {
2491f9ee
AK
2268 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2269 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2270 (h->topright_samples_available << i) & 0x4000, linesize);
2271 if (nnz) {
2272 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2273 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2274 else
2275 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
c90b9442
JGG
2276 }
2277 }
2491f9ee
AK
2278 }
2279 } else {
2280 if (transform_bypass) {
2281 idct_dc_add =
62844c3f 2282 idct_add = h->h264dsp.h264_add_pixels4_clear;
e5d40372 2283 } else {
2491f9ee
AK
2284 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2285 idct_add = h->h264dsp.h264_idct_add;
2286 }
2287 for (i = 0; i < 16; i++) {
2288 uint8_t *const ptr = dest_y + block_offset[i];
2289 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
c90b9442 2290
2491f9ee
AK
2291 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2292 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2293 } else {
2294 uint8_t *topright;
2295 int nnz, tr;
2296 uint64_t tr_high;
2297 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2298 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2c541554 2299 assert(h->mb_y || linesize <= block_offset[i]);
2491f9ee
AK
2300 if (!topright_avail) {
2301 if (pixel_shift) {
2302 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2303 topright = (uint8_t *)&tr_high;
2304 } else {
2305 tr = ptr[3 - linesize] * 0x01010101u;
2306 topright = (uint8_t *)&tr;
2307 }
e5d40372 2308 } else
2491f9ee
AK
2309 topright = ptr + (4 << pixel_shift) - linesize;
2310 } else
2311 topright = NULL;
2312
2313 h->hpc.pred4x4[dir](ptr, topright, linesize);
2314 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2315 if (nnz) {
2316 if (is_h264) {
2317 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2318 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2319 else
2320 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2321 } else if (CONFIG_SVQ3_DECODER)
2322 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
c90b9442
JGG
2323 }
2324 }
2325 }
2326 }
e5d40372
DB
2327 } else {
2328 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2329 if (is_h264) {
2330 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2331 if (!transform_bypass)
2332 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2333 h->mb_luma_dc[p],
2334 h->dequant4_coeff[p][qscale][0]);
2335 else {
2336 static const uint8_t dc_mapping[16] = {
2337 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2338 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2339 8 * 16, 9 * 16, 12 * 16, 13 * 16,
16c22122
DB
2340 10 * 16, 11 * 16, 14 * 16, 15 * 16
2341 };
e5d40372
DB
2342 for (i = 0; i < 16; i++)
2343 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2344 pixel_shift, dc_mapping[i],
2345 dctcoef_get(h->mb_luma_dc[p],
2346 pixel_shift, i));
c90b9442
JGG
2347 }
2348 }
301fb921 2349 } else if (CONFIG_SVQ3_DECODER)
e5d40372
DB
2350 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2351 h->mb_luma_dc[p], qscale);
c90b9442
JGG
2352 }
2353}
2354
e5d40372
DB
2355static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2356 int is_h264, int simple,
2357 int transform_bypass,
2358 int pixel_shift,
2359 int *block_offset,
2360 int linesize,
2361 uint8_t *dest_y, int p)
c90b9442 2362{
88bd7fdc 2363 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
c90b9442 2364 int i;
e5d40372
DB
2365 block_offset += 16 * p;
2366 if (!IS_INTRA4x4(mb_type)) {
2367 if (is_h264) {
2368 if (IS_INTRA16x16(mb_type)) {
2369 if (transform_bypass) {
2370 if (h->sps.profile_idc == 244 &&
2371 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2372 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2373 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2374 h->mb + (p * 256 << pixel_shift),
2375 linesize);
2376 } else {
2377 for (i = 0; i < 16; i++)
2378 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2379 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
62844c3f
RB
2380 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2381 h->mb + (i * 16 + p * 256 << pixel_shift),
2382 linesize);
c90b9442 2383 }
e5d40372
DB
2384 } else {
2385 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2386 h->mb + (p * 256 << pixel_shift),
2387 linesize,
2388 h->non_zero_count_cache + p * 5 * 8);
c90b9442 2389 }
e5d40372
DB
2390 } else if (h->cbp & 15) {
2391 if (transform_bypass) {
c90b9442 2392 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
62844c3f
RB
2393 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2394 : h->h264dsp.h264_add_pixels4_clear;
e5d40372
DB
2395 for (i = 0; i < 16; i += di)
2396 if (h->non_zero_count_cache[scan8[i + p * 16]])
2397 idct_add(dest_y + block_offset[i],
2398 h->mb + (i * 16 + p * 256 << pixel_shift),
2399 linesize);
2400 } else {
2401 if (IS_8x8DCT(mb_type))
2402 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2403 h->mb + (p * 256 << pixel_shift),
2404 linesize,
2405 h->non_zero_count_cache + p * 5 * 8);
2406 else
2407 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2408 h->mb + (p * 256 << pixel_shift),
2409 linesize,
2410 h->non_zero_count_cache + p * 5 * 8);
c90b9442
JGG
2411 }
2412 }
301fb921 2413 } else if (CONFIG_SVQ3_DECODER) {
e5d40372
DB
2414 for (i = 0; i < 16; i++)
2415 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2416 // FIXME benchmark weird rule, & below
2417 uint8_t *const ptr = dest_y + block_offset[i];
2418 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2c541554 2419 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
c90b9442 2420 }
c90b9442
JGG
2421 }
2422 }
2423}
2424
28fff0d9
MR
2425#define BITS 8
2426#define SIMPLE 1
2427#include "h264_mb_template.c"
e5d40372 2428
28fff0d9
MR
2429#undef BITS
2430#define BITS 16
2431#include "h264_mb_template.c"
bd91fee3 2432
28fff0d9
MR
2433#undef SIMPLE
2434#define SIMPLE 0
2435#include "h264_mb_template.c"
c90b9442 2436
e5d40372
DB
2437void ff_h264_hl_decode_mb(H264Context *h)
2438{
e5d40372 2439 const int mb_xy = h->mb_xy;
759001c5 2440 const int mb_type = h->cur_pic.mb_type[mb_xy];
16c22122
DB
2441 int is_complex = CONFIG_SMALL || h->is_complex ||
2442 IS_INTRA_PCM(mb_type) || h->qscale == 0;
bd91fee3 2443
23e85be5 2444 if (CHROMA444(h)) {
e5d40372 2445 if (is_complex || h->pixel_shift)
c90b9442
JGG
2446 hl_decode_mb_444_complex(h);
2447 else
28fff0d9 2448 hl_decode_mb_444_simple_8(h);
c90b9442 2449 } else if (is_complex) {
bd91fee3 2450 hl_decode_mb_complex(h);
6e3ef511
OA
2451 } else if (h->pixel_shift) {
2452 hl_decode_mb_simple_16(h);
2453 } else
2454 hl_decode_mb_simple_8(h);
bd91fee3
AS
2455}
2456
e5d40372
DB
2457static int pred_weight_table(H264Context *h)
2458{
0da71265 2459 int list, i;
9f2d1b4f 2460 int luma_def, chroma_def;
115329f1 2461
e5d40372
DB
2462 h->use_weight = 0;
2463 h->use_weight_chroma = 0;
2c541554 2464 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
e5d40372 2465 if (h->sps.chroma_format_idc)
2c541554 2466 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
e5d40372
DB
2467 luma_def = 1 << h->luma_log2_weight_denom;
2468 chroma_def = 1 << h->chroma_log2_weight_denom;
0da71265 2469
e5d40372 2470 for (list = 0; list < 2; list++) {
cb99c652
GB
2471 h->luma_weight_flag[list] = 0;
2472 h->chroma_weight_flag[list] = 0;
e5d40372 2473 for (i = 0; i < h->ref_count[list]; i++) {
0da71265 2474 int luma_weight_flag, chroma_weight_flag;
115329f1 2475
2c541554 2476 luma_weight_flag = get_bits1(&h->gb);
e5d40372 2477 if (luma_weight_flag) {
2c541554
AK
2478 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2479 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
e5d40372
DB
2480 if (h->luma_weight[i][list][0] != luma_def ||
2481 h->luma_weight[i][list][1] != 0) {
2482 h->use_weight = 1;
2483 h->luma_weight_flag[list] = 1;
cb99c652 2484 }
e5d40372
DB
2485 } else {
2486 h->luma_weight[i][list][0] = luma_def;
2487 h->luma_weight[i][list][1] = 0;
0da71265
MN
2488 }
2489
e5d40372 2490 if (h->sps.chroma_format_idc) {
2c541554 2491 chroma_weight_flag = get_bits1(&h->gb);
e5d40372 2492 if (chroma_weight_flag) {
fef744d4 2493 int j;
e5d40372 2494 for (j = 0; j < 2; j++) {
2c541554
AK
2495 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2496 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
e5d40372
DB
2497 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2498 h->chroma_weight[i][list][j][1] != 0) {
16c22122 2499 h->use_weight_chroma = 1;
e5d40372 2500 h->chroma_weight_flag[list] = 1;
cb99c652 2501 }
fef744d4 2502 }
e5d40372 2503 } else {
fef744d4 2504 int j;
e5d40372
DB
2505 for (j = 0; j < 2; j++) {
2506 h->chroma_weight[i][list][j][0] = chroma_def;
2507 h->chroma_weight[i][list][j][1] = 0;
fef744d4 2508 }
0da71265
MN
2509 }
2510 }
2511 }
e5d40372
DB
2512 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2513 break;
0da71265 2514 }
e5d40372 2515 h->use_weight = h->use_weight || h->use_weight_chroma;
0da71265
MN
2516 return 0;
2517}
2518
1052b76f
MN
2519/**
2520 * Initialize implicit_weight table.
6da88bd3 2521 * @param field 0/1 initialize the weight for interlaced MBAFF
1052b76f
MN
2522 * -1 initializes the rest
2523 */
e5d40372
DB
2524static void implicit_weight_table(H264Context *h, int field)
2525{
1052b76f 2526 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
9f2d1b4f 2527
ce09f927
GB
2528 for (i = 0; i < 2; i++) {
2529 h->luma_weight_flag[i] = 0;
2530 h->chroma_weight_flag[i] = 0;
2531 }
2532
e5d40372 2533 if (field < 0) {
2c541554
AK
2534 if (h->picture_structure == PICT_FRAME) {
2535 cur_poc = h->cur_pic_ptr->poc;
4418aa9c 2536 } else {
2c541554 2537 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
4418aa9c 2538 }
7bece9b2 2539 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
e5d40372 2540 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
16c22122 2541 h->use_weight = 0;
e5d40372
DB
2542 h->use_weight_chroma = 0;
2543 return;
2544 }
2545 ref_start = 0;
2546 ref_count0 = h->ref_count[0];
2547 ref_count1 = h->ref_count[1];
2548 } else {
2c541554 2549 cur_poc = h->cur_pic_ptr->field_poc[field];
e5d40372
DB
2550 ref_start = 16;
2551 ref_count0 = 16 + 2 * h->ref_count[0];
2552 ref_count1 = 16 + 2 * h->ref_count[1];
1052b76f 2553 }
9f2d1b4f 2554
e5d40372
DB
2555 h->use_weight = 2;
2556 h->use_weight_chroma = 2;
2557 h->luma_log2_weight_denom = 5;
2558 h->chroma_log2_weight_denom = 5;
9f2d1b4f 2559
e5d40372 2560 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
9f2d1b4f 2561 int poc0 = h->ref_list[0][ref0].poc;
e5d40372 2562 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
87cf70eb
JD
2563 int w = 32;
2564 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2565 int poc1 = h->ref_list[1][ref1].poc;
e5d40372
DB
2566 int td = av_clip(poc1 - poc0, -128, 127);
2567 if (td) {
87cf70eb
JD
2568 int tb = av_clip(cur_poc - poc0, -128, 127);
2569 int tx = (16384 + (FFABS(td) >> 1)) / td;
e5d40372
DB
2570 int dist_scale_factor = (tb * tx + 32) >> 8;
2571 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
87cf70eb
JD
2572 w = 64 - dist_scale_factor;
2573 }
1052b76f 2574 }
e5d40372
DB
2575 if (field < 0) {
2576 h->implicit_weight[ref0][ref1][0] =
2577 h->implicit_weight[ref0][ref1][1] = w;
2578 } else {
2579 h->implicit_weight[ref0][ref1][field] = w;
72f86ec0 2580 }
9f2d1b4f
LM
2581 }
2582 }
2583}
2584
8fd57a66 2585/**
5175b937 2586 * instantaneous decoder refresh.
0da71265 2587 */
e5d40372
DB
2588static void idr(H264Context *h)
2589{
ea6f00c4 2590 ff_h264_remove_all_refs(h);
e5d40372
DB
2591 h->prev_frame_num = 0;
2592 h->prev_frame_num_offset = 0;
2593 h->prev_poc_msb =
2594 h->prev_poc_lsb = 0;
0da71265
MN
2595}
2596
7c33ad19 2597/* forget old pics after a seek */
9e696d2e 2598static void flush_change(H264Context *h)
e5d40372 2599{
7c33ad19 2600 int i;
adedd840
RB
2601 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2602 h->last_pocs[i] = INT_MIN;
16c22122 2603 h->outputed_poc = h->next_outputed_poc = INT_MIN;
b19d493f 2604 h->prev_interlaced_frame = 1;
7c33ad19 2605 idr(h);
2c541554 2606 if (h->cur_pic_ptr)
759001c5 2607 h->cur_pic_ptr->reference = 0;
2c541554 2608 h->first_field = 0;
9e696d2e
JG
2609 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2610 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2611 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2612 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
9c095463 2613 ff_h264_reset_sei(h);
9e696d2e
JG
2614}
2615
2616/* forget old pics after a seek */
2617static void flush_dpb(AVCodecContext *avctx)
2618{
2619 H264Context *h = avctx->priv_data;
2620 int i;
2621
2622 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2623 if (h->delayed_pic[i])
759001c5 2624 h->delayed_pic[i]->reference = 0;
9e696d2e
JG
2625 h->delayed_pic[i] = NULL;
2626 }
2627
2628 flush_change(h);
2c541554 2629
555000c7
AK
2630 if (h->DPB)
2631 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2632 unref_picture(h, &h->DPB[i]);
2c541554 2633 h->cur_pic_ptr = NULL;
759001c5 2634 unref_picture(h, &h->cur_pic);
2c541554
AK
2635
2636 h->mb_x = h->mb_y = 0;
2637
2638 h->parse_context.state = -1;
2639 h->parse_context.frame_start_found = 0;
2640 h->parse_context.overread = 0;
2641 h->parse_context.overread_index = 0;
2642 h->parse_context.index = 0;
2643 h->parse_context.last_index = 0;
7c33ad19
LM
2644}
2645
3f1a7ceb 2646int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
e5d40372 2647{
e5d40372 2648 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
0da71265
MN
2649 int field_poc[2];
2650
e5d40372
DB
2651 h->frame_num_offset = h->prev_frame_num_offset;
2652 if (h->frame_num < h->prev_frame_num)
b78a6baa 2653 h->frame_num_offset += max_frame_num;
0da71265 2654
e5d40372
DB
2655 if (h->sps.poc_type == 0) {
2656 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
0da71265 2657
16c22122
DB
2658 if (h->poc_lsb < h->prev_poc_lsb &&
2659 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
0da71265 2660 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
16c22122
DB
2661 else if (h->poc_lsb > h->prev_poc_lsb &&
2662 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
0da71265
MN
2663 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2664 else
2665 h->poc_msb = h->prev_poc_msb;
115329f1 2666 field_poc[0] =
0da71265 2667 field_poc[1] = h->poc_msb + h->poc_lsb;
2c541554 2668 if (h->picture_structure == PICT_FRAME)
0da71265 2669 field_poc[1] += h->delta_poc_bottom;
e5d40372 2670 } else if (h->sps.poc_type == 1) {
0da71265
MN
2671 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2672 int i;
2673
e5d40372 2674 if (h->sps.poc_cycle_length != 0)
0da71265
MN
2675 abs_frame_num = h->frame_num_offset + h->frame_num;
2676 else
2677 abs_frame_num = 0;
2678
e5d40372 2679 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
0da71265 2680 abs_frame_num--;
115329f1 2681
0da71265 2682 expected_delta_per_poc_cycle = 0;
e5d40372
DB
2683 for (i = 0; i < h->sps.poc_cycle_length; i++)
2684 // FIXME integrate during sps parse
2685 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
0da71265 2686
e5d40372 2687 if (abs_frame_num > 0) {
0da71265
MN
2688 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2689 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2690
2691 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
e5d40372
DB
2692 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2693 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
0da71265
MN
2694 } else
2695 expectedpoc = 0;
2696
e5d40372 2697 if (h->nal_ref_idc == 0)
0da71265 2698 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
115329f1 2699
0da71265
MN
2700 field_poc[0] = expectedpoc + h->delta_poc[0];
2701 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2702
2c541554 2703 if (h->picture_structure == PICT_FRAME)
0da71265 2704 field_poc[1] += h->delta_poc[1];
e5d40372
DB
2705 } else {
2706 int poc = 2 * (h->frame_num_offset + h->frame_num);
5710b371 2707
e5d40372 2708 if (!h->nal_ref_idc)
b78a6baa 2709 poc--;
5710b371 2710
e5d40372
DB
2711 field_poc[0] = poc;
2712 field_poc[1] = poc;
0da71265 2713 }
115329f1 2714
2c541554 2715 if (h->picture_structure != PICT_BOTTOM_FIELD)
3f1a7ceb 2716 pic_field_poc[0] = field_poc[0];
2c541554 2717 if (h->picture_structure != PICT_TOP_FIELD)
3f1a7ceb 2718 pic_field_poc[1] = field_poc[1];
a8b19271 2719 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
0da71265
MN
2720
2721 return 0;
2722}
2723
b41c1db3
2724/**
2725 * initialize scan tables
2726 */
e5d40372
DB
2727static void init_scan_tables(H264Context *h)
2728{
b41c1db3 2729 int i;
e5d40372
DB
2730 for (i = 0; i < 16; i++) {
2731#define T(x) (x >> 2) | ((x << 2) & 0xF)
ca32f7f2 2732 h->zigzag_scan[i] = T(zigzag_scan[i]);
e5d40372 2733 h->field_scan[i] = T(field_scan[i]);
b41c1db3 2734#undef T
b41c1db3 2735 }
e5d40372
DB
2736 for (i = 0; i < 64; i++) {
2737#define T(x) (x >> 3) | ((x & 7) << 3)
ca32f7f2
JGG
2738 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2739 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2740 h->field_scan8x8[i] = T(field_scan8x8[i]);
2741 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
b41c1db3 2742#undef T
b41c1db3 2743 }
e5d40372 2744 if (h->sps.transform_bypass) { // FIXME same ugly
b41c1db3 2745 h->zigzag_scan_q0 = zigzag_scan;
45beb850 2746 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
b41c1db3
2747 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2748 h->field_scan_q0 = field_scan;
2749 h->field_scan8x8_q0 = field_scan8x8;
2750 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
e5d40372 2751 } else {
b41c1db3
2752 h->zigzag_scan_q0 = h->zigzag_scan;
2753 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2754 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2755 h->field_scan_q0 = h->field_scan;
2756 h->field_scan8x8_q0 = h->field_scan8x8;
2757 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2758 }
2759}
afebe2f7 2760
e5d40372
DB
2761static int field_end(H264Context *h, int in_setup)
2762{
2c541554 2763 AVCodecContext *const avctx = h->avctx;
12fe7594 2764 int err = 0;
2c541554 2765 h->mb_y = 0;
256299d3 2766
2c541554 2767 if (!in_setup && !h->droppable)
759001c5 2768 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2c541554 2769 h->picture_structure == PICT_BOTTOM_FIELD);
256299d3 2770
e5d40372 2771 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2c541554 2772 if (!h->droppable) {
12fe7594 2773 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
e5d40372
DB
2774 h->prev_poc_msb = h->poc_msb;
2775 h->prev_poc_lsb = h->poc_lsb;
6a9c8594 2776 }
e5d40372
DB
2777 h->prev_frame_num_offset = h->frame_num_offset;
2778 h->prev_frame_num = h->frame_num;
2779 h->outputed_poc = h->next_outputed_poc;
256299d3 2780 }
256299d3
MN
2781
2782 if (avctx->hwaccel) {
2783 if (avctx->hwaccel->end_frame(avctx) < 0)
e5d40372
DB
2784 av_log(avctx, AV_LOG_ERROR,
2785 "hardware accelerator failed to decode picture\n");
256299d3
MN
2786 }
2787
256299d3
MN
2788 /*
2789 * FIXME: Error handling code does not seem to support interlaced
2790 * when slices span multiple rows
2791 * The ff_er_add_slice calls don't work right for bottom
2792 * fields; they cause massive erroneous error concealing
2793 * Error marking covers both fields (top and bottom).
2794 * This causes a mismatched s->error_count
2795 * and a bad error table. Further, the error count goes to
2796 * INT_MAX when called for bottom field, because mb_y is
2797 * past end by one (callers fault) and resync_mb_y != 0
2798 * causes problems for the first MB line, too.
2799 */
0b499c9b 2800 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h)) {
2c541554
AK
2801 h->er.cur_pic = h->cur_pic_ptr;
2802 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2803 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2804 ff_er_frame_end(&h->er);
2805 }
2c541554 2806 emms_c();
d225a1e2 2807
e5d40372 2808 h->current_slice = 0;
12fe7594
DB
2809
2810 return err;
256299d3
MN
2811}
2812
afebe2f7 2813/**
49bd8e4b 2814 * Replicate H264 "master" context to thread contexts.
afebe2f7 2815 */
f1d8763a 2816static int clone_slice(H264Context *dst, H264Context *src)
afebe2f7 2817{
e5d40372 2818 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2c541554
AK
2819 dst->cur_pic_ptr = src->cur_pic_ptr;
2820 dst->cur_pic = src->cur_pic;
2821 dst->linesize = src->linesize;
2822 dst->uvlinesize = src->uvlinesize;
2823 dst->first_field = src->first_field;
f1d8763a 2824
e5d40372
DB
2825 dst->prev_poc_msb = src->prev_poc_msb;
2826 dst->prev_poc_lsb = src->prev_poc_lsb;
2827 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2828 dst->prev_frame_num = src->prev_frame_num;
2829 dst->short_ref_count = src->short_ref_count;
afebe2f7
2830
2831 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2832 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2833 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
50c21814
2834
2835 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2836 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
f1d8763a
JG
2837
2838 return 0;
afebe2f7
2839}
2840
0da71265 2841/**
58c42af7 2842 * Compute profile from profile_idc and constraint_set?_flags.
fe9a3fbe
JG
2843 *
2844 * @param sps SPS
2845 *
2846 * @return profile as defined by FF_PROFILE_H264_*
2847 */
2848int ff_h264_get_profile(SPS *sps)
2849{
2850 int profile = sps->profile_idc;
2851
e5d40372 2852 switch (sps->profile_idc) {
fe9a3fbe
JG
2853 case FF_PROFILE_H264_BASELINE:
2854 // constraint_set1_flag set to 1
e5d40372 2855 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
fe9a3fbe
JG
2856 break;
2857 case FF_PROFILE_H264_HIGH_10:
2858 case FF_PROFILE_H264_HIGH_422:
2859 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2860 // constraint_set3_flag set to 1
e5d40372 2861 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
fe9a3fbe
JG
2862 break;
2863 }
2864
2865 return profile;
2866}
2867
072be3e8
JG
2868static int h264_set_parameter_from_sps(H264Context *h)
2869{
2c541554 2870 if (h->flags & CODEC_FLAG_LOW_DELAY ||
072be3e8
JG
2871 (h->sps.bitstream_restriction_flag &&
2872 !h->sps.num_reorder_frames)) {
2c541554
AK
2873 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2874 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
072be3e8
JG
2875 "Reenabling low delay requires a codec flush.\n");
2876 else
2c541554 2877 h->low_delay = 1;
072be3e8
JG
2878 }
2879
2c541554
AK
2880 if (h->avctx->has_b_frames < 2)
2881 h->avctx->has_b_frames = !h->low_delay;
072be3e8 2882
4987faee 2883 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
12e25ed2
DB
2884 avpriv_request_sample(h->avctx,
2885 "Different chroma and luma bit depth");
4987faee
LB
2886 return AVERROR_PATCHWELCOME;
2887 }
2888
2c541554 2889 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
072be3e8 2890 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
072be3e8 2891 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
2c541554 2892 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
072be3e8
JG
2893 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2894 h->pixel_shift = h->sps.bit_depth_luma > 8;
2895
2896 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2897 h->sps.chroma_format_idc);
79dad2a9 2898 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
e9d81735 2899 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2c541554 2900 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
072be3e8 2901 h->sps.chroma_format_idc);
85deb51a
RB
2902 if (CONFIG_ERROR_RESILIENCE)
2903 ff_dsputil_init(&h->dsp, h->avctx);
2c541554 2904 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
072be3e8 2905 } else {
2c541554 2906 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
072be3e8
JG
2907 h->sps.bit_depth_luma);
2908 return AVERROR_INVALIDDATA;
2909 }
2910 }
2911 return 0;
2912}
2913
542b83fc 2914static enum AVPixelFormat get_pixel_format(H264Context *h)
9e696d2e 2915{
9e696d2e
JG
2916 switch (h->sps.bit_depth_luma) {
2917 case 9:
23e85be5 2918 if (CHROMA444(h)) {
2c541554 2919 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
9e696d2e
JG
2920 return AV_PIX_FMT_GBRP9;
2921 } else
2922 return AV_PIX_FMT_YUV444P9;
e962bd08 2923 } else if (CHROMA422(h))
9e696d2e
JG
2924 return AV_PIX_FMT_YUV422P9;
2925 else
2926 return AV_PIX_FMT_YUV420P9;
2927 break;
2928 case 10:
23e85be5 2929 if (CHROMA444(h)) {
2c541554 2930 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
9e696d2e
JG
2931 return AV_PIX_FMT_GBRP10;
2932 } else
2933 return AV_PIX_FMT_YUV444P10;
e962bd08 2934 } else if (CHROMA422(h))
9e696d2e
JG
2935 return AV_PIX_FMT_YUV422P10;
2936 else
2937 return AV_PIX_FMT_YUV420P10;
2938 break;
2939 case 8:
23e85be5 2940 if (CHROMA444(h)) {
2c541554 2941 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
9e696d2e
JG
2942 return AV_PIX_FMT_GBRP;
2943 } else
2c541554 2944 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
9e696d2e 2945 : AV_PIX_FMT_YUV444P;
e962bd08 2946 } else if (CHROMA422(h)) {
2c541554 2947 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
9e696d2e
JG
2948 : AV_PIX_FMT_YUV422P;
2949 } else {
2c541554
AK
2950 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
2951 h->avctx->codec->pix_fmts :
2952 h->avctx->color_range == AVCOL_RANGE_JPEG ?
d65522e8 2953 h264_hwaccel_pixfmt_list_jpeg_420 :
8d061989 2954 h264_hwaccel_pixfmt_list_420);
9e696d2e
JG
2955 }
2956 break;
2957 default:
2c541554 2958 av_log(h->avctx, AV_LOG_ERROR,
9e696d2e
JG
2959 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2960 return AVERROR_INVALIDDATA;
2961 }
2962}
2963
5e83d9ac
AK
2964/* export coded and cropped frame dimensions to AVCodecContext */
2965static int init_dimensions(H264Context *h)
2966{
2967 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
2968 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
2969
2970 /* handle container cropping */
2971 if (!h->sps.crop &&
2972 FFALIGN(h->avctx->width, 16) == h->width &&
2973 FFALIGN(h->avctx->height, 16) == h->height) {
2974 width = h->avctx->width;
2975 height = h->avctx->height;
2976 }
2977
2978 if (width <= 0 || height <= 0) {
2979 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
2980 width, height);
2981 if (h->avctx->err_recognition & AV_EF_EXPLODE)
2982 return AVERROR_INVALIDDATA;
2983
2984 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
2985 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
16c22122 2986 h->sps.crop = 0;
5e83d9ac
AK
2987
2988 width = h->width;
2989 height = h->height;
2990 }
2991
2992 h->avctx->coded_width = h->width;
2993 h->avctx->coded_height = h->height;
2994 h->avctx->width = width;
2995 h->avctx->height = height;
2996
2997 return 0;
2998}
2999
9e696d2e
JG
3000static int h264_slice_header_init(H264Context *h, int reinit)
3001{
2c541554
AK
3002 int nb_slices = (HAVE_THREADS &&
3003 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3004 h->avctx->thread_count : 1;
fce99322 3005 int i;
9e696d2e 3006
2c541554
AK
3007 h->avctx->sample_aspect_ratio = h->sps.sar;
3008 av_assert0(h->avctx->sample_aspect_ratio.den);
3009 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3010 &h->chroma_x_shift, &h->chroma_y_shift);
9e696d2e
JG
3011
3012 if (h->sps.timing_info_present_flag) {
3013 int64_t den = h->sps.time_scale;
3014 if (h->x264_build < 44U)
3015 den *= 2;
2c541554 3016 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
9e696d2e
JG
3017 h->sps.num_units_in_tick, den, 1 << 30);
3018 }
3019
2c541554 3020 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
9e696d2e 3021
2c541554 3022 if (reinit)
9e696d2e 3023 free_tables(h, 0);
16c22122 3024 h->first_field = 0;
9e696d2e
JG
3025 h->prev_interlaced_frame = 1;
3026
3027 init_scan_tables(h);
3028 if (ff_h264_alloc_tables(h) < 0) {
2c541554 3029 av_log(h->avctx, AV_LOG_ERROR,
9e696d2e
JG
3030 "Could not allocate memory for h264\n");
3031 return AVERROR(ENOMEM);
3032 }
3033
2c541554
AK
3034 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3035 int max_slices;
3036 if (h->mb_height)
3037 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3038 else
3039 max_slices = MAX_THREADS;
3040 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3041 " reducing to %d\n", nb_slices, max_slices);
3042 nb_slices = max_slices;
3043 }
3044 h->slice_context_count = nb_slices;
3045
3046 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
9e696d2e 3047 if (context_init(h) < 0) {
2c541554 3048 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
9e696d2e
JG
3049 return -1;
3050 }
3051 } else {
2c541554 3052 for (i = 1; i < h->slice_context_count; i++) {
9e696d2e 3053 H264Context *c;
16c22122
DB
3054 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3055 c->avctx = h->avctx;
3056 c->dsp = h->dsp;
3057 c->vdsp = h->vdsp;
3058 c->h264dsp = h->h264dsp;
3059 c->h264qpel = h->h264qpel;
3060 c->h264chroma = h->h264chroma;
3061 c->sps = h->sps;
3062 c->pps = h->pps;
3063 c->pixel_shift = h->pixel_shift;
3064 c->width = h->width;
3065 c->height = h->height;
3066 c->linesize = h->linesize;
3067 c->uvlinesize = h->uvlinesize;
3068 c->chroma_x_shift = h->chroma_x_shift;
3069 c->chroma_y_shift = h->chroma_y_shift;
3070 c->qscale = h->qscale;
3071 c->droppable = h->droppable;
2c541554 3072 c->data_partitioning = h->data_partitioning;
16c22122
DB
3073 c->low_delay = h->low_delay;
3074 c->mb_width = h->mb_width;
3075 c->mb_height = h->mb_height;
3076 c->mb_stride = h->mb_stride;
3077 c->mb_num = h->mb_num;
3078 c->flags = h->flags;
3079 c->workaround_bugs = h->workaround_bugs;
3080 c->pict_type = h->pict_type;
2c541554 3081
9e696d2e
JG
3082 init_scan_tables(c);
3083 clone_tables(c, h, i);
2c541554 3084 c->context_initialized = 1;
9e696d2e
JG
3085 }
3086
2c541554 3087 for (i = 0; i < h->slice_context_count; i++)
9e696d2e 3088 if (context_init(h->thread_context[i]) < 0) {
2c541554 3089 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
9e696d2e
JG
3090 return -1;
3091 }
3092 }
3093
2c541554
AK
3094 h->context_initialized = 1;
3095
9e696d2e
JG
3096 return 0;
3097}
3098
fe9a3fbe 3099/**
58c42af7 3100 * Decode a slice header.
efd29844 3101 * This will also call ff_MPV_common_init() and frame_start() as needed.
afebe2f7
3102 *
3103 * @param h h264context
e5d40372
DB
3104 * @param h0 h264 master context (differs from 'h' when doing sliced based
3105 * parallel decoding)
afebe2f7 3106 *
d9526386 3107 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
0da71265 3108 */
e5d40372
DB
3109static int decode_slice_header(H264Context *h, H264Context *h0)
3110{
88e7a4d1 3111 unsigned int first_mb_in_slice;
ac658be5 3112 unsigned int pps_id;
072be3e8 3113 int num_ref_idx_active_override_flag, max_refs, ret;
41f5c62f 3114 unsigned int slice_type, tmp, i, j;
0bf79634 3115 int default_ref_list_done = 0;
ba0c8981 3116 int last_pic_structure, last_pic_droppable;
9e696d2e 3117 int needs_reinit = 0;
0da71265 3118
2c541554
AK
3119 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3120 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
cf653d08 3121
2c541554 3122 first_mb_in_slice = get_ue_golomb(&h->gb);
0da71265 3123
e5d40372 3124 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
7fa00653 3125 if (h0->current_slice && FIELD_PICTURE(h)) {
6a9c8594 3126 field_end(h, 1);
d225a1e2
MN
3127 }
3128
afebe2f7 3129 h0->current_slice = 0;
2c541554 3130 if (!h0->first_field) {
759001c5
AK
3131 if (h->cur_pic_ptr && !h->droppable) {
3132 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2c541554 3133 h->picture_structure == PICT_BOTTOM_FIELD);
1e26a48f 3134 }
2c541554 3135 h->cur_pic_ptr = NULL;
1e26a48f 3136 }
66a4b2c1
MN
3137 }
3138
2c541554 3139 slice_type = get_ue_golomb_31(&h->gb);
e5d40372 3140 if (slice_type > 9) {
2c541554