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