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