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