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