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