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