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