]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264_slice.c
lavc: Add spherical packet side data API
[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     if (width <= 0 || height <= 0) {
807         av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
808                width, height);
809         if (h->avctx->err_recognition & AV_EF_EXPLODE)
810             return AVERROR_INVALIDDATA;
811
812         av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
813         sps->crop_bottom =
814         sps->crop_top    =
815         sps->crop_right  =
816         sps->crop_left   =
817         sps->crop        = 0;
818
819         width  = h->width;
820         height = h->height;
821     }
822
823     h->avctx->coded_width  = h->width;
824     h->avctx->coded_height = h->height;
825     h->avctx->width        = width;
826     h->avctx->height       = height;
827
828     return 0;
829 }
830
831 static int h264_slice_header_init(H264Context *h)
832 {
833     const SPS *sps = h->ps.sps;
834     int i, ret;
835
836     ff_set_sar(h->avctx, sps->sar);
837     av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
838                                      &h->chroma_x_shift, &h->chroma_y_shift);
839
840     if (sps->timing_info_present_flag) {
841         int64_t den = sps->time_scale;
842         if (h->sei.unregistered.x264_build < 44U)
843             den *= 2;
844         av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
845                   sps->num_units_in_tick, den, 1 << 30);
846     }
847
848     ff_h264_free_tables(h);
849
850     h->first_field           = 0;
851     h->prev_interlaced_frame = 1;
852
853     init_scan_tables(h);
854     ret = ff_h264_alloc_tables(h);
855     if (ret < 0) {
856         av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
857         return ret;
858     }
859
860     if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 10) {
861         av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
862                sps->bit_depth_luma);
863         return AVERROR_INVALIDDATA;
864     }
865
866     h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
867     h->pixel_shift                = sps->bit_depth_luma > 8;
868     h->chroma_format_idc          = sps->chroma_format_idc;
869     h->bit_depth_luma             = sps->bit_depth_luma;
870
871     ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
872                     sps->chroma_format_idc);
873     ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
874     ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
875     ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
876                       sps->chroma_format_idc);
877     ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
878
879     if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
880         ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
881         if (ret < 0) {
882             av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
883             return ret;
884         }
885     } else {
886         for (i = 0; i < h->nb_slice_ctx; i++) {
887             H264SliceContext *sl = &h->slice_ctx[i];
888
889             sl->h264               = h;
890             sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
891             sl->mvd_table[0]       = h->mvd_table[0]       + i * 8 * 2 * h->mb_stride;
892             sl->mvd_table[1]       = h->mvd_table[1]       + i * 8 * 2 * h->mb_stride;
893
894             if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
895                 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
896                 return ret;
897             }
898         }
899     }
900
901     h->context_initialized = 1;
902
903     return 0;
904 }
905
906 static int h264_init_ps(H264Context *h, const H264SliceContext *sl)
907 {
908     const SPS *sps;
909     int needs_reinit = 0, ret;
910
911     h->ps.pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
912     if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
913         h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;
914
915         if (h->bit_depth_luma    != h->ps.sps->bit_depth_luma ||
916             h->chroma_format_idc != h->ps.sps->chroma_format_idc)
917             needs_reinit         = 1;
918     }
919     sps = h->ps.sps;
920
921     h->avctx->profile = ff_h264_get_profile(sps);
922     h->avctx->level   = sps->level_idc;
923     h->avctx->refs    = sps->ref_frame_count;
924
925     if (h->mb_width  != sps->mb_width ||
926         h->mb_height != sps->mb_height)
927         needs_reinit = 1;
928
929     h->mb_width  = sps->mb_width;
930     h->mb_height = sps->mb_height;
931     h->mb_num    = h->mb_width * h->mb_height;
932     h->mb_stride = h->mb_width + 1;
933
934     h->b_stride = h->mb_width * 4;
935
936     h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
937
938     h->width  = 16 * h->mb_width;
939     h->height = 16 * h->mb_height;
940
941     ret = init_dimensions(h);
942     if (ret < 0)
943         return ret;
944
945     if (sps->video_signal_type_present_flag) {
946         h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG
947             : AVCOL_RANGE_MPEG;
948         if (sps->colour_description_present_flag) {
949             if (h->avctx->colorspace != sps->colorspace)
950                 needs_reinit = 1;
951             h->avctx->color_primaries = sps->color_primaries;
952             h->avctx->color_trc       = sps->color_trc;
953             h->avctx->colorspace      = sps->colorspace;
954         }
955     }
956
957     if (!h->context_initialized || needs_reinit) {
958         h->context_initialized = 0;
959         if (sl != h->slice_ctx) {
960             av_log(h->avctx, AV_LOG_ERROR,
961                    "changing width %d -> %d / height %d -> %d on "
962                    "slice %d\n",
963                    h->width, h->avctx->coded_width,
964                    h->height, h->avctx->coded_height,
965                    h->current_slice + 1);
966             return AVERROR_INVALIDDATA;
967         }
968
969         ff_h264_flush_change(h);
970
971         if ((ret = get_pixel_format(h)) < 0)
972             return ret;
973         h->avctx->pix_fmt = ret;
974
975         av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
976                "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
977
978         if ((ret = h264_slice_header_init(h)) < 0) {
979             av_log(h->avctx, AV_LOG_ERROR,
980                    "h264_slice_header_init() failed\n");
981             return ret;
982         }
983     }
984
985     return 0;
986 }
987
988 static int h264_export_frame_props(H264Context *h)
989 {
990     const SPS *sps = h->ps.sps;
991     H264Picture *cur = h->cur_pic_ptr;
992
993     cur->f->interlaced_frame = 0;
994     cur->f->repeat_pict      = 0;
995
996     /* Signal interlacing information externally. */
997     /* Prioritize picture timing SEI information over used
998      * decoding process if it exists. */
999
1000     if (sps->pic_struct_present_flag) {
1001         H264SEIPictureTiming *pt = &h->sei.picture_timing;
1002         switch (pt->pic_struct) {
1003         case SEI_PIC_STRUCT_FRAME:
1004             break;
1005         case SEI_PIC_STRUCT_TOP_FIELD:
1006         case SEI_PIC_STRUCT_BOTTOM_FIELD:
1007             cur->f->interlaced_frame = 1;
1008             break;
1009         case SEI_PIC_STRUCT_TOP_BOTTOM:
1010         case SEI_PIC_STRUCT_BOTTOM_TOP:
1011             if (FIELD_OR_MBAFF_PICTURE(h))
1012                 cur->f->interlaced_frame = 1;
1013             else
1014                 // try to flag soft telecine progressive
1015                 cur->f->interlaced_frame = h->prev_interlaced_frame;
1016             break;
1017         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1018         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1019             /* Signal the possibility of telecined film externally
1020              * (pic_struct 5,6). From these hints, let the applications
1021              * decide if they apply deinterlacing. */
1022             cur->f->repeat_pict = 1;
1023             break;
1024         case SEI_PIC_STRUCT_FRAME_DOUBLING:
1025             cur->f->repeat_pict = 2;
1026             break;
1027         case SEI_PIC_STRUCT_FRAME_TRIPLING:
1028             cur->f->repeat_pict = 4;
1029             break;
1030         }
1031
1032         if ((pt->ct_type & 3) &&
1033             pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1034             cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
1035     } else {
1036         /* Derive interlacing flag from used decoding process. */
1037         cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
1038     }
1039     h->prev_interlaced_frame = cur->f->interlaced_frame;
1040
1041     if (cur->field_poc[0] != cur->field_poc[1]) {
1042         /* Derive top_field_first from field pocs. */
1043         cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1044     } else {
1045         if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
1046             /* Use picture timing SEI information. Even if it is a
1047              * information of a past frame, better than nothing. */
1048             if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1049                 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1050                 cur->f->top_field_first = 1;
1051             else
1052                 cur->f->top_field_first = 0;
1053         } else {
1054             /* Most likely progressive */
1055             cur->f->top_field_first = 0;
1056         }
1057     }
1058
1059     if (h->sei.frame_packing.present &&
1060         h->sei.frame_packing.arrangement_type >= 0 &&
1061         h->sei.frame_packing.arrangement_type <= 6 &&
1062         h->sei.frame_packing.content_interpretation_type > 0 &&
1063         h->sei.frame_packing.content_interpretation_type < 3) {
1064         H264SEIFramePacking *fp = &h->sei.frame_packing;
1065         AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
1066         if (!stereo)
1067             return AVERROR(ENOMEM);
1068
1069         switch (fp->arrangement_type) {
1070         case 0:
1071             stereo->type = AV_STEREO3D_CHECKERBOARD;
1072             break;
1073         case 1:
1074             stereo->type = AV_STEREO3D_COLUMNS;
1075             break;
1076         case 2:
1077             stereo->type = AV_STEREO3D_LINES;
1078             break;
1079         case 3:
1080             if (fp->quincunx_subsampling)
1081                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
1082             else
1083                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
1084             break;
1085         case 4:
1086             stereo->type = AV_STEREO3D_TOPBOTTOM;
1087             break;
1088         case 5:
1089             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
1090             break;
1091         case 6:
1092             stereo->type = AV_STEREO3D_2D;
1093             break;
1094         }
1095
1096         if (fp->content_interpretation_type == 2)
1097             stereo->flags = AV_STEREO3D_FLAG_INVERT;
1098     }
1099
1100     if (h->sei.display_orientation.present &&
1101         (h->sei.display_orientation.anticlockwise_rotation ||
1102          h->sei.display_orientation.hflip ||
1103          h->sei.display_orientation.vflip)) {
1104         H264SEIDisplayOrientation *o = &h->sei.display_orientation;
1105         double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
1106         AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
1107                                                            AV_FRAME_DATA_DISPLAYMATRIX,
1108                                                            sizeof(int32_t) * 9);
1109         if (!rotation)
1110             return AVERROR(ENOMEM);
1111
1112         av_display_rotation_set((int32_t *)rotation->data, angle);
1113         av_display_matrix_flip((int32_t *)rotation->data,
1114                                o->hflip, o->vflip);
1115     }
1116
1117     if (h->sei.afd.present) {
1118         AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
1119                                                      sizeof(uint8_t));
1120         if (!sd)
1121             return AVERROR(ENOMEM);
1122
1123         *sd->data = h->sei.afd.active_format_description;
1124         h->sei.afd.present = 0;
1125     }
1126
1127     if (h->sei.a53_caption.a53_caption) {
1128         H264SEIA53Caption *a53 = &h->sei.a53_caption;
1129         AVFrameSideData *sd = av_frame_new_side_data(cur->f,
1130                                                      AV_FRAME_DATA_A53_CC,
1131                                                      a53->a53_caption_size);
1132         if (!sd)
1133             return AVERROR(ENOMEM);
1134
1135         memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
1136         av_freep(&a53->a53_caption);
1137         a53->a53_caption_size = 0;
1138     }
1139
1140     return 0;
1141 }
1142
1143 static int h264_select_output_frame(H264Context *h)
1144 {
1145     const SPS *sps = h->ps.sps;
1146     H264Picture *out = h->cur_pic_ptr;
1147     H264Picture *cur = h->cur_pic_ptr;
1148     int i, pics, out_of_order, out_idx;
1149     int invalid = 0, cnt = 0;
1150     int ret;
1151
1152     if (sps->bitstream_restriction_flag ||
1153         h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
1154         h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
1155     }
1156
1157     pics = 0;
1158     while (h->delayed_pic[pics])
1159         pics++;
1160
1161     assert(pics <= MAX_DELAYED_PIC_COUNT);
1162
1163     h->delayed_pic[pics++] = cur;
1164     if (cur->reference == 0)
1165         cur->reference = DELAYED_PIC_REF;
1166
1167     /* Frame reordering. This code takes pictures from coding order and sorts
1168      * them by their incremental POC value into display order. It supports POC
1169      * gaps, MMCO reset codes and random resets.
1170      * A "display group" can start either with a IDR frame (f.key_frame = 1),
1171      * and/or can be closed down with a MMCO reset code. In sequences where
1172      * there is no delay, we can't detect that (since the frame was already
1173      * output to the user), so we also set h->mmco_reset to detect the MMCO
1174      * reset code.
1175      * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1176      * we increase the delay between input and output. All frames affected by
1177      * the lag (e.g. those that should have been output before another frame
1178      * that we already returned to the user) will be dropped. This is a bug
1179      * that we will fix later. */
1180     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1181         cnt     += out->poc < h->last_pocs[i];
1182         invalid += out->poc == INT_MIN;
1183     }
1184     if (!h->mmco_reset && !cur->f->key_frame &&
1185         cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1186         h->mmco_reset = 2;
1187         if (pics > 1)
1188             h->delayed_pic[pics - 2]->mmco_reset = 2;
1189     }
1190     if (h->mmco_reset || cur->f->key_frame) {
1191         for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1192             h->last_pocs[i] = INT_MIN;
1193         cnt     = 0;
1194         invalid = MAX_DELAYED_PIC_COUNT;
1195     }
1196     out     = h->delayed_pic[0];
1197     out_idx = 0;
1198     for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1199                 h->delayed_pic[i] &&
1200                 !h->delayed_pic[i - 1]->mmco_reset &&
1201                 !h->delayed_pic[i]->f->key_frame;
1202          i++)
1203         if (h->delayed_pic[i]->poc < out->poc) {
1204             out     = h->delayed_pic[i];
1205             out_idx = i;
1206         }
1207     if (h->avctx->has_b_frames == 0 &&
1208         (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
1209         h->next_outputed_poc = INT_MIN;
1210     out_of_order = !out->f->key_frame && !h->mmco_reset &&
1211                    (out->poc < h->next_outputed_poc);
1212
1213     if (sps->bitstream_restriction_flag &&
1214         h->avctx->has_b_frames >= sps->num_reorder_frames) {
1215     } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1216                h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1217         if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1218             h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1219         }
1220     } else if (!h->avctx->has_b_frames &&
1221                ((h->next_outputed_poc != INT_MIN &&
1222                  out->poc > h->next_outputed_poc + 2) ||
1223                 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
1224         h->avctx->has_b_frames++;
1225     }
1226
1227     if (pics > h->avctx->has_b_frames) {
1228         out->reference &= ~DELAYED_PIC_REF;
1229         for (i = out_idx; h->delayed_pic[i]; i++)
1230             h->delayed_pic[i] = h->delayed_pic[i + 1];
1231     }
1232     memmove(h->last_pocs, &h->last_pocs[1],
1233             sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1234     h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1235     if (!out_of_order && pics > h->avctx->has_b_frames) {
1236         av_frame_unref(h->output_frame);
1237         ret = av_frame_ref(h->output_frame, out->f);
1238         if (ret < 0)
1239             return ret;
1240
1241         if (out->recovered) {
1242             // We have reached an recovery point and all frames after it in
1243             // display order are "recovered".
1244             h->frame_recovered |= FRAME_RECOVERED_SEI;
1245         }
1246         out->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1247
1248         if (!out->recovered) {
1249             if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT))
1250                 av_frame_unref(h->output_frame);
1251             else
1252                 h->output_frame->flags |= AV_FRAME_FLAG_CORRUPT;
1253         }
1254
1255         if (out->mmco_reset) {
1256             if (out_idx > 0) {
1257                 h->next_outputed_poc                    = out->poc;
1258                 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1259             } else {
1260                 h->next_outputed_poc = INT_MIN;
1261             }
1262         } else {
1263             if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
1264                 h->next_outputed_poc = INT_MIN;
1265             } else {
1266                 h->next_outputed_poc = out->poc;
1267             }
1268         }
1269         h->mmco_reset = 0;
1270     } else {
1271         av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
1272     }
1273
1274     return 0;
1275 }
1276
1277 /* This function is called right after decoding the slice header for a first
1278  * slice in a field (or a frame). It decides whether we are decoding a new frame
1279  * or a second field in a pair and does the necessary setup.
1280  */
1281 static int h264_field_start(H264Context *h, const H264SliceContext *sl,
1282                             const H2645NAL *nal)
1283 {
1284     const SPS *sps;
1285
1286     int last_pic_structure, last_pic_droppable, ret;
1287
1288     ret = h264_init_ps(h, sl);
1289     if (ret < 0)
1290         return ret;
1291
1292     sps = h->ps.sps;
1293
1294     last_pic_droppable   = h->droppable;
1295     last_pic_structure   = h->picture_structure;
1296     h->droppable         = (nal->ref_idc == 0);
1297     h->picture_structure = sl->picture_structure;
1298
1299     h->poc.frame_num        = sl->frame_num;
1300     h->poc.poc_lsb          = sl->poc_lsb;
1301     h->poc.delta_poc_bottom = sl->delta_poc_bottom;
1302     h->poc.delta_poc[0]     = sl->delta_poc[0];
1303     h->poc.delta_poc[1]     = sl->delta_poc[1];
1304
1305     /* Shorten frame num gaps so we don't have to allocate reference
1306      * frames just to throw them away */
1307     if (h->poc.frame_num != h->poc.prev_frame_num) {
1308         int unwrap_prev_frame_num = h->poc.prev_frame_num;
1309         int max_frame_num         = 1 << sps->log2_max_frame_num;
1310
1311         if (unwrap_prev_frame_num > h->poc.frame_num)
1312             unwrap_prev_frame_num -= max_frame_num;
1313
1314         if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1315             unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1316             if (unwrap_prev_frame_num < 0)
1317                 unwrap_prev_frame_num += max_frame_num;
1318
1319             h->poc.prev_frame_num = unwrap_prev_frame_num;
1320         }
1321     }
1322
1323     /* See if we have a decoded first field looking for a pair...
1324      * Here, we're using that to see if we should mark previously
1325      * decode frames as "finished".
1326      * We have to do that before the "dummy" in-between frame allocation,
1327      * since that can modify s->current_picture_ptr. */
1328     if (h->first_field) {
1329         assert(h->cur_pic_ptr);
1330         assert(h->cur_pic_ptr->f->buf[0]);
1331         assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1332
1333         /* figure out if we have a complementary field pair */
1334         if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1335             /* Previous field is unmatched. Don't display it, but let it
1336              * remain for reference if marked as such. */
1337             if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1338                 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1339                                           last_pic_structure == PICT_TOP_FIELD);
1340             }
1341         } else {
1342             if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1343                 /* This and previous field were reference, but had
1344                  * different frame_nums. Consider this field first in
1345                  * pair. Throw away previous field except for reference
1346                  * purposes. */
1347                 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1348                     ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1349                                               last_pic_structure == PICT_TOP_FIELD);
1350                 }
1351             } else {
1352                 /* Second field in complementary pair */
1353                 if (!((last_pic_structure   == PICT_TOP_FIELD &&
1354                        h->picture_structure == PICT_BOTTOM_FIELD) ||
1355                       (last_pic_structure   == PICT_BOTTOM_FIELD &&
1356                        h->picture_structure == PICT_TOP_FIELD))) {
1357                     av_log(h->avctx, AV_LOG_ERROR,
1358                            "Invalid field mode combination %d/%d\n",
1359                            last_pic_structure, h->picture_structure);
1360                     h->picture_structure = last_pic_structure;
1361                     h->droppable         = last_pic_droppable;
1362                     return AVERROR_INVALIDDATA;
1363                 } else if (last_pic_droppable != h->droppable) {
1364                     avpriv_request_sample(h->avctx,
1365                                           "Found reference and non-reference fields in the same frame, which");
1366                     h->picture_structure = last_pic_structure;
1367                     h->droppable         = last_pic_droppable;
1368                     return AVERROR_PATCHWELCOME;
1369                 }
1370             }
1371         }
1372     }
1373
1374     while (h->poc.frame_num != h->poc.prev_frame_num &&
1375            h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1376         H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1377         av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1378                h->poc.frame_num, h->poc.prev_frame_num);
1379         ret = initialize_cur_frame(h);
1380         if (ret < 0) {
1381             h->first_field = 0;
1382             return ret;
1383         }
1384
1385         h->poc.prev_frame_num++;
1386         h->poc.prev_frame_num        %= 1 << sps->log2_max_frame_num;
1387         h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1388         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1389         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1390
1391         h->explicit_ref_marking = 0;
1392         ret = ff_h264_execute_ref_pic_marking(h);
1393         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1394             return ret;
1395         /* Error concealment: If a ref is missing, copy the previous ref
1396          * in its place.
1397          * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1398          * many assumptions about there being no actual duplicates.
1399          * FIXME: This does not copy padding for out-of-frame motion
1400          * vectors.  Given we are concealing a lost frame, this probably
1401          * is not noticeable by comparison, but it should be fixed. */
1402         if (h->short_ref_count) {
1403             if (prev &&
1404                 h->short_ref[0]->f->width == prev->f->width &&
1405                 h->short_ref[0]->f->height == prev->f->height &&
1406                 h->short_ref[0]->f->format == prev->f->format) {
1407                 av_image_copy(h->short_ref[0]->f->data,
1408                               h->short_ref[0]->f->linesize,
1409                               (const uint8_t **)prev->f->data,
1410                               prev->f->linesize,
1411                               prev->f->format,
1412                               h->mb_width  * 16,
1413                               h->mb_height * 16);
1414                 h->short_ref[0]->poc = prev->poc + 2;
1415             }
1416             h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1417         }
1418     }
1419
1420     /* See if we have a decoded first field looking for a pair...
1421      * We're using that to see whether to continue decoding in that
1422      * frame, or to allocate a new one. */
1423     if (h->first_field) {
1424         assert(h->cur_pic_ptr);
1425         assert(h->cur_pic_ptr->f->buf[0]);
1426         assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1427
1428         /* figure out if we have a complementary field pair */
1429         if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1430             /* Previous field is unmatched. Don't display it, but let it
1431              * remain for reference if marked as such. */
1432             h->cur_pic_ptr = NULL;
1433             h->first_field = FIELD_PICTURE(h);
1434         } else {
1435             if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1436                 /* This and the previous field had different frame_nums.
1437                  * Consider this field first in pair. Throw away previous
1438                  * one except for reference purposes. */
1439                 h->first_field = 1;
1440                 h->cur_pic_ptr = NULL;
1441             } else {
1442                 /* Second field in complementary pair */
1443                 h->first_field = 0;
1444             }
1445         }
1446     } else {
1447         /* Frame or first field in a potentially complementary pair */
1448         h->first_field = FIELD_PICTURE(h);
1449     }
1450
1451     if (!FIELD_PICTURE(h) || h->first_field) {
1452         if (h264_frame_start(h) < 0) {
1453             h->first_field = 0;
1454             return AVERROR_INVALIDDATA;
1455         }
1456     } else {
1457         release_unused_pictures(h, 0);
1458     }
1459
1460     ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1461                      h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
1462
1463     memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
1464     h->nb_mmco = sl->nb_mmco;
1465     h->explicit_ref_marking = sl->explicit_ref_marking;
1466
1467     h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
1468
1469     if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1470         h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
1471                             ((1 << h->ps.sps->log2_max_frame_num) - 1);
1472     }
1473
1474     h->cur_pic_ptr->f->key_frame |= (nal->type == H264_NAL_IDR_SLICE) ||
1475                                     (h->sei.recovery_point.recovery_frame_cnt >= 0);
1476
1477     if (nal->type == H264_NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
1478         h->recovery_frame         = -1;
1479         h->cur_pic_ptr->recovered = 1;
1480     }
1481     // If we have an IDR, all frames after it in decoded order are
1482     // "recovered".
1483     if (nal->type == H264_NAL_IDR_SLICE)
1484         h->frame_recovered |= FRAME_RECOVERED_IDR;
1485     h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1486
1487     /* Set the frame properties/side data. Only done for the second field in
1488      * field coded frames, since some SEI information is present for each field
1489      * and is merged by the SEI parsing code. */
1490     if (!FIELD_PICTURE(h) || !h->first_field) {
1491         ret = h264_export_frame_props(h);
1492         if (ret < 0)
1493             return ret;
1494
1495         ret = h264_select_output_frame(h);
1496         if (ret < 0)
1497             return ret;
1498     }
1499
1500     if (h->avctx->hwaccel) {
1501         ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0);
1502         if (ret < 0)
1503             return ret;
1504     }
1505
1506     return 0;
1507 }
1508
1509 static int h264_slice_header_parse(H264SliceContext *sl, const H2645NAL *nal,
1510                                    const H264ParamSets *ps, AVCodecContext *avctx)
1511 {
1512     const SPS *sps;
1513     const PPS *pps;
1514     int ret;
1515     unsigned int slice_type, tmp, i;
1516     int field_pic_flag, bottom_field_flag, picture_structure;
1517
1518     sl->first_mb_addr = get_ue_golomb(&sl->gb);
1519
1520     slice_type = get_ue_golomb_31(&sl->gb);
1521     if (slice_type > 9) {
1522         av_log(avctx, AV_LOG_ERROR,
1523                "slice type %d too large at %d\n",
1524                slice_type, sl->first_mb_addr);
1525         return AVERROR_INVALIDDATA;
1526     }
1527     if (slice_type > 4) {
1528         slice_type -= 5;
1529         sl->slice_type_fixed = 1;
1530     } else
1531         sl->slice_type_fixed = 0;
1532
1533     slice_type         = ff_h264_golomb_to_pict_type[slice_type];
1534     sl->slice_type     = slice_type;
1535     sl->slice_type_nos = slice_type & 3;
1536
1537     if (nal->type  == H264_NAL_IDR_SLICE &&
1538         sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1539         av_log(avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1540         return AVERROR_INVALIDDATA;
1541     }
1542
1543     sl->pps_id = get_ue_golomb(&sl->gb);
1544     if (sl->pps_id >= MAX_PPS_COUNT) {
1545         av_log(avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
1546         return AVERROR_INVALIDDATA;
1547     }
1548     if (!ps->pps_list[sl->pps_id]) {
1549         av_log(avctx, AV_LOG_ERROR,
1550                "non-existing PPS %u referenced\n",
1551                sl->pps_id);
1552         return AVERROR_INVALIDDATA;
1553     }
1554     pps = (const PPS*)ps->pps_list[sl->pps_id]->data;
1555
1556     if (!ps->sps_list[pps->sps_id]) {
1557         av_log(avctx, AV_LOG_ERROR,
1558                "non-existing SPS %u referenced\n", pps->sps_id);
1559         return AVERROR_INVALIDDATA;
1560     }
1561     sps = (const SPS*)ps->sps_list[pps->sps_id]->data;
1562
1563     sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1564
1565     sl->mb_mbaff       = 0;
1566
1567     if (sps->frame_mbs_only_flag) {
1568         picture_structure = PICT_FRAME;
1569     } else {
1570         field_pic_flag = get_bits1(&sl->gb);
1571         if (field_pic_flag) {
1572             bottom_field_flag = get_bits1(&sl->gb);
1573             picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1574         } else {
1575             picture_structure = PICT_FRAME;
1576         }
1577     }
1578     sl->picture_structure      = picture_structure;
1579     sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
1580
1581     if (picture_structure == PICT_FRAME) {
1582         sl->curr_pic_num = sl->frame_num;
1583         sl->max_pic_num  = 1 << sps->log2_max_frame_num;
1584     } else {
1585         sl->curr_pic_num = 2 * sl->frame_num + 1;
1586         sl->max_pic_num  = 1 << (sps->log2_max_frame_num + 1);
1587     }
1588
1589     if (nal->type == H264_NAL_IDR_SLICE)
1590         get_ue_golomb(&sl->gb); /* idr_pic_id */
1591
1592     if (sps->poc_type == 0) {
1593         sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1594
1595         if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1596             sl->delta_poc_bottom = get_se_golomb(&sl->gb);
1597     }
1598
1599     if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1600         sl->delta_poc[0] = get_se_golomb(&sl->gb);
1601
1602         if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1603             sl->delta_poc[1] = get_se_golomb(&sl->gb);
1604     }
1605
1606     sl->redundant_pic_count = 0;
1607     if (pps->redundant_pic_cnt_present)
1608         sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1609
1610     if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1611         sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1612
1613     ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1614                                   &sl->gb, pps, sl->slice_type_nos,
1615                                   picture_structure);
1616     if (ret < 0)
1617         return ret;
1618
1619     if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1620        ret = ff_h264_decode_ref_pic_list_reordering(sl, avctx);
1621        if (ret < 0) {
1622            sl->ref_count[1] = sl->ref_count[0] = 0;
1623            return ret;
1624        }
1625     }
1626
1627     sl->pwt.use_weight = 0;
1628     for (i = 0; i < 2; i++) {
1629         sl->pwt.luma_weight_flag[i]   = 0;
1630         sl->pwt.chroma_weight_flag[i] = 0;
1631     }
1632     if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1633         (pps->weighted_bipred_idc == 1 &&
1634          sl->slice_type_nos == AV_PICTURE_TYPE_B))
1635         ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1636                                   sl->slice_type_nos, &sl->pwt);
1637
1638     sl->explicit_ref_marking = 0;
1639     if (nal->ref_idc) {
1640         ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, avctx);
1641         if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
1642             return AVERROR_INVALIDDATA;
1643     }
1644
1645     if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1646         tmp = get_ue_golomb_31(&sl->gb);
1647         if (tmp > 2) {
1648             av_log(avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1649             return AVERROR_INVALIDDATA;
1650         }
1651         sl->cabac_init_idc = tmp;
1652     }
1653
1654     sl->last_qscale_diff = 0;
1655     tmp = pps->init_qp + get_se_golomb(&sl->gb);
1656     if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1657         av_log(avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1658         return AVERROR_INVALIDDATA;
1659     }
1660     sl->qscale       = tmp;
1661     sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
1662     sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
1663     // FIXME qscale / qp ... stuff
1664     if (sl->slice_type == AV_PICTURE_TYPE_SP)
1665         get_bits1(&sl->gb); /* sp_for_switch_flag */
1666     if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1667         sl->slice_type == AV_PICTURE_TYPE_SI)
1668         get_se_golomb(&sl->gb); /* slice_qs_delta */
1669
1670     sl->deblocking_filter     = 1;
1671     sl->slice_alpha_c0_offset = 0;
1672     sl->slice_beta_offset     = 0;
1673     if (pps->deblocking_filter_parameters_present) {
1674         tmp = get_ue_golomb_31(&sl->gb);
1675         if (tmp > 2) {
1676             av_log(avctx, AV_LOG_ERROR,
1677                    "deblocking_filter_idc %u out of range\n", tmp);
1678             return AVERROR_INVALIDDATA;
1679         }
1680         sl->deblocking_filter = tmp;
1681         if (sl->deblocking_filter < 2)
1682             sl->deblocking_filter ^= 1;  // 1<->0
1683
1684         if (sl->deblocking_filter) {
1685             sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1686             sl->slice_beta_offset     = get_se_golomb(&sl->gb) * 2;
1687             if (sl->slice_alpha_c0_offset >  12 ||
1688                 sl->slice_alpha_c0_offset < -12 ||
1689                 sl->slice_beta_offset >  12     ||
1690                 sl->slice_beta_offset < -12) {
1691                 av_log(avctx, AV_LOG_ERROR,
1692                        "deblocking filter parameters %d %d out of range\n",
1693                        sl->slice_alpha_c0_offset, sl->slice_beta_offset);
1694                 return AVERROR_INVALIDDATA;
1695             }
1696         }
1697     }
1698
1699     return 0;
1700 }
1701
1702 /* do all the per-slice initialization needed before we can start decoding the
1703  * actual MBs */
1704 static int h264_slice_init(H264Context *h, H264SliceContext *sl,
1705                            const H2645NAL *nal)
1706 {
1707     int i, j, ret = 0;
1708
1709     if (h->current_slice > 0) {
1710         if (h->ps.pps != (const PPS*)h->ps.pps_list[sl->pps_id]->data) {
1711             av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
1712             return AVERROR_INVALIDDATA;
1713         }
1714
1715         if (h->picture_structure != sl->picture_structure ||
1716             h->droppable         != (nal->ref_idc == 0)) {
1717             av_log(h->avctx, AV_LOG_ERROR,
1718                    "Changing field mode (%d -> %d) between slices is not allowed\n",
1719                    h->picture_structure, sl->picture_structure);
1720             return AVERROR_INVALIDDATA;
1721         } else if (!h->cur_pic_ptr) {
1722             av_log(h->avctx, AV_LOG_ERROR,
1723                    "unset cur_pic_ptr on slice %d\n",
1724                    h->current_slice + 1);
1725             return AVERROR_INVALIDDATA;
1726         }
1727     }
1728
1729     if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
1730         av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
1731         return AVERROR_INVALIDDATA;
1732     }
1733
1734     assert(h->mb_num == h->mb_width * h->mb_height);
1735     if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1736         sl->first_mb_addr >= h->mb_num) {
1737         av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1738         return AVERROR_INVALIDDATA;
1739     }
1740     sl->resync_mb_x = sl->mb_x =  sl->first_mb_addr % h->mb_width;
1741     sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
1742                                  FIELD_OR_MBAFF_PICTURE(h);
1743     if (h->picture_structure == PICT_BOTTOM_FIELD)
1744         sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1745     assert(sl->mb_y < h->mb_height);
1746
1747     ret = ff_h264_build_ref_list(h, sl);
1748     if (ret < 0)
1749         return ret;
1750
1751     if (h->ps.pps->weighted_bipred_idc == 2 &&
1752         sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1753         implicit_weight_table(h, sl, -1);
1754         if (FRAME_MBAFF(h)) {
1755             implicit_weight_table(h, sl, 0);
1756             implicit_weight_table(h, sl, 1);
1757         }
1758     }
1759
1760     if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1761         ff_h264_direct_dist_scale_factor(h, sl);
1762     ff_h264_direct_ref_list_init(h, sl);
1763
1764     if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1765         (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1766          sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1767         (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&
1768          sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1769         (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1770          nal->ref_idc == 0))
1771         sl->deblocking_filter = 0;
1772
1773     if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
1774         if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1775             /* Cheat slightly for speed:
1776              * Do not bother to deblock across slices. */
1777             sl->deblocking_filter = 2;
1778         } else {
1779             h->postpone_filter = 1;
1780         }
1781     }
1782     sl->qp_thresh = 15 -
1783                    FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1784                    FFMAX3(0,
1785                           h->ps.pps->chroma_qp_index_offset[0],
1786                           h->ps.pps->chroma_qp_index_offset[1]) +
1787                    6 * (h->ps.sps->bit_depth_luma - 8);
1788
1789     sl->slice_num       = ++h->current_slice;
1790     if (sl->slice_num >= MAX_SLICES) {
1791         av_log(h->avctx, AV_LOG_ERROR,
1792                "Too many slices, increase MAX_SLICES and recompile\n");
1793     }
1794
1795     for (j = 0; j < 2; j++) {
1796         int id_list[16];
1797         int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
1798         for (i = 0; i < 16; i++) {
1799             id_list[i] = 60;
1800             if (j < sl->list_count && i < sl->ref_count[j] &&
1801                 sl->ref_list[j][i].parent->f->buf[0]) {
1802                 int k;
1803                 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
1804                 for (k = 0; k < h->short_ref_count; k++)
1805                     if (h->short_ref[k]->f->buf[0]->buffer == buf) {
1806                         id_list[i] = k;
1807                         break;
1808                     }
1809                 for (k = 0; k < h->long_ref_count; k++)
1810                     if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
1811                         id_list[i] = h->short_ref_count + k;
1812                         break;
1813                     }
1814             }
1815         }
1816
1817         ref2frm[0] =
1818         ref2frm[1] = -1;
1819         for (i = 0; i < 16; i++)
1820             ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
1821         ref2frm[18 + 0] =
1822         ref2frm[18 + 1] = -1;
1823         for (i = 16; i < 48; i++)
1824             ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
1825                              (sl->ref_list[j][i].reference & 3);
1826     }
1827
1828     if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1829         av_log(h->avctx, AV_LOG_DEBUG,
1830                "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",
1831                sl->slice_num,
1832                (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1833                sl->mb_y * h->mb_width + sl->mb_x,
1834                av_get_picture_type_char(sl->slice_type),
1835                sl->slice_type_fixed ? " fix" : "",
1836                nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
1837                h->poc.frame_num,
1838                h->cur_pic_ptr->field_poc[0],
1839                h->cur_pic_ptr->field_poc[1],
1840                sl->ref_count[0], sl->ref_count[1],
1841                sl->qscale,
1842                sl->deblocking_filter,
1843                sl->slice_alpha_c0_offset, sl->slice_beta_offset,
1844                sl->pwt.use_weight,
1845                sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
1846                sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
1847     }
1848
1849     return 0;
1850 }
1851
1852 int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
1853 {
1854     H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
1855     int ret;
1856
1857     sl->gb = nal->gb;
1858
1859     ret = h264_slice_header_parse(sl, nal, &h->ps, h->avctx);
1860     if (ret < 0)
1861         return ret;
1862
1863     // discard redundant pictures
1864     if (sl->redundant_pic_count > 0)
1865         return 0;
1866
1867     if (!h->setup_finished) {
1868         if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
1869             // this slice starts a new field
1870             // first decode any pending queued slices
1871             if (h->nb_slice_ctx_queued) {
1872                 H264SliceContext tmp_ctx;
1873
1874                 ret = ff_h264_execute_decode_slices(h);
1875                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1876                     return ret;
1877
1878                 memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
1879                 memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
1880                 memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
1881                 sl = h->slice_ctx;
1882             }
1883
1884             if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
1885                 ff_h264_field_end(h, sl, 1);
1886             }
1887
1888             h->current_slice = 0;
1889             if (!h->first_field) {
1890                 if (h->cur_pic_ptr && !h->droppable) {
1891                     ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1892                                               h->picture_structure == PICT_BOTTOM_FIELD);
1893                 }
1894                 h->cur_pic_ptr = NULL;
1895             }
1896         }
1897
1898         if (h->current_slice == 0) {
1899             ret = h264_field_start(h, sl, nal);
1900             if (ret < 0)
1901                 return ret;
1902         }
1903     }
1904
1905     ret = h264_slice_init(h, sl, nal);
1906     if (ret < 0)
1907         return ret;
1908
1909     if ((h->avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1910         (h->avctx->skip_frame < AVDISCARD_BIDIR  ||
1911          sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1912         (h->avctx->skip_frame < AVDISCARD_NONKEY ||
1913          h->cur_pic_ptr->f->key_frame) &&
1914         h->avctx->skip_frame < AVDISCARD_ALL) {
1915         h->nb_slice_ctx_queued++;
1916     }
1917
1918     return 0;
1919 }
1920
1921 int ff_h264_get_slice_type(const H264SliceContext *sl)
1922 {
1923     switch (sl->slice_type) {
1924     case AV_PICTURE_TYPE_P:
1925         return 0;
1926     case AV_PICTURE_TYPE_B:
1927         return 1;
1928     case AV_PICTURE_TYPE_I:
1929         return 2;
1930     case AV_PICTURE_TYPE_SP:
1931         return 3;
1932     case AV_PICTURE_TYPE_SI:
1933         return 4;
1934     default:
1935         return AVERROR_INVALIDDATA;
1936     }
1937 }
1938
1939 static av_always_inline void fill_filter_caches_inter(const H264Context *h,
1940                                                       H264SliceContext *sl,
1941                                                       int mb_type, int top_xy,
1942                                                       int left_xy[LEFT_MBS],
1943                                                       int top_type,
1944                                                       int left_type[LEFT_MBS],
1945                                                       int mb_xy, int list)
1946 {
1947     int b_stride = h->b_stride;
1948     int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1949     int8_t *ref_cache   = &sl->ref_cache[list][scan8[0]];
1950     if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1951         if (USES_LIST(top_type, list)) {
1952             const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;
1953             const int b8_xy = 4 * top_xy + 2;
1954             const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1955             AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1956             ref_cache[0 - 1 * 8] =
1957             ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
1958             ref_cache[2 - 1 * 8] =
1959             ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
1960         } else {
1961             AV_ZERO128(mv_dst - 1 * 8);
1962             AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1963         }
1964
1965         if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1966             if (USES_LIST(left_type[LTOP], list)) {
1967                 const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;
1968                 const int b8_xy = 4 * left_xy[LTOP] + 1;
1969                 const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1970                 AV_COPY32(mv_dst - 1 +  0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1971                 AV_COPY32(mv_dst - 1 +  8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1972                 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1973                 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1974                 ref_cache[-1 +  0] =
1975                 ref_cache[-1 +  8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1976                 ref_cache[-1 + 16] =
1977                 ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1978             } else {
1979                 AV_ZERO32(mv_dst - 1 +  0);
1980                 AV_ZERO32(mv_dst - 1 +  8);
1981                 AV_ZERO32(mv_dst - 1 + 16);
1982                 AV_ZERO32(mv_dst - 1 + 24);
1983                 ref_cache[-1 +  0] =
1984                 ref_cache[-1 +  8] =
1985                 ref_cache[-1 + 16] =
1986                 ref_cache[-1 + 24] = LIST_NOT_USED;
1987             }
1988         }
1989     }
1990
1991     if (!USES_LIST(mb_type, list)) {
1992         fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
1993         AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1994         AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1995         AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1996         AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1997         return;
1998     }
1999
2000     {
2001         int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
2002         const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
2003         uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
2004         uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
2005         AV_WN32A(&ref_cache[0 * 8], ref01);
2006         AV_WN32A(&ref_cache[1 * 8], ref01);
2007         AV_WN32A(&ref_cache[2 * 8], ref23);
2008         AV_WN32A(&ref_cache[3 * 8], ref23);
2009     }
2010
2011     {
2012         int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
2013         AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
2014         AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
2015         AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
2016         AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
2017     }
2018 }
2019
2020 /**
2021  * @return non zero if the loop filter can be skipped
2022  */
2023 static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
2024 {
2025     const int mb_xy = sl->mb_xy;
2026     int top_xy, left_xy[LEFT_MBS];
2027     int top_type, left_type[LEFT_MBS];
2028     uint8_t *nnz;
2029     uint8_t *nnz_cache;
2030
2031     top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
2032
2033     left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
2034     if (FRAME_MBAFF(h)) {
2035         const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
2036         const int curr_mb_field_flag = IS_INTERLACED(mb_type);
2037         if (sl->mb_y & 1) {
2038             if (left_mb_field_flag != curr_mb_field_flag)
2039                 left_xy[LTOP] -= h->mb_stride;
2040         } else {
2041             if (curr_mb_field_flag)
2042                 top_xy += h->mb_stride &
2043                           (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
2044             if (left_mb_field_flag != curr_mb_field_flag)
2045                 left_xy[LBOT] += h->mb_stride;
2046         }
2047     }
2048
2049     sl->top_mb_xy        = top_xy;
2050     sl->left_mb_xy[LTOP] = left_xy[LTOP];
2051     sl->left_mb_xy[LBOT] = left_xy[LBOT];
2052     {
2053         /* For sufficiently low qp, filtering wouldn't do anything.
2054          * This is a conservative estimate: could also check beta_offset
2055          * and more accurate chroma_qp. */
2056         int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
2057         int qp        = h->cur_pic.qscale_table[mb_xy];
2058         if (qp <= qp_thresh &&
2059             (left_xy[LTOP] < 0 ||
2060              ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
2061             (top_xy < 0 ||
2062              ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
2063             if (!FRAME_MBAFF(h))
2064                 return 1;
2065             if ((left_xy[LTOP] < 0 ||
2066                  ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
2067                 (top_xy < h->mb_stride ||
2068                  ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
2069                 return 1;
2070         }
2071     }
2072
2073     top_type        = h->cur_pic.mb_type[top_xy];
2074     left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
2075     left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
2076     if (sl->deblocking_filter == 2) {
2077         if (h->slice_table[top_xy] != sl->slice_num)
2078             top_type = 0;
2079         if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
2080             left_type[LTOP] = left_type[LBOT] = 0;
2081     } else {
2082         if (h->slice_table[top_xy] == 0xFFFF)
2083             top_type = 0;
2084         if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
2085             left_type[LTOP] = left_type[LBOT] = 0;
2086     }
2087     sl->top_type        = top_type;
2088     sl->left_type[LTOP] = left_type[LTOP];
2089     sl->left_type[LBOT] = left_type[LBOT];
2090
2091     if (IS_INTRA(mb_type))
2092         return 0;
2093
2094     fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2095                              top_type, left_type, mb_xy, 0);
2096     if (sl->list_count == 2)
2097         fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2098                                  top_type, left_type, mb_xy, 1);
2099
2100     nnz       = h->non_zero_count[mb_xy];
2101     nnz_cache = sl->non_zero_count_cache;
2102     AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
2103     AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
2104     AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
2105     AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
2106     sl->cbp = h->cbp_table[mb_xy];
2107
2108     if (top_type) {
2109         nnz = h->non_zero_count[top_xy];
2110         AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
2111     }
2112
2113     if (left_type[LTOP]) {
2114         nnz = h->non_zero_count[left_xy[LTOP]];
2115         nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
2116         nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
2117         nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
2118         nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
2119     }
2120
2121     /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
2122      * from what the loop filter needs */
2123     if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
2124         if (IS_8x8DCT(top_type)) {
2125             nnz_cache[4 + 8 * 0] =
2126             nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
2127             nnz_cache[6 + 8 * 0] =
2128             nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
2129         }
2130         if (IS_8x8DCT(left_type[LTOP])) {
2131             nnz_cache[3 + 8 * 1] =
2132             nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
2133         }
2134         if (IS_8x8DCT(left_type[LBOT])) {
2135             nnz_cache[3 + 8 * 3] =
2136             nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
2137         }
2138
2139         if (IS_8x8DCT(mb_type)) {
2140             nnz_cache[scan8[0]] =
2141             nnz_cache[scan8[1]] =
2142             nnz_cache[scan8[2]] =
2143             nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
2144
2145             nnz_cache[scan8[0 + 4]] =
2146             nnz_cache[scan8[1 + 4]] =
2147             nnz_cache[scan8[2 + 4]] =
2148             nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
2149
2150             nnz_cache[scan8[0 + 8]] =
2151             nnz_cache[scan8[1 + 8]] =
2152             nnz_cache[scan8[2 + 8]] =
2153             nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
2154
2155             nnz_cache[scan8[0 + 12]] =
2156             nnz_cache[scan8[1 + 12]] =
2157             nnz_cache[scan8[2 + 12]] =
2158             nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
2159         }
2160     }
2161
2162     return 0;
2163 }
2164
2165 static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
2166 {
2167     uint8_t *dest_y, *dest_cb, *dest_cr;
2168     int linesize, uvlinesize, mb_x, mb_y;
2169     const int end_mb_y       = sl->mb_y + FRAME_MBAFF(h);
2170     const int old_slice_type = sl->slice_type;
2171     const int pixel_shift    = h->pixel_shift;
2172     const int block_h        = 16 >> h->chroma_y_shift;
2173
2174     if (h->postpone_filter)
2175         return;
2176
2177     if (sl->deblocking_filter) {
2178         for (mb_x = start_x; mb_x < end_x; mb_x++)
2179             for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
2180                 int mb_xy, mb_type;
2181                 mb_xy         = sl->mb_xy = mb_x + mb_y * h->mb_stride;
2182                 mb_type       = h->cur_pic.mb_type[mb_xy];
2183
2184                 if (FRAME_MBAFF(h))
2185                     sl->mb_mbaff               =
2186                     sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2187
2188                 sl->mb_x = mb_x;
2189                 sl->mb_y = mb_y;
2190                 dest_y  = h->cur_pic.f->data[0] +
2191                           ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
2192                 dest_cb = h->cur_pic.f->data[1] +
2193                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2194                           mb_y * sl->uvlinesize * block_h;
2195                 dest_cr = h->cur_pic.f->data[2] +
2196                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2197                           mb_y * sl->uvlinesize * block_h;
2198                 // FIXME simplify above
2199
2200                 if (MB_FIELD(sl)) {
2201                     linesize   = sl->mb_linesize   = sl->linesize   * 2;
2202                     uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
2203                     if (mb_y & 1) { // FIXME move out of this function?
2204                         dest_y  -= sl->linesize   * 15;
2205                         dest_cb -= sl->uvlinesize * (block_h - 1);
2206                         dest_cr -= sl->uvlinesize * (block_h - 1);
2207                     }
2208                 } else {
2209                     linesize   = sl->mb_linesize   = sl->linesize;
2210                     uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
2211                 }
2212                 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
2213                                  uvlinesize, 0);
2214                 if (fill_filter_caches(h, sl, mb_type))
2215                     continue;
2216                 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
2217                 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
2218
2219                 if (FRAME_MBAFF(h)) {
2220                     ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
2221                                       linesize, uvlinesize);
2222                 } else {
2223                     ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
2224                                            dest_cr, linesize, uvlinesize);
2225                 }
2226             }
2227     }
2228     sl->slice_type  = old_slice_type;
2229     sl->mb_x         = end_x;
2230     sl->mb_y         = end_mb_y - FRAME_MBAFF(h);
2231     sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
2232     sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
2233 }
2234
2235 static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
2236 {
2237     const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
2238     int mb_type     = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
2239                       h->cur_pic.mb_type[mb_xy - 1] :
2240                       (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
2241                       h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
2242     sl->mb_mbaff    = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2243 }
2244
2245 /**
2246  * Draw edges and report progress for the last MB row.
2247  */
2248 static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
2249 {
2250     int top            = 16 * (sl->mb_y      >> FIELD_PICTURE(h));
2251     int pic_height     = 16 *  h->mb_height >> FIELD_PICTURE(h);
2252     int height         =  16      << FRAME_MBAFF(h);
2253     int deblock_border = (16 + 4) << FRAME_MBAFF(h);
2254
2255     if (sl->deblocking_filter) {
2256         if ((top + height) >= pic_height)
2257             height += deblock_border;
2258         top -= deblock_border;
2259     }
2260
2261     if (top >= pic_height || (top + height) < 0)
2262         return;
2263
2264     height = FFMIN(height, pic_height - top);
2265     if (top < 0) {
2266         height = top + height;
2267         top    = 0;
2268     }
2269
2270     ff_h264_draw_horiz_band(h, sl, top, height);
2271
2272     if (h->droppable)
2273         return;
2274
2275     ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
2276                               h->picture_structure == PICT_BOTTOM_FIELD);
2277 }
2278
2279 static void er_add_slice(H264SliceContext *sl,
2280                          int startx, int starty,
2281                          int endx, int endy, int status)
2282 {
2283 #if CONFIG_ERROR_RESILIENCE
2284     ERContext *er = &sl->er;
2285
2286     if (!sl->h264->enable_er)
2287         return;
2288
2289     er->ref_count = sl->ref_count[0];
2290     ff_er_add_slice(er, startx, starty, endx, endy, status);
2291 #endif
2292 }
2293
2294 static int decode_slice(struct AVCodecContext *avctx, void *arg)
2295 {
2296     H264SliceContext *sl = arg;
2297     const H264Context *h = sl->h264;
2298     int lf_x_start = sl->mb_x;
2299     int orig_deblock = sl->deblocking_filter;
2300     int ret;
2301
2302     sl->linesize   = h->cur_pic_ptr->f->linesize[0];
2303     sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
2304
2305     ret = alloc_scratch_buffers(sl, sl->linesize);
2306     if (ret < 0)
2307         return ret;
2308
2309     sl->mb_skip_run = -1;
2310
2311     if (h->postpone_filter)
2312         sl->deblocking_filter = 0;
2313
2314     sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
2315                      (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
2316
2317     if (h->ps.pps->cabac) {
2318         /* realign */
2319         align_get_bits(&sl->gb);
2320
2321         /* init cabac */
2322         ff_init_cabac_decoder(&sl->cabac,
2323                               sl->gb.buffer + get_bits_count(&sl->gb) / 8,
2324                               (get_bits_left(&sl->gb) + 7) / 8);
2325
2326         ff_h264_init_cabac_states(h, sl);
2327
2328         for (;;) {
2329             // START_TIMER
2330             int ret, eos;
2331
2332             if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2333                 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2334                        sl->next_slice_idx);
2335                 return AVERROR_INVALIDDATA;
2336             }
2337
2338             ret = ff_h264_decode_mb_cabac(h, sl);
2339             // STOP_TIMER("decode_mb_cabac")
2340
2341             if (ret >= 0)
2342                 ff_h264_hl_decode_mb(h, sl);
2343
2344             // FIXME optimal? or let mb_decode decode 16x32 ?
2345             if (ret >= 0 && FRAME_MBAFF(h)) {
2346                 sl->mb_y++;
2347
2348                 ret = ff_h264_decode_mb_cabac(h, sl);
2349
2350                 if (ret >= 0)
2351                     ff_h264_hl_decode_mb(h, sl);
2352                 sl->mb_y--;
2353             }
2354             eos = get_cabac_terminate(&sl->cabac);
2355
2356             if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
2357                 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2358                 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2359                              sl->mb_y, ER_MB_END);
2360                 if (sl->mb_x >= lf_x_start)
2361                     loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
2362                 goto finish;
2363             }
2364             if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2365                 av_log(h->avctx, AV_LOG_ERROR,
2366                        "error while decoding MB %d %d, bytestream %td\n",
2367                        sl->mb_x, sl->mb_y,
2368                        sl->cabac.bytestream_end - sl->cabac.bytestream);
2369                 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2370                              sl->mb_y, ER_MB_ERROR);
2371                 return AVERROR_INVALIDDATA;
2372             }
2373
2374             if (++sl->mb_x >= h->mb_width) {
2375                 loop_filter(h, sl, lf_x_start, sl->mb_x);
2376                 sl->mb_x = lf_x_start = 0;
2377                 decode_finish_row(h, sl);
2378                 ++sl->mb_y;
2379                 if (FIELD_OR_MBAFF_PICTURE(h)) {
2380                     ++sl->mb_y;
2381                     if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2382                         predict_field_decoding_flag(h, sl);
2383                 }
2384             }
2385
2386             if (eos || sl->mb_y >= h->mb_height) {
2387                 ff_tlog(h->avctx, "slice end %d %d\n",
2388                         get_bits_count(&sl->gb), sl->gb.size_in_bits);
2389                 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2390                              sl->mb_y, ER_MB_END);
2391                 if (sl->mb_x > lf_x_start)
2392                     loop_filter(h, sl, lf_x_start, sl->mb_x);
2393                 goto finish;
2394             }
2395         }
2396     } else {
2397         for (;;) {
2398             int ret;
2399
2400             if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2401                 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2402                        sl->next_slice_idx);
2403                 return AVERROR_INVALIDDATA;
2404             }
2405
2406             ret = ff_h264_decode_mb_cavlc(h, sl);
2407
2408             if (ret >= 0)
2409                 ff_h264_hl_decode_mb(h, sl);
2410
2411             // FIXME optimal? or let mb_decode decode 16x32 ?
2412             if (ret >= 0 && FRAME_MBAFF(h)) {
2413                 sl->mb_y++;
2414                 ret = ff_h264_decode_mb_cavlc(h, sl);
2415
2416                 if (ret >= 0)
2417                     ff_h264_hl_decode_mb(h, sl);
2418                 sl->mb_y--;
2419             }
2420
2421             if (ret < 0) {
2422                 av_log(h->avctx, AV_LOG_ERROR,
2423                        "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2424                 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2425                              sl->mb_y, ER_MB_ERROR);
2426                 return ret;
2427             }
2428
2429             if (++sl->mb_x >= h->mb_width) {
2430                 loop_filter(h, sl, lf_x_start, sl->mb_x);
2431                 sl->mb_x = lf_x_start = 0;
2432                 decode_finish_row(h, sl);
2433                 ++sl->mb_y;
2434                 if (FIELD_OR_MBAFF_PICTURE(h)) {
2435                     ++sl->mb_y;
2436                     if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2437                         predict_field_decoding_flag(h, sl);
2438                 }
2439                 if (sl->mb_y >= h->mb_height) {
2440                     ff_tlog(h->avctx, "slice end %d %d\n",
2441                             get_bits_count(&sl->gb), sl->gb.size_in_bits);
2442
2443                     if (get_bits_left(&sl->gb) == 0) {
2444                         er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2445                                      sl->mb_x - 1, sl->mb_y, ER_MB_END);
2446
2447                         goto finish;
2448                     } else {
2449                         er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2450                                      sl->mb_x - 1, sl->mb_y, ER_MB_END);
2451
2452                         return AVERROR_INVALIDDATA;
2453                     }
2454                 }
2455             }
2456
2457             if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2458                 ff_tlog(h->avctx, "slice end %d %d\n",
2459                         get_bits_count(&sl->gb), sl->gb.size_in_bits);
2460
2461                 if (get_bits_left(&sl->gb) == 0) {
2462                     er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2463                                  sl->mb_x - 1, sl->mb_y, ER_MB_END);
2464                     if (sl->mb_x > lf_x_start)
2465                         loop_filter(h, sl, lf_x_start, sl->mb_x);
2466
2467                     goto finish;
2468                 } else {
2469                     er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2470                                  sl->mb_y, ER_MB_ERROR);
2471
2472                     return AVERROR_INVALIDDATA;
2473                 }
2474             }
2475         }
2476     }
2477
2478 finish:
2479     sl->deblocking_filter = orig_deblock;
2480     return 0;
2481 }
2482
2483 /**
2484  * Call decode_slice() for each context.
2485  *
2486  * @param h h264 master context
2487  */
2488 int ff_h264_execute_decode_slices(H264Context *h)
2489 {
2490     AVCodecContext *const avctx = h->avctx;
2491     H264SliceContext *sl;
2492     int context_count = h->nb_slice_ctx_queued;
2493     int ret = 0;
2494     int i, j;
2495
2496     if (h->avctx->hwaccel || context_count < 1)
2497         return 0;
2498     if (context_count == 1) {
2499
2500         h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2501         h->postpone_filter = 0;
2502
2503         ret = decode_slice(avctx, &h->slice_ctx[0]);
2504         h->mb_y = h->slice_ctx[0].mb_y;
2505         if (ret < 0)
2506             goto finish;
2507     } else {
2508         for (i = 0; i < context_count; i++) {
2509             int next_slice_idx = h->mb_width * h->mb_height;
2510             int slice_idx;
2511
2512             sl                 = &h->slice_ctx[i];
2513             sl->er.error_count = 0;
2514
2515             /* make sure none of those slices overlap */
2516             slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2517             for (j = 0; j < context_count; j++) {
2518                 H264SliceContext *sl2 = &h->slice_ctx[j];
2519                 int        slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2520
2521                 if (i == j || slice_idx2 < slice_idx)
2522                     continue;
2523                 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2524             }
2525             sl->next_slice_idx = next_slice_idx;
2526         }
2527
2528         avctx->execute(avctx, decode_slice, h->slice_ctx,
2529                        NULL, context_count, sizeof(h->slice_ctx[0]));
2530
2531         /* pull back stuff from slices to master context */
2532         sl                   = &h->slice_ctx[context_count - 1];
2533         h->mb_y              = sl->mb_y;
2534         for (i = 1; i < context_count; i++)
2535             h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
2536
2537         if (h->postpone_filter) {
2538             h->postpone_filter = 0;
2539
2540             for (i = 0; i < context_count; i++) {
2541                 int y_end, x_end;
2542
2543                 sl = &h->slice_ctx[i];
2544                 y_end = FFMIN(sl->mb_y + 1, h->mb_height);
2545                 x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
2546
2547                 for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
2548                     sl->mb_y = j;
2549                     loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
2550                                 j == y_end - 1 ? x_end : h->mb_width);
2551                 }
2552             }
2553         }
2554     }
2555
2556 finish:
2557     h->nb_slice_ctx_queued = 0;
2558     return ret;
2559 }