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