h264: Add missing ff_ prefix to internally visible h264_init_dequant_tables()
[libav.git] / libavcodec / h264_slice.c
CommitLineData
f51d0f39
LB
1/*
2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
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
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
23 * @file
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
26 */
27
28#include "libavutil/avassert.h"
29#include "libavutil/imgutils.h"
30#include "libavutil/timer.h"
31#include "internal.h"
32#include "cabac.h"
33#include "cabac_functions.h"
f51d0f39
LB
34#include "error_resilience.h"
35#include "avcodec.h"
36#include "h264.h"
37#include "h264data.h"
38#include "h264chroma.h"
39#include "h264_mvpred.h"
40#include "golomb.h"
41#include "mathops.h"
42#include "mpegutils.h"
43#include "rectangle.h"
44#include "thread.h"
45
f51d0f39
LB
46static const uint8_t field_scan[16] = {
47 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
48 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
49 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
50 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
51};
52
53static const uint8_t field_scan8x8[64] = {
54 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
55 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
56 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
57 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
58 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
59 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
60 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
61 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
62 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
63 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
64 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
65 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
66 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
67 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
68 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
69 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
70};
71
72static const uint8_t field_scan8x8_cavlc[64] = {
73 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
74 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
75 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
76 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
77 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
78 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
79 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
80 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
81 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
82 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
83 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
84 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
85 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
86 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
87 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
88 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
89};
90
91// zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
92static const uint8_t zigzag_scan8x8_cavlc[64] = {
93 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
94 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
95 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
96 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
97 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
98 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
99 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
100 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
101 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
102 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
103 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
104 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
105 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
106 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
107 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
108 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
109};
110
f51d0f39
LB
111static void release_unused_pictures(H264Context *h, int remove_current)
112{
113 int i;
114
115 /* release non reference frames */
116 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
a0f29460 117 if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
f51d0f39
LB
118 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
119 ff_h264_unref_picture(h, &h->DPB[i]);
120 }
121 }
122}
123
36d04801 124static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
f51d0f39 125{
c377e04d 126 const H264Context *h = sl->h264;
f51d0f39
LB
127 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
128
36d04801 129 av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
f51d0f39
LB
130 // edge emu needs blocksize + filter length - 1
131 // (= 21x21 for h264)
36d04801 132 av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
f51d0f39 133
c377e04d
AK
134 av_fast_malloc(&sl->top_borders[0], &sl->top_borders_allocated[0],
135 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
136 av_fast_malloc(&sl->top_borders[1], &sl->top_borders_allocated[1],
137 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
138
139 if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
140 !sl->top_borders[0] || !sl->top_borders[1]) {
36d04801
AK
141 av_freep(&sl->bipred_scratchpad);
142 av_freep(&sl->edge_emu_buffer);
c377e04d
AK
143 av_freep(&sl->top_borders[0]);
144 av_freep(&sl->top_borders[1]);
145
36d04801
AK
146 sl->bipred_scratchpad_allocated = 0;
147 sl->edge_emu_buffer_allocated = 0;
c377e04d
AK
148 sl->top_borders_allocated[0] = 0;
149 sl->top_borders_allocated[1] = 0;
f51d0f39
LB
150 return AVERROR(ENOMEM);
151 }
152
153 return 0;
154}
155
156static int init_table_pools(H264Context *h)
157{
158 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
159 const int mb_array_size = h->mb_stride * h->mb_height;
160 const int b4_stride = h->mb_width * 4 + 1;
161 const int b4_array_size = b4_stride * h->mb_height * 4;
162
163 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
164 av_buffer_allocz);
165 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
166 sizeof(uint32_t), av_buffer_allocz);
2db953f8
LB
167 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
168 sizeof(int16_t), av_buffer_allocz);
169 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
f51d0f39
LB
170
171 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
172 !h->ref_index_pool) {
173 av_buffer_pool_uninit(&h->qscale_table_pool);
174 av_buffer_pool_uninit(&h->mb_type_pool);
175 av_buffer_pool_uninit(&h->motion_val_pool);
176 av_buffer_pool_uninit(&h->ref_index_pool);
177 return AVERROR(ENOMEM);
178 }
179
180 return 0;
181}
182
183static int alloc_picture(H264Context *h, H264Picture *pic)
184{
185 int i, ret = 0;
186
a0f29460 187 av_assert0(!pic->f->data[0]);
f51d0f39 188
a0f29460 189 pic->tf.f = pic->f;
f51d0f39
LB
190 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
191 AV_GET_BUFFER_FLAG_REF : 0);
192 if (ret < 0)
193 goto fail;
194
f51d0f39
LB
195 if (h->avctx->hwaccel) {
196 const AVHWAccel *hwaccel = h->avctx->hwaccel;
197 av_assert0(!pic->hwaccel_picture_private);
a871ef0c
AK
198 if (hwaccel->frame_priv_data_size) {
199 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
f51d0f39
LB
200 if (!pic->hwaccel_priv_buf)
201 return AVERROR(ENOMEM);
202 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
203 }
204 }
205
206 if (!h->qscale_table_pool) {
207 ret = init_table_pools(h);
208 if (ret < 0)
209 goto fail;
210 }
211
212 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
213 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
214 if (!pic->qscale_table_buf || !pic->mb_type_buf)
215 goto fail;
216
217 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
218 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
219
220 for (i = 0; i < 2; i++) {
221 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
222 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
223 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
224 goto fail;
225
226 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
227 pic->ref_index[i] = pic->ref_index_buf[i]->data;
228 }
229
230 return 0;
231fail:
232 ff_h264_unref_picture(h, pic);
233 return (ret < 0) ? ret : AVERROR(ENOMEM);
234}
235
236static inline int pic_is_unused(H264Context *h, H264Picture *pic)
237{
a0f29460 238 if (!pic->f->buf[0])
f51d0f39 239 return 1;
f51d0f39
LB
240 return 0;
241}
242
243static int find_unused_picture(H264Context *h)
244{
245 int i;
246
247 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
248 if (pic_is_unused(h, &h->DPB[i]))
249 break;
250 }
251 if (i == H264_MAX_PICTURE_COUNT)
252 return AVERROR_INVALIDDATA;
253
f51d0f39
LB
254 return i;
255}
256
f1ccd076
AK
257static int initialize_cur_frame(H264Context *h)
258{
259 H264Picture *cur;
260 int ret;
261
262 release_unused_pictures(h, 1);
263 ff_h264_unref_picture(h, &h->cur_pic);
264 h->cur_pic_ptr = NULL;
265
266 ret = find_unused_picture(h);
267 if (ret < 0) {
268 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
269 return ret;
270 }
271 cur = &h->DPB[ret];
272
273 ret = alloc_picture(h, cur);
274 if (ret < 0)
275 return ret;
276
277 ret = ff_h264_ref_picture(h, &h->cur_pic, cur);
278 if (ret < 0)
279 return ret;
280 h->cur_pic_ptr = cur;
281
282 return 0;
283}
f51d0f39
LB
284
285static void init_dequant8_coeff_table(H264Context *h)
286{
287 int i, j, q, x;
288 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
289
290 for (i = 0; i < 6; i++) {
291 h->dequant8_coeff[i] = h->dequant8_buffer[i];
292 for (j = 0; j < i; j++)
293 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
294 64 * sizeof(uint8_t))) {
295 h->dequant8_coeff[i] = h->dequant8_buffer[j];
296 break;
297 }
298 if (j < i)
299 continue;
300
301 for (q = 0; q < max_qp + 1; q++) {
ad9d3384
AK
302 int shift = ff_h264_quant_div6[q];
303 int idx = ff_h264_quant_rem6[q];
f51d0f39
LB
304 for (x = 0; x < 64; x++)
305 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
ad9d3384 306 ((uint32_t)ff_h264_dequant8_coeff_init[idx][ff_h264_dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
f51d0f39
LB
307 h->pps.scaling_matrix8[i][x]) << shift;
308 }
309 }
310}
311
312static void init_dequant4_coeff_table(H264Context *h)
313{
314 int i, j, q, x;
315 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
316 for (i = 0; i < 6; i++) {
317 h->dequant4_coeff[i] = h->dequant4_buffer[i];
318 for (j = 0; j < i; j++)
319 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
320 16 * sizeof(uint8_t))) {
321 h->dequant4_coeff[i] = h->dequant4_buffer[j];
322 break;
323 }
324 if (j < i)
325 continue;
326
327 for (q = 0; q < max_qp + 1; q++) {
ad9d3384
AK
328 int shift = ff_h264_quant_div6[q] + 2;
329 int idx = ff_h264_quant_rem6[q];
f51d0f39
LB
330 for (x = 0; x < 16; x++)
331 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
ad9d3384 332 ((uint32_t)ff_h264_dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
f51d0f39
LB
333 h->pps.scaling_matrix4[i][x]) << shift;
334 }
335 }
336}
337
061dc203 338void ff_h264_init_dequant_tables(H264Context *h)
f51d0f39
LB
339{
340 int i, x;
341 init_dequant4_coeff_table(h);
342 if (h->pps.transform_8x8_mode)
343 init_dequant8_coeff_table(h);
344 if (h->sps.transform_bypass) {
345 for (i = 0; i < 6; i++)
346 for (x = 0; x < 16; x++)
347 h->dequant4_coeff[i][0][x] = 1 << 6;
348 if (h->pps.transform_8x8_mode)
349 for (i = 0; i < 6; i++)
350 for (x = 0; x < 64; x++)
351 h->dequant8_coeff[i][0][x] = 1 << 6;
352 }
353}
354
f51d0f39 355#define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
d75190aa 356
f51d0f39
LB
357#define REBASE_PICTURE(pic, new_ctx, old_ctx) \
358 ((pic && pic >= old_ctx->DPB && \
359 pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
360 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
361
362static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
363 H264Context *new_base,
364 H264Context *old_base)
365{
366 int i;
367
368 for (i = 0; i < count; i++) {
369 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
370 IN_RANGE(from[i], old_base->DPB,
371 sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
372 !from[i]));
373 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
374 }
375}
376
377static int copy_parameter_set(void **to, void **from, int count, int size)
378{
379 int i;
380
381 for (i = 0; i < count; i++) {
382 if (to[i] && !from[i]) {
383 av_freep(&to[i]);
384 } else if (from[i] && !to[i]) {
385 to[i] = av_malloc(size);
386 if (!to[i])
387 return AVERROR(ENOMEM);
388 }
389
390 if (from[i])
391 memcpy(to[i], from[i], size);
392 }
393
394 return 0;
395}
396
397#define copy_fields(to, from, start_field, end_field) \
398 memcpy(&to->start_field, &from->start_field, \
399 (char *)&to->end_field - (char *)&to->start_field)
400
8a66fd40 401static int h264_slice_header_init(H264Context *h);
f51d0f39
LB
402
403int ff_h264_update_thread_context(AVCodecContext *dst,
404 const AVCodecContext *src)
405{
406 H264Context *h = dst->priv_data, *h1 = src->priv_data;
407 int inited = h->context_initialized, err = 0;
54986d6d 408 int need_reinit = 0;
f51d0f39
LB
409 int i, ret;
410
411 if (dst == src || !h1->context_initialized)
412 return 0;
413
414 if (inited &&
415 (h->width != h1->width ||
416 h->height != h1->height ||
417 h->mb_width != h1->mb_width ||
418 h->mb_height != h1->mb_height ||
419 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
420 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
421 h->sps.colorspace != h1->sps.colorspace)) {
54986d6d 422 need_reinit = 1;
f51d0f39
LB
423 }
424
88c612e3
AK
425 // SPS/PPS
426 if ((ret = copy_parameter_set((void **)h->sps_buffers,
427 (void **)h1->sps_buffers,
428 MAX_SPS_COUNT, sizeof(SPS))) < 0)
429 return ret;
430 h->sps = h1->sps;
431 if ((ret = copy_parameter_set((void **)h->pps_buffers,
432 (void **)h1->pps_buffers,
433 MAX_PPS_COUNT, sizeof(PPS))) < 0)
434 return ret;
435 h->pps = h1->pps;
436
437 if (need_reinit || !inited) {
438 h->width = h1->width;
439 h->height = h1->height;
440 h->mb_height = h1->mb_height;
441 h->mb_width = h1->mb_width;
442 h->mb_num = h1->mb_num;
443 h->mb_stride = h1->mb_stride;
444 h->b_stride = h1->b_stride;
445
446 if ((err = h264_slice_header_init(h)) < 0) {
447 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
448 return err;
f51d0f39
LB
449 }
450
88c612e3
AK
451 /* copy block_offset since frame_start may not be called */
452 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
f51d0f39
LB
453 }
454
455 h->avctx->coded_height = h1->avctx->coded_height;
456 h->avctx->coded_width = h1->avctx->coded_width;
457 h->avctx->width = h1->avctx->width;
458 h->avctx->height = h1->avctx->height;
459 h->coded_picture_number = h1->coded_picture_number;
460 h->first_field = h1->first_field;
461 h->picture_structure = h1->picture_structure;
f51d0f39
LB
462 h->droppable = h1->droppable;
463 h->low_delay = h1->low_delay;
464
465 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
466 ff_h264_unref_picture(h, &h->DPB[i]);
a0f29460 467 if (h1->DPB[i].f->buf[0] &&
f51d0f39
LB
468 (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
469 return ret;
470 }
471
472 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
473 ff_h264_unref_picture(h, &h->cur_pic);
a0f29460 474 if (h1->cur_pic.f->buf[0]) {
0dea4c77
AK
475 ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
476 if (ret < 0)
477 return ret;
478 }
f51d0f39 479
a4d34e21 480 h->enable_er = h1->enable_er;
f51d0f39
LB
481 h->workaround_bugs = h1->workaround_bugs;
482 h->low_delay = h1->low_delay;
483 h->droppable = h1->droppable;
484
f51d0f39
LB
485 // extradata/NAL handling
486 h->is_avc = h1->is_avc;
29dcde2b 487 h->nal_length_size = h1->nal_length_size;
f51d0f39 488
f51d0f39
LB
489 // Dequantization matrices
490 // FIXME these are big - can they be only copied when PPS changes?
491 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
492
493 for (i = 0; i < 6; i++)
494 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
495 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
496
497 for (i = 0; i < 6; i++)
498 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
499 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
500
501 h->dequant_coeff_pps = h1->dequant_coeff_pps;
502
503 // POC timing
741b494f 504 copy_fields(h, h1, poc_lsb, current_slice);
f51d0f39
LB
505
506 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
507 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
508 copy_picture_range(h->delayed_pic, h1->delayed_pic,
509 MAX_DELAYED_PIC_COUNT + 2, h, h1);
510
f51d0f39
LB
511 if (!h->cur_pic_ptr)
512 return 0;
513
514 if (!h->droppable) {
515 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
516 h->prev_poc_msb = h->poc_msb;
517 h->prev_poc_lsb = h->poc_lsb;
518 }
519 h->prev_frame_num_offset = h->frame_num_offset;
520 h->prev_frame_num = h->frame_num;
f51d0f39
LB
521
522 h->recovery_frame = h1->recovery_frame;
523 h->frame_recovered = h1->frame_recovered;
524
525 return err;
526}
527
528static int h264_frame_start(H264Context *h)
529{
530 H264Picture *pic;
531 int i, ret;
532 const int pixel_shift = h->pixel_shift;
533
f1ccd076
AK
534 ret = initialize_cur_frame(h);
535 if (ret < 0)
536 return ret;
f51d0f39 537
f1ccd076 538 pic = h->cur_pic_ptr;
f51d0f39 539 pic->reference = h->droppable ? 0 : h->picture_structure;
a0f29460 540 pic->f->coded_picture_number = h->coded_picture_number++;
f51d0f39 541 pic->field_picture = h->picture_structure != PICT_FRAME;
792b9c9d 542 pic->frame_num = h->frame_num;
f51d0f39
LB
543 /*
544 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
545 * in later.
546 * See decode_nal_units().
547 */
a0f29460 548 pic->f->key_frame = 0;
f51d0f39
LB
549 pic->mmco_reset = 0;
550 pic->recovered = 0;
551
a4d34e21 552 if (CONFIG_ERROR_RESILIENCE && h->enable_er)
582683b6 553 ff_er_frame_start(&h->slice_ctx[0].er);
f51d0f39 554
f51d0f39 555 for (i = 0; i < 16; i++) {
a0f29460
AK
556 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
557 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
f51d0f39
LB
558 }
559 for (i = 0; i < 16; i++) {
560 h->block_offset[16 + i] =
a0f29460 561 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
f51d0f39 562 h->block_offset[48 + 16 + i] =
a0f29460 563 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
f51d0f39
LB
564 }
565
f51d0f39
LB
566 /* Some macroblocks can be accessed before they're available in case
567 * of lost slices, MBAFF or threading. */
568 memset(h->slice_table, -1,
569 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
570
f51d0f39
LB
571 /* We mark the current picture as non-reference after allocating it, so
572 * that if we break out due to an error it can be released automatically
835f798c 573 * in the next ff_mpv_frame_start().
f51d0f39
LB
574 */
575 h->cur_pic_ptr->reference = 0;
576
577 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
578
579 h->next_output_pic = NULL;
580
581 assert(h->cur_pic_ptr->long_ref == 0);
582
583 return 0;
584}
585
92e0b734 586static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
d4d9068c 587 uint8_t *src_y,
f51d0f39
LB
588 uint8_t *src_cb, uint8_t *src_cr,
589 int linesize, int uvlinesize,
590 int simple)
591{
592 uint8_t *top_border;
593 int top_idx = 1;
594 const int pixel_shift = h->pixel_shift;
595 int chroma444 = CHROMA444(h);
596 int chroma422 = CHROMA422(h);
597
598 src_y -= linesize;
599 src_cb -= uvlinesize;
600 src_cr -= uvlinesize;
601
602 if (!simple && FRAME_MBAFF(h)) {
d4d9068c 603 if (sl->mb_y & 1) {
e9b2383b 604 if (!MB_MBAFF(sl)) {
c377e04d 605 top_border = sl->top_borders[0][sl->mb_x];
f51d0f39
LB
606 AV_COPY128(top_border, src_y + 15 * linesize);
607 if (pixel_shift)
608 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
7c6eb0a1 609 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
f51d0f39
LB
610 if (chroma444) {
611 if (pixel_shift) {
612 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
613 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
614 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
615 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
616 } else {
617 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
618 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
619 }
620 } else if (chroma422) {
621 if (pixel_shift) {
622 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
623 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
624 } else {
625 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
626 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
627 }
628 } else {
629 if (pixel_shift) {
630 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
631 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
632 } else {
633 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
634 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
635 }
636 }
637 }
638 }
e9b2383b 639 } else if (MB_MBAFF(sl)) {
f51d0f39
LB
640 top_idx = 0;
641 } else
642 return;
643 }
644
c377e04d 645 top_border = sl->top_borders[top_idx][sl->mb_x];
f51d0f39
LB
646 /* There are two lines saved, the line above the top macroblock
647 * of a pair, and the line above the bottom macroblock. */
648 AV_COPY128(top_border, src_y + 16 * linesize);
649 if (pixel_shift)
650 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
651
7c6eb0a1 652 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
f51d0f39
LB
653 if (chroma444) {
654 if (pixel_shift) {
655 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
656 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
657 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
658 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
659 } else {
660 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
661 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
662 }
663 } else if (chroma422) {
664 if (pixel_shift) {
665 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
666 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
667 } else {
668 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
669 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
670 }
671 } else {
672 if (pixel_shift) {
673 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
674 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
675 } else {
676 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
677 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
678 }
679 }
680 }
681}
682
683/**
684 * Initialize implicit_weight table.
685 * @param field 0/1 initialize the weight for interlaced MBAFF
686 * -1 initializes the rest
687 */
92e0b734 688static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
f51d0f39
LB
689{
690 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
691
692 for (i = 0; i < 2; i++) {
e481458b
AK
693 sl->pwt.luma_weight_flag[i] = 0;
694 sl->pwt.chroma_weight_flag[i] = 0;
f51d0f39
LB
695 }
696
697 if (field < 0) {
698 if (h->picture_structure == PICT_FRAME) {
699 cur_poc = h->cur_pic_ptr->poc;
700 } else {
701 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
702 }
95eb35f3
AK
703 if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
704 sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
e481458b
AK
705 sl->pwt.use_weight = 0;
706 sl->pwt.use_weight_chroma = 0;
f51d0f39
LB
707 return;
708 }
709 ref_start = 0;
95eb35f3
AK
710 ref_count0 = sl->ref_count[0];
711 ref_count1 = sl->ref_count[1];
f51d0f39
LB
712 } else {
713 cur_poc = h->cur_pic_ptr->field_poc[field];
714 ref_start = 16;
95eb35f3
AK
715 ref_count0 = 16 + 2 * sl->ref_count[0];
716 ref_count1 = 16 + 2 * sl->ref_count[1];
f51d0f39
LB
717 }
718
e481458b
AK
719 sl->pwt.use_weight = 2;
720 sl->pwt.use_weight_chroma = 2;
721 sl->pwt.luma_log2_weight_denom = 5;
722 sl->pwt.chroma_log2_weight_denom = 5;
f51d0f39
LB
723
724 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
95eb35f3 725 int poc0 = sl->ref_list[0][ref0].poc;
f51d0f39
LB
726 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
727 int w = 32;
a12d3188 728 if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
95eb35f3 729 int poc1 = sl->ref_list[1][ref1].poc;
9abc80f1 730 int td = av_clip_int8(poc1 - poc0);
f51d0f39 731 if (td) {
9abc80f1 732 int tb = av_clip_int8(cur_poc - poc0);
f51d0f39
LB
733 int tx = (16384 + (FFABS(td) >> 1)) / td;
734 int dist_scale_factor = (tb * tx + 32) >> 8;
735 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
736 w = 64 - dist_scale_factor;
737 }
738 }
739 if (field < 0) {
e481458b
AK
740 sl->pwt.implicit_weight[ref0][ref1][0] =
741 sl->pwt.implicit_weight[ref0][ref1][1] = w;
f51d0f39 742 } else {
e481458b 743 sl->pwt.implicit_weight[ref0][ref1][field] = w;
f51d0f39
LB
744 }
745 }
746 }
747}
748
749/**
750 * initialize scan tables
751 */
752static void init_scan_tables(H264Context *h)
753{
754 int i;
755 for (i = 0; i < 16; i++) {
756#define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
f4d581cd 757 h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
f51d0f39
LB
758 h->field_scan[i] = TRANSPOSE(field_scan[i]);
759#undef TRANSPOSE
760 }
761 for (i = 0; i < 64; i++) {
762#define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
763 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
764 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
765 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
766 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
767#undef TRANSPOSE
768 }
769 if (h->sps.transform_bypass) { // FIXME same ugly
f4d581cd 770 h->zigzag_scan_q0 = ff_zigzag_scan;
f51d0f39
LB
771 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
772 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
773 h->field_scan_q0 = field_scan;
774 h->field_scan8x8_q0 = field_scan8x8;
775 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
776 } else {
777 h->zigzag_scan_q0 = h->zigzag_scan;
778 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
779 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
780 h->field_scan_q0 = h->field_scan;
781 h->field_scan8x8_q0 = h->field_scan8x8;
782 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
783 }
784}
785
f51d0f39
LB
786static enum AVPixelFormat get_pixel_format(H264Context *h)
787{
4cfbeef3 788#define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
08d006f5 789 CONFIG_H264_D3D11VA_HWACCEL + \
4cfbeef3
RDC
790 CONFIG_H264_VAAPI_HWACCEL + \
791 (CONFIG_H264_VDA_HWACCEL * 2) + \
792 CONFIG_H264_VDPAU_HWACCEL)
793 enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
ce423163
RDC
794 const enum AVPixelFormat *choices = pix_fmts;
795
f51d0f39
LB
796 switch (h->sps.bit_depth_luma) {
797 case 9:
798 if (CHROMA444(h)) {
799 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
4cfbeef3 800 *fmt++ = AV_PIX_FMT_GBRP9;
f51d0f39 801 } else
4cfbeef3 802 *fmt++ = AV_PIX_FMT_YUV444P9;
f51d0f39 803 } else if (CHROMA422(h))
4cfbeef3 804 *fmt++ = AV_PIX_FMT_YUV422P9;
f51d0f39 805 else
4cfbeef3 806 *fmt++ = AV_PIX_FMT_YUV420P9;
f51d0f39
LB
807 break;
808 case 10:
809 if (CHROMA444(h)) {
810 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
4cfbeef3 811 *fmt++ = AV_PIX_FMT_GBRP10;
f51d0f39 812 } else
4cfbeef3 813 *fmt++ = AV_PIX_FMT_YUV444P10;
f51d0f39 814 } else if (CHROMA422(h))
4cfbeef3 815 *fmt++ = AV_PIX_FMT_YUV422P10;
f51d0f39 816 else
4cfbeef3 817 *fmt++ = AV_PIX_FMT_YUV420P10;
f51d0f39
LB
818 break;
819 case 8:
ebd5320a
RDC
820#if CONFIG_H264_VDPAU_HWACCEL
821 *fmt++ = AV_PIX_FMT_VDPAU;
822#endif
f51d0f39 823 if (CHROMA444(h)) {
ce423163 824 if (h->avctx->colorspace == AVCOL_SPC_RGB)
4cfbeef3 825 *fmt++ = AV_PIX_FMT_GBRP;
ce423163 826 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
4cfbeef3 827 *fmt++ = AV_PIX_FMT_YUVJ444P;
ce423163 828 else
4cfbeef3 829 *fmt++ = AV_PIX_FMT_YUV444P;
f51d0f39 830 } else if (CHROMA422(h)) {
ce423163 831 if (h->avctx->color_range == AVCOL_RANGE_JPEG)
4cfbeef3 832 *fmt++ = AV_PIX_FMT_YUVJ422P;
ce423163 833 else
4cfbeef3 834 *fmt++ = AV_PIX_FMT_YUV422P;
f51d0f39 835 } else {
4cfbeef3
RDC
836#if CONFIG_H264_DXVA2_HWACCEL
837 *fmt++ = AV_PIX_FMT_DXVA2_VLD;
838#endif
d8039ef8
SL
839#if CONFIG_H264_D3D11VA_HWACCEL
840 *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
841#endif
4cfbeef3 842#if CONFIG_H264_VAAPI_HWACCEL
d264c720 843 *fmt++ = AV_PIX_FMT_VAAPI;
4cfbeef3
RDC
844#endif
845#if CONFIG_H264_VDA_HWACCEL
846 *fmt++ = AV_PIX_FMT_VDA_VLD;
847 *fmt++ = AV_PIX_FMT_VDA;
848#endif
ce423163
RDC
849 if (h->avctx->codec->pix_fmts)
850 choices = h->avctx->codec->pix_fmts;
851 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
4cfbeef3 852 *fmt++ = AV_PIX_FMT_YUVJ420P;
ce423163 853 else
4cfbeef3 854 *fmt++ = AV_PIX_FMT_YUV420P;
f51d0f39
LB
855 }
856 break;
857 default:
858 av_log(h->avctx, AV_LOG_ERROR,
859 "Unsupported bit depth %d\n", h->sps.bit_depth_luma);
860 return AVERROR_INVALIDDATA;
861 }
ce423163 862
4cfbeef3
RDC
863 *fmt = AV_PIX_FMT_NONE;
864
ce423163 865 return ff_get_format(h->avctx, choices);
f51d0f39
LB
866}
867
868/* export coded and cropped frame dimensions to AVCodecContext */
869static int init_dimensions(H264Context *h)
870{
871 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
872 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
873
874 /* handle container cropping */
3e3056f2
VG
875 if (FFALIGN(h->avctx->width, 16) == FFALIGN(width, 16) &&
876 FFALIGN(h->avctx->height, 16) == FFALIGN(height, 16)) {
f51d0f39
LB
877 width = h->avctx->width;
878 height = h->avctx->height;
879 }
880
881 if (width <= 0 || height <= 0) {
882 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
883 width, height);
884 if (h->avctx->err_recognition & AV_EF_EXPLODE)
885 return AVERROR_INVALIDDATA;
886
887 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
2db953f8
LB
888 h->sps.crop_bottom =
889 h->sps.crop_top =
890 h->sps.crop_right =
891 h->sps.crop_left =
f51d0f39
LB
892 h->sps.crop = 0;
893
894 width = h->width;
895 height = h->height;
896 }
897
898 h->avctx->coded_width = h->width;
899 h->avctx->coded_height = h->height;
900 h->avctx->width = width;
901 h->avctx->height = height;
902
903 return 0;
904}
905
8a66fd40 906static int h264_slice_header_init(H264Context *h)
f51d0f39
LB
907{
908 int nb_slices = (HAVE_THREADS &&
909 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
910 h->avctx->thread_count : 1;
911 int i, ret;
912
9e500efd 913 ff_set_sar(h->avctx, h->sps.sar);
f51d0f39
LB
914 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
915 &h->chroma_x_shift, &h->chroma_y_shift);
916
917 if (h->sps.timing_info_present_flag) {
918 int64_t den = h->sps.time_scale;
919 if (h->x264_build < 44U)
920 den *= 2;
7ea1b347 921 av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
f51d0f39
LB
922 h->sps.num_units_in_tick, den, 1 << 30);
923 }
924
8a66fd40
AK
925 ff_h264_free_tables(h);
926
f51d0f39
LB
927 h->first_field = 0;
928 h->prev_interlaced_frame = 1;
929
930 init_scan_tables(h);
931 ret = ff_h264_alloc_tables(h);
932 if (ret < 0) {
933 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
934 return ret;
935 }
936
ee62b364
AK
937 if (h->sps.bit_depth_luma < 8 || h->sps.bit_depth_luma > 10) {
938 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
939 h->sps.bit_depth_luma);
940 return AVERROR_INVALIDDATA;
941 }
942
943 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
944 h->pixel_shift = h->sps.bit_depth_luma > 8;
c9ccbc73
AK
945 h->chroma_format_idc = h->sps.chroma_format_idc;
946 h->bit_depth_luma = h->sps.bit_depth_luma;
ee62b364
AK
947
948 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
949 h->sps.chroma_format_idc);
950 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
951 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
952 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
953 h->sps.chroma_format_idc);
954 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
955
f51d0f39
LB
956 if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
957 int max_slices;
958 if (h->mb_height)
959 max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
960 else
961 max_slices = H264_MAX_THREADS;
962 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
963 " reducing to %d\n", nb_slices, max_slices);
964 nb_slices = max_slices;
965 }
966 h->slice_context_count = nb_slices;
967
968 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
582683b6 969 ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
f51d0f39
LB
970 if (ret < 0) {
971 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
972 return ret;
973 }
974 } else {
5bf3c0fa
AK
975 for (i = 0; i < h->slice_context_count; i++) {
976 H264SliceContext *sl = &h->slice_ctx[i];
f51d0f39 977
5bf3c0fa
AK
978 sl->h264 = h;
979 sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
980 sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
981 sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
982
983 if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
f51d0f39
LB
984 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
985 return ret;
986 }
5bf3c0fa 987 }
f51d0f39
LB
988 }
989
990 h->context_initialized = 1;
991
992 return 0;
993}
994
995/**
996 * Decode a slice header.
997 * This will (re)intialize the decoder and call h264_frame_start() as needed.
998 *
999 * @param h h264context
f51d0f39
LB
1000 *
1001 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
1002 */
51d8725a 1003int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl)
f51d0f39
LB
1004{
1005 unsigned int first_mb_in_slice;
1006 unsigned int pps_id;
1007 int ret;
1008 unsigned int slice_type, tmp, i, j;
f51d0f39
LB
1009 int last_pic_structure, last_pic_droppable;
1010 int needs_reinit = 0;
1011 int field_pic_flag, bottom_field_flag;
5ec0bdf2
AK
1012 int frame_num, droppable, picture_structure;
1013 int mb_aff_frame = 0;
f51d0f39
LB
1014
1015 h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
1016 h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
1017
f42485db 1018 first_mb_in_slice = get_ue_golomb(&sl->gb);
f51d0f39
LB
1019
1020 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
51d8725a 1021 if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
95eb35f3 1022 ff_h264_field_end(h, sl, 1);
f51d0f39
LB
1023 }
1024
51d8725a
AK
1025 h->current_slice = 0;
1026 if (!h->first_field) {
f51d0f39
LB
1027 if (h->cur_pic_ptr && !h->droppable) {
1028 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1029 h->picture_structure == PICT_BOTTOM_FIELD);
1030 }
1031 h->cur_pic_ptr = NULL;
1032 }
1033 }
1034
f42485db 1035 slice_type = get_ue_golomb_31(&sl->gb);
f51d0f39
LB
1036 if (slice_type > 9) {
1037 av_log(h->avctx, AV_LOG_ERROR,
d4d9068c
AK
1038 "slice type %d too large at %d\n",
1039 slice_type, first_mb_in_slice);
f51d0f39
LB
1040 return AVERROR_INVALIDDATA;
1041 }
1042 if (slice_type > 4) {
1043 slice_type -= 5;
56febc99 1044 sl->slice_type_fixed = 1;
f51d0f39 1045 } else
56febc99 1046 sl->slice_type_fixed = 0;
f51d0f39 1047
a7da517f 1048 slice_type = ff_h264_golomb_to_pict_type[slice_type];
56febc99
AK
1049 sl->slice_type = slice_type;
1050 sl->slice_type_nos = slice_type & 3;
f51d0f39
LB
1051
1052 if (h->nal_unit_type == NAL_IDR_SLICE &&
56febc99 1053 sl->slice_type_nos != AV_PICTURE_TYPE_I) {
f51d0f39
LB
1054 av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1055 return AVERROR_INVALIDDATA;
1056 }
1057
1058 // to make a few old functions happy, it's wrong though
5ec0bdf2
AK
1059 if (!h->setup_finished)
1060 h->pict_type = sl->slice_type;
f51d0f39 1061
f42485db 1062 pps_id = get_ue_golomb(&sl->gb);
f51d0f39
LB
1063 if (pps_id >= MAX_PPS_COUNT) {
1064 av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
1065 return AVERROR_INVALIDDATA;
1066 }
51d8725a 1067 if (!h->pps_buffers[pps_id]) {
f51d0f39
LB
1068 av_log(h->avctx, AV_LOG_ERROR,
1069 "non-existing PPS %u referenced\n",
1070 pps_id);
1071 return AVERROR_INVALIDDATA;
1072 }
5ec0bdf2
AK
1073 if (!h->setup_finished) {
1074 h->pps = *h->pps_buffers[pps_id];
1075 } else if (h->dequant_coeff_pps != pps_id) {
1076 av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
1077 return AVERROR_INVALIDDATA;
1078 }
f51d0f39 1079
51d8725a 1080 if (!h->sps_buffers[h->pps.sps_id]) {
f51d0f39
LB
1081 av_log(h->avctx, AV_LOG_ERROR,
1082 "non-existing SPS %u referenced\n",
1083 h->pps.sps_id);
1084 return AVERROR_INVALIDDATA;
1085 }
1086
1087 if (h->pps.sps_id != h->sps.sps_id ||
51d8725a
AK
1088 h->sps_buffers[h->pps.sps_id]->new) {
1089 h->sps_buffers[h->pps.sps_id]->new = 0;
f51d0f39 1090
51d8725a 1091 h->sps = *h->sps_buffers[h->pps.sps_id];
f51d0f39
LB
1092
1093 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
c9ccbc73 1094 h->chroma_format_idc != h->sps.chroma_format_idc)
f51d0f39 1095 needs_reinit = 1;
ee62b364 1096
7c6eb0a1 1097 if (h->flags & AV_CODEC_FLAG_LOW_DELAY ||
ee62b364
AK
1098 (h->sps.bitstream_restriction_flag &&
1099 !h->sps.num_reorder_frames)) {
1100 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1101 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1102 "Reenabling low delay requires a codec flush.\n");
1103 else
1104 h->low_delay = 1;
1105 }
1106
1107 if (h->avctx->has_b_frames < 2)
1108 h->avctx->has_b_frames = !h->low_delay;
1109
f51d0f39
LB
1110 }
1111
5ec0bdf2
AK
1112 if (!h->setup_finished) {
1113 h->avctx->profile = ff_h264_get_profile(&h->sps);
1114 h->avctx->level = h->sps.level_idc;
1115 h->avctx->refs = h->sps.ref_frame_count;
f51d0f39 1116
5ec0bdf2
AK
1117 if (h->mb_width != h->sps.mb_width ||
1118 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
1119 needs_reinit = 1;
f51d0f39 1120
5ec0bdf2
AK
1121 h->mb_width = h->sps.mb_width;
1122 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
1123 h->mb_num = h->mb_width * h->mb_height;
1124 h->mb_stride = h->mb_width + 1;
f51d0f39 1125
5ec0bdf2 1126 h->b_stride = h->mb_width * 4;
f51d0f39 1127
5ec0bdf2 1128 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
f51d0f39 1129
5ec0bdf2
AK
1130 h->width = 16 * h->mb_width;
1131 h->height = 16 * h->mb_height;
f51d0f39 1132
5ec0bdf2
AK
1133 ret = init_dimensions(h);
1134 if (ret < 0)
1135 return ret;
f51d0f39 1136
5ec0bdf2
AK
1137 if (h->sps.video_signal_type_present_flag) {
1138 h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
1139 : AVCOL_RANGE_MPEG;
1140 if (h->sps.colour_description_present_flag) {
1141 if (h->avctx->colorspace != h->sps.colorspace)
1142 needs_reinit = 1;
1143 h->avctx->color_primaries = h->sps.color_primaries;
1144 h->avctx->color_trc = h->sps.color_trc;
1145 h->avctx->colorspace = h->sps.colorspace;
1146 }
f51d0f39
LB
1147 }
1148 }
1149
34c5a666 1150 if (h->context_initialized && needs_reinit) {
0181ae9a 1151 h->context_initialized = 0;
51d8725a 1152 if (sl != h->slice_ctx) {
f51d0f39
LB
1153 av_log(h->avctx, AV_LOG_ERROR,
1154 "changing width %d -> %d / height %d -> %d on "
1155 "slice %d\n",
1156 h->width, h->avctx->coded_width,
1157 h->height, h->avctx->coded_height,
51d8725a 1158 h->current_slice + 1);
f51d0f39
LB
1159 return AVERROR_INVALIDDATA;
1160 }
1161
1162 ff_h264_flush_change(h);
1163
1164 if ((ret = get_pixel_format(h)) < 0)
1165 return ret;
1166 h->avctx->pix_fmt = ret;
1167
1168 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
1169 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
1170
8a66fd40 1171 if ((ret = h264_slice_header_init(h)) < 0) {
f51d0f39
LB
1172 av_log(h->avctx, AV_LOG_ERROR,
1173 "h264_slice_header_init() failed\n");
1174 return ret;
1175 }
1176 }
1177 if (!h->context_initialized) {
51d8725a 1178 if (sl != h->slice_ctx) {
f51d0f39
LB
1179 av_log(h->avctx, AV_LOG_ERROR,
1180 "Cannot (re-)initialize context during parallel decoding.\n");
1181 return AVERROR_PATCHWELCOME;
1182 }
1183
1184 if ((ret = get_pixel_format(h)) < 0)
1185 return ret;
1186 h->avctx->pix_fmt = ret;
1187
8a66fd40 1188 if ((ret = h264_slice_header_init(h)) < 0) {
f51d0f39
LB
1189 av_log(h->avctx, AV_LOG_ERROR,
1190 "h264_slice_header_init() failed\n");
1191 return ret;
1192 }
1193 }
1194
51d8725a 1195 if (sl == h->slice_ctx && h->dequant_coeff_pps != pps_id) {
f51d0f39 1196 h->dequant_coeff_pps = pps_id;
061dc203 1197 ff_h264_init_dequant_tables(h);
f51d0f39
LB
1198 }
1199
5ec0bdf2
AK
1200 frame_num = get_bits(&sl->gb, h->sps.log2_max_frame_num);
1201 if (!h->setup_finished)
1202 h->frame_num = frame_num;
f51d0f39 1203
e9b2383b 1204 sl->mb_mbaff = 0;
5ec0bdf2 1205
51d8725a
AK
1206 last_pic_structure = h->picture_structure;
1207 last_pic_droppable = h->droppable;
5ec0bdf2
AK
1208
1209 droppable = h->nal_ref_idc == 0;
f51d0f39 1210 if (h->sps.frame_mbs_only_flag) {
5ec0bdf2 1211 picture_structure = PICT_FRAME;
f51d0f39 1212 } else {
f42485db 1213 field_pic_flag = get_bits1(&sl->gb);
f51d0f39 1214 if (field_pic_flag) {
f42485db 1215 bottom_field_flag = get_bits1(&sl->gb);
5ec0bdf2 1216 picture_structure = PICT_TOP_FIELD + bottom_field_flag;
f51d0f39 1217 } else {
5ec0bdf2
AK
1218 picture_structure = PICT_FRAME;
1219 mb_aff_frame = h->sps.mb_aff;
f51d0f39
LB
1220 }
1221 }
5ec0bdf2
AK
1222 if (!h->setup_finished) {
1223 h->droppable = droppable;
1224 h->picture_structure = picture_structure;
1225 h->mb_aff_frame = mb_aff_frame;
1226 }
bc98e8c0 1227 sl->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
f51d0f39 1228
51d8725a 1229 if (h->current_slice != 0) {
5ec0bdf2
AK
1230 if (last_pic_structure != picture_structure ||
1231 last_pic_droppable != droppable) {
f51d0f39
LB
1232 av_log(h->avctx, AV_LOG_ERROR,
1233 "Changing field mode (%d -> %d) between slices is not allowed\n",
1234 last_pic_structure, h->picture_structure);
f51d0f39 1235 return AVERROR_INVALIDDATA;
51d8725a 1236 } else if (!h->cur_pic_ptr) {
f51d0f39
LB
1237 av_log(h->avctx, AV_LOG_ERROR,
1238 "unset cur_pic_ptr on slice %d\n",
51d8725a 1239 h->current_slice + 1);
f51d0f39
LB
1240 return AVERROR_INVALIDDATA;
1241 }
1242 } else {
1243 /* Shorten frame num gaps so we don't have to allocate reference
1244 * frames just to throw them away */
1245 if (h->frame_num != h->prev_frame_num) {
1246 int unwrap_prev_frame_num = h->prev_frame_num;
1247 int max_frame_num = 1 << h->sps.log2_max_frame_num;
1248
1249 if (unwrap_prev_frame_num > h->frame_num)
1250 unwrap_prev_frame_num -= max_frame_num;
1251
1252 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
1253 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
1254 if (unwrap_prev_frame_num < 0)
1255 unwrap_prev_frame_num += max_frame_num;
1256
1257 h->prev_frame_num = unwrap_prev_frame_num;
1258 }
1259 }
1260
1261 /* See if we have a decoded first field looking for a pair...
1262 * Here, we're using that to see if we should mark previously
1263 * decode frames as "finished".
1264 * We have to do that before the "dummy" in-between frame allocation,
1265 * since that can modify s->current_picture_ptr. */
51d8725a
AK
1266 if (h->first_field) {
1267 assert(h->cur_pic_ptr);
a0f29460 1268 assert(h->cur_pic_ptr->f->buf[0]);
51d8725a 1269 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
f51d0f39
LB
1270
1271 /* figure out if we have a complementary field pair */
1272 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1273 /* Previous field is unmatched. Don't display it, but let it
1274 * remain for reference if marked as such. */
1275 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
51d8725a 1276 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
f51d0f39
LB
1277 last_pic_structure == PICT_TOP_FIELD);
1278 }
1279 } else {
51d8725a 1280 if (h->cur_pic_ptr->frame_num != h->frame_num) {
f51d0f39
LB
1281 /* This and previous field were reference, but had
1282 * different frame_nums. Consider this field first in
1283 * pair. Throw away previous field except for reference
1284 * purposes. */
1285 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
51d8725a 1286 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
f51d0f39
LB
1287 last_pic_structure == PICT_TOP_FIELD);
1288 }
1289 } else {
1290 /* Second field in complementary pair */
1291 if (!((last_pic_structure == PICT_TOP_FIELD &&
1292 h->picture_structure == PICT_BOTTOM_FIELD) ||
1293 (last_pic_structure == PICT_BOTTOM_FIELD &&
1294 h->picture_structure == PICT_TOP_FIELD))) {
1295 av_log(h->avctx, AV_LOG_ERROR,
1296 "Invalid field mode combination %d/%d\n",
1297 last_pic_structure, h->picture_structure);
1298 h->picture_structure = last_pic_structure;
1299 h->droppable = last_pic_droppable;
1300 return AVERROR_INVALIDDATA;
1301 } else if (last_pic_droppable != h->droppable) {
1302 avpriv_request_sample(h->avctx,
1303 "Found reference and non-reference fields in the same frame, which");
1304 h->picture_structure = last_pic_structure;
1305 h->droppable = last_pic_droppable;
1306 return AVERROR_PATCHWELCOME;
1307 }
1308 }
1309 }
1310 }
1311
1312 while (h->frame_num != h->prev_frame_num &&
1313 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
1314 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1315 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1316 h->frame_num, h->prev_frame_num);
f1ccd076 1317 ret = initialize_cur_frame(h);
f51d0f39 1318 if (ret < 0) {
51d8725a 1319 h->first_field = 0;
f51d0f39
LB
1320 return ret;
1321 }
1322
1323 h->prev_frame_num++;
1324 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
1325 h->cur_pic_ptr->frame_num = h->prev_frame_num;
1326 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1327 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1328 ret = ff_generate_sliding_window_mmcos(h, 1);
1329 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1330 return ret;
1331 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1332 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1333 return ret;
1334 /* Error concealment: If a ref is missing, copy the previous ref
1335 * in its place.
1336 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1337 * many assumptions about there being no actual duplicates.
1338 * FIXME: This does not copy padding for out-of-frame motion
1339 * vectors. Given we are concealing a lost frame, this probably
1340 * is not noticeable by comparison, but it should be fixed. */
1341 if (h->short_ref_count) {
a4fbd55d
AC
1342 if (prev &&
1343 h->short_ref[0]->f->width == prev->f->width &&
1344 h->short_ref[0]->f->height == prev->f->height &&
1345 h->short_ref[0]->f->format == prev->f->format) {
a0f29460
AK
1346 av_image_copy(h->short_ref[0]->f->data,
1347 h->short_ref[0]->f->linesize,
1348 (const uint8_t **)prev->f->data,
1349 prev->f->linesize,
a4fbd55d 1350 prev->f->format,
f51d0f39
LB
1351 h->mb_width * 16,
1352 h->mb_height * 16);
1353 h->short_ref[0]->poc = prev->poc + 2;
1354 }
1355 h->short_ref[0]->frame_num = h->prev_frame_num;
1356 }
1357 }
1358
1359 /* See if we have a decoded first field looking for a pair...
1360 * We're using that to see whether to continue decoding in that
1361 * frame, or to allocate a new one. */
51d8725a
AK
1362 if (h->first_field) {
1363 assert(h->cur_pic_ptr);
a0f29460 1364 assert(h->cur_pic_ptr->f->buf[0]);
51d8725a 1365 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
f51d0f39
LB
1366
1367 /* figure out if we have a complementary field pair */
1368 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1369 /* Previous field is unmatched. Don't display it, but let it
1370 * remain for reference if marked as such. */
51d8725a
AK
1371 h->cur_pic_ptr = NULL;
1372 h->first_field = FIELD_PICTURE(h);
f51d0f39 1373 } else {
51d8725a 1374 if (h->cur_pic_ptr->frame_num != h->frame_num) {
f51d0f39
LB
1375 /* This and the previous field had different frame_nums.
1376 * Consider this field first in pair. Throw away previous
1377 * one except for reference purposes. */
51d8725a
AK
1378 h->first_field = 1;
1379 h->cur_pic_ptr = NULL;
f51d0f39
LB
1380 } else {
1381 /* Second field in complementary pair */
51d8725a 1382 h->first_field = 0;
f51d0f39
LB
1383 }
1384 }
1385 } else {
1386 /* Frame or first field in a potentially complementary pair */
51d8725a 1387 h->first_field = FIELD_PICTURE(h);
f51d0f39
LB
1388 }
1389
51d8725a 1390 if (!FIELD_PICTURE(h) || h->first_field) {
f51d0f39 1391 if (h264_frame_start(h) < 0) {
51d8725a 1392 h->first_field = 0;
f51d0f39
LB
1393 return AVERROR_INVALIDDATA;
1394 }
1395 } else {
1396 release_unused_pictures(h, 0);
1397 }
1398 }
f51d0f39 1399
f51d0f39
LB
1400 assert(h->mb_num == h->mb_width * h->mb_height);
1401 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1402 first_mb_in_slice >= h->mb_num) {
1403 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1404 return AVERROR_INVALIDDATA;
1405 }
7bbc254d
AK
1406 sl->resync_mb_x = sl->mb_x = first_mb_in_slice % h->mb_width;
1407 sl->resync_mb_y = sl->mb_y = (first_mb_in_slice / h->mb_width) <<
1408 FIELD_OR_MBAFF_PICTURE(h);
f51d0f39 1409 if (h->picture_structure == PICT_BOTTOM_FIELD)
7bbc254d 1410 sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
d4d9068c 1411 assert(sl->mb_y < h->mb_height);
f51d0f39
LB
1412
1413 if (h->picture_structure == PICT_FRAME) {
1414 h->curr_pic_num = h->frame_num;
1415 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
1416 } else {
1417 h->curr_pic_num = 2 * h->frame_num + 1;
1418 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
1419 }
1420
1421 if (h->nal_unit_type == NAL_IDR_SLICE)
f42485db 1422 get_ue_golomb(&sl->gb); /* idr_pic_id */
f51d0f39
LB
1423
1424 if (h->sps.poc_type == 0) {
5ec0bdf2 1425 int poc_lsb = get_bits(&sl->gb, h->sps.log2_max_poc_lsb);
f51d0f39 1426
5ec0bdf2
AK
1427 if (!h->setup_finished)
1428 h->poc_lsb = poc_lsb;
1429
1430 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) {
1431 int delta_poc_bottom = get_se_golomb(&sl->gb);
1432 if (!h->setup_finished)
1433 h->delta_poc_bottom = delta_poc_bottom;
1434 }
f51d0f39
LB
1435 }
1436
1437 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
5ec0bdf2 1438 int delta_poc = get_se_golomb(&sl->gb);
f51d0f39 1439
5ec0bdf2
AK
1440 if (!h->setup_finished)
1441 h->delta_poc[0] = delta_poc;
1442
1443 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) {
1444 delta_poc = get_se_golomb(&sl->gb);
1445
1446 if (!h->setup_finished)
1447 h->delta_poc[1] = delta_poc;
1448 }
f51d0f39
LB
1449 }
1450
5ec0bdf2
AK
1451 if (!h->setup_finished)
1452 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
f51d0f39
LB
1453
1454 if (h->pps.redundant_pic_cnt_present)
f42485db 1455 sl->redundant_pic_count = get_ue_golomb(&sl->gb);
f51d0f39 1456
56febc99 1457 ret = ff_set_ref_count(h, sl);
f51d0f39
LB
1458 if (ret < 0)
1459 return ret;
f51d0f39 1460
56febc99 1461 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
95eb35f3 1462 ret = ff_h264_decode_ref_pic_list_reordering(h, sl);
f51d0f39 1463 if (ret < 0) {
95eb35f3 1464 sl->ref_count[1] = sl->ref_count[0] = 0;
f51d0f39
LB
1465 return ret;
1466 }
1467 }
1468
56febc99 1469 if ((h->pps.weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
f51d0f39 1470 (h->pps.weighted_bipred_idc == 1 &&
56febc99 1471 sl->slice_type_nos == AV_PICTURE_TYPE_B))
e481458b
AK
1472 ff_h264_pred_weight_table(&sl->gb, &h->sps, sl->ref_count,
1473 sl->slice_type_nos, &sl->pwt);
f51d0f39 1474 else if (h->pps.weighted_bipred_idc == 2 &&
56febc99 1475 sl->slice_type_nos == AV_PICTURE_TYPE_B) {
92c6c2a6 1476 implicit_weight_table(h, sl, -1);
f51d0f39 1477 } else {
e481458b 1478 sl->pwt.use_weight = 0;
f51d0f39 1479 for (i = 0; i < 2; i++) {
e481458b
AK
1480 sl->pwt.luma_weight_flag[i] = 0;
1481 sl->pwt.chroma_weight_flag[i] = 0;
f51d0f39
LB
1482 }
1483 }
1484
1485 // If frame-mt is enabled, only update mmco tables for the first slice
1486 // in a field. Subsequent slices can temporarily clobber h->mmco_index
1487 // or h->mmco, which will cause ref list mix-ups and decoding errors
1488 // further down the line. This may break decoding if the first slice is
1489 // corrupt, thus we only do this if frame-mt is enabled.
1490 if (h->nal_ref_idc) {
51d8725a 1491 ret = ff_h264_decode_ref_pic_marking(h, &sl->gb,
f51d0f39 1492 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
51d8725a 1493 h->current_slice == 0);
f51d0f39
LB
1494 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1495 return AVERROR_INVALIDDATA;
1496 }
1497
1498 if (FRAME_MBAFF(h)) {
92c6c2a6 1499 ff_h264_fill_mbaff_ref_list(h, sl);
f51d0f39 1500
56febc99 1501 if (h->pps.weighted_bipred_idc == 2 && sl->slice_type_nos == AV_PICTURE_TYPE_B) {
92c6c2a6
AK
1502 implicit_weight_table(h, sl, 0);
1503 implicit_weight_table(h, sl, 1);
f51d0f39
LB
1504 }
1505 }
1506
066aafce 1507 if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
ee0d774d 1508 ff_h264_direct_dist_scale_factor(h, sl);
56febc99 1509 ff_h264_direct_ref_list_init(h, sl);
f51d0f39 1510
56febc99 1511 if (sl->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
f42485db 1512 tmp = get_ue_golomb_31(&sl->gb);
f51d0f39
LB
1513 if (tmp > 2) {
1514 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1515 return AVERROR_INVALIDDATA;
1516 }
a9b201ca 1517 sl->cabac_init_idc = tmp;
f51d0f39
LB
1518 }
1519
5c8280c3 1520 sl->last_qscale_diff = 0;
f42485db 1521 tmp = h->pps.init_qp + get_se_golomb(&sl->gb);
f51d0f39
LB
1522 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
1523 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1524 return AVERROR_INVALIDDATA;
1525 }
d231e84b
AK
1526 sl->qscale = tmp;
1527 sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
1528 sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
f51d0f39 1529 // FIXME qscale / qp ... stuff
56febc99 1530 if (sl->slice_type == AV_PICTURE_TYPE_SP)
f42485db 1531 get_bits1(&sl->gb); /* sp_for_switch_flag */
56febc99
AK
1532 if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1533 sl->slice_type == AV_PICTURE_TYPE_SI)
f42485db 1534 get_se_golomb(&sl->gb); /* slice_qs_delta */
f51d0f39 1535
e6c90ce9
AK
1536 sl->deblocking_filter = 1;
1537 sl->slice_alpha_c0_offset = 0;
1538 sl->slice_beta_offset = 0;
f51d0f39 1539 if (h->pps.deblocking_filter_parameters_present) {
f42485db 1540 tmp = get_ue_golomb_31(&sl->gb);
f51d0f39
LB
1541 if (tmp > 2) {
1542 av_log(h->avctx, AV_LOG_ERROR,
1543 "deblocking_filter_idc %u out of range\n", tmp);
1544 return AVERROR_INVALIDDATA;
1545 }
e6c90ce9
AK
1546 sl->deblocking_filter = tmp;
1547 if (sl->deblocking_filter < 2)
1548 sl->deblocking_filter ^= 1; // 1<->0
1549
1550 if (sl->deblocking_filter) {
f42485db
AK
1551 sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1552 sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2;
e6c90ce9
AK
1553 if (sl->slice_alpha_c0_offset > 12 ||
1554 sl->slice_alpha_c0_offset < -12 ||
1555 sl->slice_beta_offset > 12 ||
1556 sl->slice_beta_offset < -12) {
f51d0f39
LB
1557 av_log(h->avctx, AV_LOG_ERROR,
1558 "deblocking filter parameters %d %d out of range\n",
e6c90ce9 1559 sl->slice_alpha_c0_offset, sl->slice_beta_offset);
f51d0f39
LB
1560 return AVERROR_INVALIDDATA;
1561 }
1562 }
1563 }
1564
1565 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1566 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
56febc99 1567 sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
f51d0f39 1568 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
56febc99 1569 sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
f51d0f39
LB
1570 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1571 h->nal_ref_idc == 0))
e6c90ce9 1572 sl->deblocking_filter = 0;
f51d0f39 1573
51d8725a 1574 if (sl->deblocking_filter == 1 && h->max_contexts > 1) {
7c6eb0a1 1575 if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
f51d0f39
LB
1576 /* Cheat slightly for speed:
1577 * Do not bother to deblock across slices. */
e6c90ce9 1578 sl->deblocking_filter = 2;
f51d0f39 1579 } else {
51d8725a
AK
1580 h->max_contexts = 1;
1581 if (!h->single_decode_warning) {
f51d0f39
LB
1582 av_log(h->avctx, AV_LOG_INFO,
1583 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
51d8725a 1584 h->single_decode_warning = 1;
f51d0f39 1585 }
51d8725a 1586 if (sl != h->slice_ctx) {
f51d0f39
LB
1587 av_log(h->avctx, AV_LOG_ERROR,
1588 "Deblocking switched inside frame.\n");
1589 return 1;
1590 }
1591 }
1592 }
06789ad3 1593 sl->qp_thresh = 15 -
e6c90ce9 1594 FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
f51d0f39
LB
1595 FFMAX3(0,
1596 h->pps.chroma_qp_index_offset[0],
1597 h->pps.chroma_qp_index_offset[1]) +
1598 6 * (h->sps.bit_depth_luma - 8);
1599
51d8725a 1600 sl->slice_num = ++h->current_slice;
56febc99 1601 if (sl->slice_num >= MAX_SLICES) {
f51d0f39
LB
1602 av_log(h->avctx, AV_LOG_ERROR,
1603 "Too many slices, increase MAX_SLICES and recompile\n");
1604 }
1605
1606 for (j = 0; j < 2; j++) {
1607 int id_list[16];
95eb35f3 1608 int *ref2frm = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
f51d0f39
LB
1609 for (i = 0; i < 16; i++) {
1610 id_list[i] = 60;
95eb35f3 1611 if (j < sl->list_count && i < sl->ref_count[j] &&
a0f29460 1612 sl->ref_list[j][i].parent->f->buf[0]) {
f51d0f39 1613 int k;
a0f29460 1614 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
f51d0f39 1615 for (k = 0; k < h->short_ref_count; k++)
a0f29460 1616 if (h->short_ref[k]->f->buf[0]->buffer == buf) {
f51d0f39
LB
1617 id_list[i] = k;
1618 break;
1619 }
1620 for (k = 0; k < h->long_ref_count; k++)
a0f29460 1621 if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
f51d0f39
LB
1622 id_list[i] = h->short_ref_count + k;
1623 break;
1624 }
1625 }
1626 }
1627
1628 ref2frm[0] =
1629 ref2frm[1] = -1;
1630 for (i = 0; i < 16; i++)
95eb35f3 1631 ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
f51d0f39
LB
1632 ref2frm[18 + 0] =
1633 ref2frm[18 + 1] = -1;
1634 for (i = 16; i < 48; i++)
1635 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
95eb35f3 1636 (sl->ref_list[j][i].reference & 3);
f51d0f39
LB
1637 }
1638
1639 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1640 av_log(h->avctx, AV_LOG_DEBUG,
1641 "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
56febc99 1642 sl->slice_num,
f51d0f39
LB
1643 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1644 first_mb_in_slice,
56febc99
AK
1645 av_get_picture_type_char(sl->slice_type),
1646 sl->slice_type_fixed ? " fix" : "",
f51d0f39
LB
1647 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
1648 pps_id, h->frame_num,
1649 h->cur_pic_ptr->field_poc[0],
1650 h->cur_pic_ptr->field_poc[1],
95eb35f3 1651 sl->ref_count[0], sl->ref_count[1],
d231e84b 1652 sl->qscale,
e6c90ce9
AK
1653 sl->deblocking_filter,
1654 sl->slice_alpha_c0_offset, sl->slice_beta_offset,
e481458b
AK
1655 sl->pwt.use_weight,
1656 sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
066aafce 1657 sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
f51d0f39
LB
1658 }
1659
1660 return 0;
1661}
1662
56febc99 1663int ff_h264_get_slice_type(const H264SliceContext *sl)
f51d0f39 1664{
56febc99 1665 switch (sl->slice_type) {
f51d0f39
LB
1666 case AV_PICTURE_TYPE_P:
1667 return 0;
1668 case AV_PICTURE_TYPE_B:
1669 return 1;
1670 case AV_PICTURE_TYPE_I:
1671 return 2;
1672 case AV_PICTURE_TYPE_SP:
1673 return 3;
1674 case AV_PICTURE_TYPE_SI:
1675 return 4;
1676 default:
1677 return AVERROR_INVALIDDATA;
1678 }
1679}
1680
92e0b734 1681static av_always_inline void fill_filter_caches_inter(const H264Context *h,
e6287f07 1682 H264SliceContext *sl,
f51d0f39
LB
1683 int mb_type, int top_xy,
1684 int left_xy[LEFT_MBS],
1685 int top_type,
1686 int left_type[LEFT_MBS],
1687 int mb_xy, int list)
1688{
1689 int b_stride = h->b_stride;
e6287f07
AK
1690 int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1691 int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
f51d0f39
LB
1692 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1693 if (USES_LIST(top_type, list)) {
1694 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
1695 const int b8_xy = 4 * top_xy + 2;
e9b2383b 1696 int (*ref2frm)[64] = sl->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
f51d0f39
LB
1697 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1698 ref_cache[0 - 1 * 8] =
1699 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
1700 ref_cache[2 - 1 * 8] =
1701 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
1702 } else {
1703 AV_ZERO128(mv_dst - 1 * 8);
1704 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1705 }
1706
1707 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1708 if (USES_LIST(left_type[LTOP], list)) {
1709 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
1710 const int b8_xy = 4 * left_xy[LTOP] + 1;
e9b2383b 1711 int (*ref2frm)[64] = sl->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
f51d0f39
LB
1712 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1713 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1714 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1715 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1716 ref_cache[-1 + 0] =
1717 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1718 ref_cache[-1 + 16] =
1719 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1720 } else {
1721 AV_ZERO32(mv_dst - 1 + 0);
1722 AV_ZERO32(mv_dst - 1 + 8);
1723 AV_ZERO32(mv_dst - 1 + 16);
1724 AV_ZERO32(mv_dst - 1 + 24);
1725 ref_cache[-1 + 0] =
1726 ref_cache[-1 + 8] =
1727 ref_cache[-1 + 16] =
1728 ref_cache[-1 + 24] = LIST_NOT_USED;
1729 }
1730 }
1731 }
1732
1733 if (!USES_LIST(mb_type, list)) {
1734 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
1735 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1736 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1737 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1738 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1739 return;
1740 }
1741
1742 {
1743 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
e9b2383b 1744 int (*ref2frm)[64] = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
f51d0f39
LB
1745 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
1746 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
1747 AV_WN32A(&ref_cache[0 * 8], ref01);
1748 AV_WN32A(&ref_cache[1 * 8], ref01);
1749 AV_WN32A(&ref_cache[2 * 8], ref23);
1750 AV_WN32A(&ref_cache[3 * 8], ref23);
1751 }
1752
1753 {
d4d9068c 1754 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
f51d0f39
LB
1755 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
1756 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
1757 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
1758 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
1759 }
1760}
1761
1762/**
f51d0f39
LB
1763 * @return non zero if the loop filter can be skipped
1764 */
92e0b734 1765static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
f51d0f39 1766{
0edbe6fa 1767 const int mb_xy = sl->mb_xy;
f51d0f39
LB
1768 int top_xy, left_xy[LEFT_MBS];
1769 int top_type, left_type[LEFT_MBS];
1770 uint8_t *nnz;
1771 uint8_t *nnz_cache;
1772
bc98e8c0 1773 top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
f51d0f39
LB
1774
1775 /* Wow, what a mess, why didn't they simplify the interlacing & intra
1776 * stuff, I can't imagine that these complex rules are worth it. */
1777
1778 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
1779 if (FRAME_MBAFF(h)) {
1780 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
1781 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
d4d9068c 1782 if (sl->mb_y & 1) {
f51d0f39
LB
1783 if (left_mb_field_flag != curr_mb_field_flag)
1784 left_xy[LTOP] -= h->mb_stride;
1785 } else {
1786 if (curr_mb_field_flag)
1787 top_xy += h->mb_stride &
1788 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
1789 if (left_mb_field_flag != curr_mb_field_flag)
1790 left_xy[LBOT] += h->mb_stride;
1791 }
1792 }
1793
8b00f4df
AK
1794 sl->top_mb_xy = top_xy;
1795 sl->left_mb_xy[LTOP] = left_xy[LTOP];
1796 sl->left_mb_xy[LBOT] = left_xy[LBOT];
f51d0f39
LB
1797 {
1798 /* For sufficiently low qp, filtering wouldn't do anything.
1799 * This is a conservative estimate: could also check beta_offset
1800 * and more accurate chroma_qp. */
06789ad3 1801 int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
f51d0f39
LB
1802 int qp = h->cur_pic.qscale_table[mb_xy];
1803 if (qp <= qp_thresh &&
1804 (left_xy[LTOP] < 0 ||
1805 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
1806 (top_xy < 0 ||
1807 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
1808 if (!FRAME_MBAFF(h))
1809 return 1;
1810 if ((left_xy[LTOP] < 0 ||
1811 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
1812 (top_xy < h->mb_stride ||
1813 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
1814 return 1;
1815 }
1816 }
1817
1818 top_type = h->cur_pic.mb_type[top_xy];
1819 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
1820 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
e6c90ce9 1821 if (sl->deblocking_filter == 2) {
56febc99 1822 if (h->slice_table[top_xy] != sl->slice_num)
f51d0f39 1823 top_type = 0;
56febc99 1824 if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
f51d0f39
LB
1825 left_type[LTOP] = left_type[LBOT] = 0;
1826 } else {
1827 if (h->slice_table[top_xy] == 0xFFFF)
1828 top_type = 0;
1829 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
1830 left_type[LTOP] = left_type[LBOT] = 0;
1831 }
8b00f4df
AK
1832 sl->top_type = top_type;
1833 sl->left_type[LTOP] = left_type[LTOP];
1834 sl->left_type[LBOT] = left_type[LBOT];
f51d0f39
LB
1835
1836 if (IS_INTRA(mb_type))
1837 return 0;
1838
e6287f07 1839 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
f51d0f39 1840 top_type, left_type, mb_xy, 0);
95eb35f3 1841 if (sl->list_count == 2)
e6287f07 1842 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
f51d0f39
LB
1843 top_type, left_type, mb_xy, 1);
1844
1845 nnz = h->non_zero_count[mb_xy];
f69574cf 1846 nnz_cache = sl->non_zero_count_cache;
f51d0f39
LB
1847 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
1848 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
1849 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
1850 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
e7226984 1851 sl->cbp = h->cbp_table[mb_xy];
f51d0f39
LB
1852
1853 if (top_type) {
1854 nnz = h->non_zero_count[top_xy];
1855 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
1856 }
1857
1858 if (left_type[LTOP]) {
1859 nnz = h->non_zero_count[left_xy[LTOP]];
1860 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
1861 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
1862 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
1863 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
1864 }
1865
1866 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
1867 * from what the loop filter needs */
1868 if (!CABAC(h) && h->pps.transform_8x8_mode) {
1869 if (IS_8x8DCT(top_type)) {
1870 nnz_cache[4 + 8 * 0] =
1871 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
1872 nnz_cache[6 + 8 * 0] =
1873 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
1874 }
1875 if (IS_8x8DCT(left_type[LTOP])) {
1876 nnz_cache[3 + 8 * 1] =
1877 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
1878 }
1879 if (IS_8x8DCT(left_type[LBOT])) {
1880 nnz_cache[3 + 8 * 3] =
1881 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
1882 }
1883
1884 if (IS_8x8DCT(mb_type)) {
1885 nnz_cache[scan8[0]] =
1886 nnz_cache[scan8[1]] =
1887 nnz_cache[scan8[2]] =
e7226984 1888 nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
f51d0f39
LB
1889
1890 nnz_cache[scan8[0 + 4]] =
1891 nnz_cache[scan8[1 + 4]] =
1892 nnz_cache[scan8[2 + 4]] =
e7226984 1893 nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
f51d0f39
LB
1894
1895 nnz_cache[scan8[0 + 8]] =
1896 nnz_cache[scan8[1 + 8]] =
1897 nnz_cache[scan8[2 + 8]] =
e7226984 1898 nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
f51d0f39
LB
1899
1900 nnz_cache[scan8[0 + 12]] =
1901 nnz_cache[scan8[1 + 12]] =
1902 nnz_cache[scan8[2 + 12]] =
e7226984 1903 nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
f51d0f39
LB
1904 }
1905 }
1906
1907 return 0;
1908}
1909
92e0b734 1910static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
f51d0f39
LB
1911{
1912 uint8_t *dest_y, *dest_cb, *dest_cr;
1913 int linesize, uvlinesize, mb_x, mb_y;
d4d9068c 1914 const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
56febc99 1915 const int old_slice_type = sl->slice_type;
f51d0f39
LB
1916 const int pixel_shift = h->pixel_shift;
1917 const int block_h = 16 >> h->chroma_y_shift;
1918
e6c90ce9 1919 if (sl->deblocking_filter) {
f51d0f39
LB
1920 for (mb_x = start_x; mb_x < end_x; mb_x++)
1921 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
1922 int mb_xy, mb_type;
0edbe6fa 1923 mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
56febc99 1924 sl->slice_num = h->slice_table[mb_xy];
f51d0f39 1925 mb_type = h->cur_pic.mb_type[mb_xy];
95eb35f3 1926 sl->list_count = h->list_counts[mb_xy];
f51d0f39
LB
1927
1928 if (FRAME_MBAFF(h))
e9b2383b 1929 sl->mb_mbaff =
bc98e8c0 1930 sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
f51d0f39 1931
d4d9068c
AK
1932 sl->mb_x = mb_x;
1933 sl->mb_y = mb_y;
a0f29460 1934 dest_y = h->cur_pic.f->data[0] +
c28ed1d7 1935 ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
a0f29460 1936 dest_cb = h->cur_pic.f->data[1] +
f51d0f39 1937 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
c28ed1d7 1938 mb_y * sl->uvlinesize * block_h;
a0f29460 1939 dest_cr = h->cur_pic.f->data[2] +
f51d0f39 1940 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
c28ed1d7 1941 mb_y * sl->uvlinesize * block_h;
f51d0f39
LB
1942 // FIXME simplify above
1943
bc98e8c0 1944 if (MB_FIELD(sl)) {
c28ed1d7
AK
1945 linesize = sl->mb_linesize = sl->linesize * 2;
1946 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
f51d0f39 1947 if (mb_y & 1) { // FIXME move out of this function?
c28ed1d7
AK
1948 dest_y -= sl->linesize * 15;
1949 dest_cb -= sl->uvlinesize * (block_h - 1);
1950 dest_cr -= sl->uvlinesize * (block_h - 1);
f51d0f39
LB
1951 }
1952 } else {
c28ed1d7
AK
1953 linesize = sl->mb_linesize = sl->linesize;
1954 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
f51d0f39 1955 }
d4d9068c 1956 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
f51d0f39 1957 uvlinesize, 0);
06789ad3 1958 if (fill_filter_caches(h, sl, mb_type))
f51d0f39 1959 continue;
d231e84b
AK
1960 sl->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
1961 sl->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
f51d0f39
LB
1962
1963 if (FRAME_MBAFF(h)) {
d231e84b 1964 ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
f51d0f39
LB
1965 linesize, uvlinesize);
1966 } else {
d231e84b 1967 ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
f51d0f39
LB
1968 dest_cr, linesize, uvlinesize);
1969 }
1970 }
1971 }
56febc99 1972 sl->slice_type = old_slice_type;
d4d9068c
AK
1973 sl->mb_x = end_x;
1974 sl->mb_y = end_mb_y - FRAME_MBAFF(h);
d231e84b
AK
1975 sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
1976 sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
f51d0f39
LB
1977}
1978
92e0b734 1979static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
f51d0f39 1980{
d4d9068c 1981 const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
56febc99 1982 int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
f51d0f39 1983 h->cur_pic.mb_type[mb_xy - 1] :
56febc99 1984 (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
f51d0f39 1985 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
e9b2383b 1986 sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
f51d0f39
LB
1987}
1988
1989/**
1990 * Draw edges and report progress for the last MB row.
1991 */
92e0b734 1992static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
f51d0f39 1993{
d4d9068c 1994 int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
f51d0f39
LB
1995 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
1996 int height = 16 << FRAME_MBAFF(h);
1997 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
1998
e6c90ce9 1999 if (sl->deblocking_filter) {
f51d0f39
LB
2000 if ((top + height) >= pic_height)
2001 height += deblock_border;
2002 top -= deblock_border;
2003 }
2004
2005 if (top >= pic_height || (top + height) < 0)
2006 return;
2007
2008 height = FFMIN(height, pic_height - top);
2009 if (top < 0) {
2010 height = top + height;
2011 top = 0;
2012 }
2013
95eb35f3 2014 ff_h264_draw_horiz_band(h, sl, top, height);
f51d0f39
LB
2015
2016 if (h->droppable)
2017 return;
2018
2019 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
2020 h->picture_structure == PICT_BOTTOM_FIELD);
2021}
2022
582683b6 2023static void er_add_slice(H264SliceContext *sl,
95eb35f3 2024 int startx, int starty,
f51d0f39
LB
2025 int endx, int endy, int status)
2026{
2027#if CONFIG_ERROR_RESILIENCE
582683b6 2028 ERContext *er = &sl->er;
f51d0f39 2029
a4d34e21
AK
2030 if (!sl->h264->enable_er)
2031 return;
2032
95eb35f3 2033 er->ref_count = sl->ref_count[0];
f51d0f39
LB
2034 ff_er_add_slice(er, startx, starty, endx, endy, status);
2035#endif
2036}
2037
2038static int decode_slice(struct AVCodecContext *avctx, void *arg)
2039{
92c6c2a6 2040 H264SliceContext *sl = arg;
92e0b734 2041 const H264Context *h = sl->h264;
d4d9068c 2042 int lf_x_start = sl->mb_x;
36d04801
AK
2043 int ret;
2044
a0f29460
AK
2045 sl->linesize = h->cur_pic_ptr->f->linesize[0];
2046 sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
c28ed1d7
AK
2047
2048 ret = alloc_scratch_buffers(sl, sl->linesize);
36d04801
AK
2049 if (ret < 0)
2050 return ret;
f51d0f39 2051
47a0d393 2052 sl->mb_skip_run = -1;
f51d0f39 2053
07c5ca55
AK
2054 sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
2055 avctx->codec_id != AV_CODEC_ID_H264 ||
7c6eb0a1 2056 (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
f51d0f39
LB
2057
2058 if (h->pps.cabac) {
2059 /* realign */
f42485db 2060 align_get_bits(&sl->gb);
f51d0f39
LB
2061
2062 /* init cabac */
30da98ad 2063 ff_init_cabac_decoder(&sl->cabac,
f42485db
AK
2064 sl->gb.buffer + get_bits_count(&sl->gb) / 8,
2065 (get_bits_left(&sl->gb) + 7) / 8);
f51d0f39 2066
d231e84b 2067 ff_h264_init_cabac_states(h, sl);
f51d0f39
LB
2068
2069 for (;;) {
2070 // START_TIMER
e49e0f58
AK
2071 int ret, eos;
2072
2073 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2074 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2075 sl->next_slice_idx);
2076 return AVERROR_INVALIDDATA;
2077 }
2078
2079 ret = ff_h264_decode_mb_cabac(h, sl);
f51d0f39
LB
2080 // STOP_TIMER("decode_mb_cabac")
2081
2082 if (ret >= 0)
92c6c2a6 2083 ff_h264_hl_decode_mb(h, sl);
f51d0f39
LB
2084
2085 // FIXME optimal? or let mb_decode decode 16x32 ?
2086 if (ret >= 0 && FRAME_MBAFF(h)) {
d4d9068c 2087 sl->mb_y++;
f51d0f39 2088
d231e84b 2089 ret = ff_h264_decode_mb_cabac(h, sl);
f51d0f39
LB
2090
2091 if (ret >= 0)
92c6c2a6 2092 ff_h264_hl_decode_mb(h, sl);
d4d9068c 2093 sl->mb_y--;
f51d0f39 2094 }
30da98ad 2095 eos = get_cabac_terminate(&sl->cabac);
f51d0f39
LB
2096
2097 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
30da98ad 2098 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
582683b6 2099 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
d4d9068c
AK
2100 sl->mb_y, ER_MB_END);
2101 if (sl->mb_x >= lf_x_start)
2102 loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
f51d0f39
LB
2103 return 0;
2104 }
30da98ad 2105 if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
f51d0f39
LB
2106 av_log(h->avctx, AV_LOG_ERROR,
2107 "error while decoding MB %d %d, bytestream %td\n",
d4d9068c 2108 sl->mb_x, sl->mb_y,
30da98ad 2109 sl->cabac.bytestream_end - sl->cabac.bytestream);
582683b6 2110 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
d4d9068c 2111 sl->mb_y, ER_MB_ERROR);
f51d0f39
LB
2112 return AVERROR_INVALIDDATA;
2113 }
2114
d4d9068c
AK
2115 if (++sl->mb_x >= h->mb_width) {
2116 loop_filter(h, sl, lf_x_start, sl->mb_x);
2117 sl->mb_x = lf_x_start = 0;
95eb35f3 2118 decode_finish_row(h, sl);
d4d9068c 2119 ++sl->mb_y;
f51d0f39 2120 if (FIELD_OR_MBAFF_PICTURE(h)) {
d4d9068c
AK
2121 ++sl->mb_y;
2122 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
56febc99 2123 predict_field_decoding_flag(h, sl);
f51d0f39
LB
2124 }
2125 }
2126
d4d9068c 2127 if (eos || sl->mb_y >= h->mb_height) {
6a85dfc8 2128 ff_tlog(h->avctx, "slice end %d %d\n",
f42485db 2129 get_bits_count(&sl->gb), sl->gb.size_in_bits);
582683b6 2130 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
d4d9068c
AK
2131 sl->mb_y, ER_MB_END);
2132 if (sl->mb_x > lf_x_start)
2133 loop_filter(h, sl, lf_x_start, sl->mb_x);
f51d0f39
LB
2134 return 0;
2135 }
2136 }
2137 } else {
2138 for (;;) {
e49e0f58
AK
2139 int ret;
2140
2141 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2142 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2143 sl->next_slice_idx);
2144 return AVERROR_INVALIDDATA;
2145 }
2146
2147 ret = ff_h264_decode_mb_cavlc(h, sl);
f51d0f39
LB
2148
2149 if (ret >= 0)
92c6c2a6 2150 ff_h264_hl_decode_mb(h, sl);
f51d0f39
LB
2151
2152 // FIXME optimal? or let mb_decode decode 16x32 ?
2153 if (ret >= 0 && FRAME_MBAFF(h)) {
d4d9068c 2154 sl->mb_y++;
d231e84b 2155 ret = ff_h264_decode_mb_cavlc(h, sl);
f51d0f39
LB
2156
2157 if (ret >= 0)
92c6c2a6 2158 ff_h264_hl_decode_mb(h, sl);
d4d9068c 2159 sl->mb_y--;
f51d0f39
LB
2160 }
2161
2162 if (ret < 0) {
2163 av_log(h->avctx, AV_LOG_ERROR,
d4d9068c 2164 "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
582683b6 2165 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
d4d9068c 2166 sl->mb_y, ER_MB_ERROR);
f51d0f39
LB
2167 return ret;
2168 }
2169
d4d9068c
AK
2170 if (++sl->mb_x >= h->mb_width) {
2171 loop_filter(h, sl, lf_x_start, sl->mb_x);
2172 sl->mb_x = lf_x_start = 0;
95eb35f3 2173 decode_finish_row(h, sl);
d4d9068c 2174 ++sl->mb_y;
f51d0f39 2175 if (FIELD_OR_MBAFF_PICTURE(h)) {
d4d9068c
AK
2176 ++sl->mb_y;
2177 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
56febc99 2178 predict_field_decoding_flag(h, sl);
f51d0f39 2179 }
d4d9068c 2180 if (sl->mb_y >= h->mb_height) {
6a85dfc8 2181 ff_tlog(h->avctx, "slice end %d %d\n",
f42485db 2182 get_bits_count(&sl->gb), sl->gb.size_in_bits);
f51d0f39 2183
f42485db 2184 if (get_bits_left(&sl->gb) == 0) {
582683b6 2185 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
d4d9068c 2186 sl->mb_x - 1, sl->mb_y, ER_MB_END);
f51d0f39
LB
2187
2188 return 0;
2189 } else {
582683b6 2190 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
d4d9068c 2191 sl->mb_x - 1, sl->mb_y, ER_MB_END);
f51d0f39
LB
2192
2193 return AVERROR_INVALIDDATA;
2194 }
2195 }
2196 }
2197
f42485db 2198 if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
6a85dfc8 2199 ff_tlog(h->avctx, "slice end %d %d\n",
f42485db 2200 get_bits_count(&sl->gb), sl->gb.size_in_bits);
f51d0f39 2201
f42485db 2202 if (get_bits_left(&sl->gb) == 0) {
582683b6 2203 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
d4d9068c
AK
2204 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2205 if (sl->mb_x > lf_x_start)
2206 loop_filter(h, sl, lf_x_start, sl->mb_x);
f51d0f39
LB
2207
2208 return 0;
2209 } else {
582683b6 2210 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
d4d9068c 2211 sl->mb_y, ER_MB_ERROR);
f51d0f39
LB
2212
2213 return AVERROR_INVALIDDATA;
2214 }
2215 }
2216 }
2217 }
2218}
2219
2220/**
2221 * Call decode_slice() for each context.
2222 *
2223 * @param h h264 master context
2224 * @param context_count number of contexts to execute
2225 */
2226int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count)
2227{
2228 AVCodecContext *const avctx = h->avctx;
d4d9068c 2229 H264SliceContext *sl;
e49e0f58 2230 int i, j;
f51d0f39 2231
f51d0f39
LB
2232 if (h->avctx->hwaccel)
2233 return 0;
2234 if (context_count == 1) {
e49e0f58
AK
2235 int ret;
2236
2237 h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2238
2239 ret = decode_slice(avctx, &h->slice_ctx[0]);
d4d9068c
AK
2240 h->mb_y = h->slice_ctx[0].mb_y;
2241 return ret;
f51d0f39 2242 } else {
e49e0f58
AK
2243 for (i = 0; i < context_count; i++) {
2244 int next_slice_idx = h->mb_width * h->mb_height;
2245 int slice_idx;
2246
582683b6
AK
2247 sl = &h->slice_ctx[i];
2248 sl->er.error_count = 0;
e49e0f58
AK
2249
2250 /* make sure none of those slices overlap */
2251 slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2252 for (j = 0; j < context_count; j++) {
2253 H264SliceContext *sl2 = &h->slice_ctx[j];
2254 int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2255
2256 if (i == j || slice_idx2 < slice_idx)
2257 continue;
2258 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2259 }
2260 sl->next_slice_idx = next_slice_idx;
f51d0f39
LB
2261 }
2262
92c6c2a6
AK
2263 avctx->execute(avctx, decode_slice, h->slice_ctx,
2264 NULL, context_count, sizeof(h->slice_ctx[0]));
f51d0f39
LB
2265
2266 /* pull back stuff from slices to master context */
d4d9068c
AK
2267 sl = &h->slice_ctx[context_count - 1];
2268 h->mb_y = sl->mb_y;
f51d0f39 2269 for (i = 1; i < context_count; i++)
582683b6 2270 h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
f51d0f39
LB
2271 }
2272
2273 return 0;
2274}