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