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