]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
mdec: set color_range
[ffmpeg] / libavcodec / h264.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... decoder
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * H.264 / AVC / MPEG4 part10 codec.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/stereo3d.h"
31 #include "libavutil/timer.h"
32 #include "internal.h"
33 #include "cabac.h"
34 #include "cabac_functions.h"
35 #include "dsputil.h"
36 #include "error_resilience.h"
37 #include "avcodec.h"
38 #include "h264.h"
39 #include "h264data.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
42 #include "golomb.h"
43 #include "mathops.h"
44 #include "mpegutils.h"
45 #include "rectangle.h"
46 #include "svq3.h"
47 #include "thread.h"
48
49 #include <assert.h>
50
51 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
52
53 static const uint8_t rem6[QP_MAX_NUM + 1] = {
54     0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
55     3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
56     0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
57 };
58
59 static const uint8_t div6[QP_MAX_NUM + 1] = {
60     0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3,  3,  3,
61     3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6,  6,  6,
62     7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
63 };
64
65 static const uint8_t field_scan[16] = {
66     0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
67     0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
68     2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
69     3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
70 };
71
72 static const uint8_t field_scan8x8[64] = {
73     0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
74     1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
75     2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
76     0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
77     2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
78     2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
79     2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
80     3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
81     3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
82     4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
83     4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
84     5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
85     5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
86     7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
87     6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
88     7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
89 };
90
91 static const uint8_t field_scan8x8_cavlc[64] = {
92     0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
93     2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
94     3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
95     5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
96     0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
97     1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
98     3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
99     5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
100     0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
101     1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
102     3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
103     5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
104     1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
105     1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
106     3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
107     6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
108 };
109
110 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
111 static const uint8_t zigzag_scan8x8_cavlc[64] = {
112     0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
113     4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
114     3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
115     2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
116     1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
117     3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
118     2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
119     3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
120     0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
121     2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
122     1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
123     4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
124     0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
125     1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
126     0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
127     5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
128 };
129
130 static const uint8_t dequant4_coeff_init[6][3] = {
131     { 10, 13, 16 },
132     { 11, 14, 18 },
133     { 13, 16, 20 },
134     { 14, 18, 23 },
135     { 16, 20, 25 },
136     { 18, 23, 29 },
137 };
138
139 static const uint8_t dequant8_coeff_init_scan[16] = {
140     0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
141 };
142
143 static const uint8_t dequant8_coeff_init[6][6] = {
144     { 20, 18, 32, 19, 25, 24 },
145     { 22, 19, 35, 21, 28, 26 },
146     { 26, 23, 42, 24, 33, 31 },
147     { 28, 25, 45, 26, 35, 33 },
148     { 32, 28, 51, 30, 40, 38 },
149     { 36, 32, 58, 34, 46, 43 },
150 };
151
152 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
153 #if CONFIG_H264_DXVA2_HWACCEL
154     AV_PIX_FMT_DXVA2_VLD,
155 #endif
156 #if CONFIG_H264_VAAPI_HWACCEL
157     AV_PIX_FMT_VAAPI_VLD,
158 #endif
159 #if CONFIG_H264_VDA_HWACCEL
160     AV_PIX_FMT_VDA_VLD,
161 #endif
162 #if CONFIG_H264_VDPAU_HWACCEL
163     AV_PIX_FMT_VDPAU,
164 #endif
165     AV_PIX_FMT_YUV420P,
166     AV_PIX_FMT_NONE
167 };
168
169 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
170 #if CONFIG_H264_DXVA2_HWACCEL
171     AV_PIX_FMT_DXVA2_VLD,
172 #endif
173 #if CONFIG_H264_VAAPI_HWACCEL
174     AV_PIX_FMT_VAAPI_VLD,
175 #endif
176 #if CONFIG_H264_VDA_HWACCEL
177     AV_PIX_FMT_VDA_VLD,
178 #endif
179 #if CONFIG_H264_VDPAU_HWACCEL
180     AV_PIX_FMT_VDPAU,
181 #endif
182     AV_PIX_FMT_YUVJ420P,
183     AV_PIX_FMT_NONE
184 };
185
186 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
187                               int (*mv)[2][4][2],
188                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
189 {
190     H264Context *h = opaque;
191
192     h->mb_x  = mb_x;
193     h->mb_y  = mb_y;
194     h->mb_xy = mb_x + mb_y * h->mb_stride;
195     memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
196     assert(ref >= 0);
197     /* FIXME: It is possible albeit uncommon that slice references
198      * differ between slices. We take the easy approach and ignore
199      * it for now. If this turns out to have any relevance in
200      * practice then correct remapping should be added. */
201     if (ref >= h->ref_count[0])
202         ref = 0;
203     fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
204                    2, 2, 2, ref, 1);
205     fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
206     fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
207                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
208     assert(!FRAME_MBAFF(h));
209     ff_h264_hl_decode_mb(h);
210 }
211
212 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
213 {
214     AVCodecContext *avctx = h->avctx;
215     AVFrame *cur  = &h->cur_pic.f;
216     AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
217     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
218     int vshift = desc->log2_chroma_h;
219     const int field_pic = h->picture_structure != PICT_FRAME;
220     if (field_pic) {
221         height <<= 1;
222         y      <<= 1;
223     }
224
225     height = FFMIN(height, avctx->height - y);
226
227     if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
228         return;
229
230     if (avctx->draw_horiz_band) {
231         AVFrame *src;
232         int offset[AV_NUM_DATA_POINTERS];
233         int i;
234
235         if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
236             (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
237             src = cur;
238         else if (last)
239             src = last;
240         else
241             return;
242
243         offset[0] = y * src->linesize[0];
244         offset[1] =
245         offset[2] = (y >> vshift) * src->linesize[1];
246         for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
247             offset[i] = 0;
248
249         emms_c();
250
251         avctx->draw_horiz_band(avctx, src, offset,
252                                y, h->picture_structure, height);
253     }
254 }
255
256 static void unref_picture(H264Context *h, H264Picture *pic)
257 {
258     int off = offsetof(H264Picture, tf) + sizeof(pic->tf);
259     int i;
260
261     if (!pic->f.buf[0])
262         return;
263
264     ff_thread_release_buffer(h->avctx, &pic->tf);
265     av_buffer_unref(&pic->hwaccel_priv_buf);
266
267     av_buffer_unref(&pic->qscale_table_buf);
268     av_buffer_unref(&pic->mb_type_buf);
269     for (i = 0; i < 2; i++) {
270         av_buffer_unref(&pic->motion_val_buf[i]);
271         av_buffer_unref(&pic->ref_index_buf[i]);
272     }
273
274     memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
275 }
276
277 static void release_unused_pictures(H264Context *h, int remove_current)
278 {
279     int i;
280
281     /* release non reference frames */
282     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
283         if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
284             (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
285             unref_picture(h, &h->DPB[i]);
286         }
287     }
288 }
289
290 static int ref_picture(H264Context *h, H264Picture *dst, H264Picture *src)
291 {
292     int ret, i;
293
294     av_assert0(!dst->f.buf[0]);
295     av_assert0(src->f.buf[0]);
296
297     src->tf.f = &src->f;
298     dst->tf.f = &dst->f;
299     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
300     if (ret < 0)
301         goto fail;
302
303     dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
304     dst->mb_type_buf      = av_buffer_ref(src->mb_type_buf);
305     if (!dst->qscale_table_buf || !dst->mb_type_buf)
306         goto fail;
307     dst->qscale_table = src->qscale_table;
308     dst->mb_type      = src->mb_type;
309
310     for (i = 0; i < 2; i++) {
311         dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
312         dst->ref_index_buf[i]  = av_buffer_ref(src->ref_index_buf[i]);
313         if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
314             goto fail;
315         dst->motion_val[i] = src->motion_val[i];
316         dst->ref_index[i]  = src->ref_index[i];
317     }
318
319     if (src->hwaccel_picture_private) {
320         dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
321         if (!dst->hwaccel_priv_buf)
322             goto fail;
323         dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
324     }
325
326     for (i = 0; i < 2; i++)
327         dst->field_poc[i] = src->field_poc[i];
328
329     memcpy(dst->ref_poc,   src->ref_poc,   sizeof(src->ref_poc));
330     memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
331
332     dst->poc           = src->poc;
333     dst->frame_num     = src->frame_num;
334     dst->mmco_reset    = src->mmco_reset;
335     dst->pic_id        = src->pic_id;
336     dst->long_ref      = src->long_ref;
337     dst->mbaff         = src->mbaff;
338     dst->field_picture = src->field_picture;
339     dst->needs_realloc = src->needs_realloc;
340     dst->reference     = src->reference;
341     dst->recovered     = src->recovered;
342
343     return 0;
344 fail:
345     unref_picture(h, dst);
346     return ret;
347 }
348
349 static int alloc_scratch_buffers(H264Context *h, int linesize)
350 {
351     int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
352
353     if (h->bipred_scratchpad)
354         return 0;
355
356     h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
357     // edge emu needs blocksize + filter length - 1
358     // (= 21x21 for  h264)
359     h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
360
361     if (!h->bipred_scratchpad || !h->edge_emu_buffer) {
362         av_freep(&h->bipred_scratchpad);
363         av_freep(&h->edge_emu_buffer);
364         return AVERROR(ENOMEM);
365     }
366
367     return 0;
368 }
369
370 static int init_table_pools(H264Context *h)
371 {
372     const int big_mb_num    = h->mb_stride * (h->mb_height + 1) + 1;
373     const int mb_array_size = h->mb_stride * h->mb_height;
374     const int b4_stride     = h->mb_width * 4 + 1;
375     const int b4_array_size = b4_stride * h->mb_height * 4;
376
377     h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
378                                                av_buffer_allocz);
379     h->mb_type_pool      = av_buffer_pool_init((big_mb_num + h->mb_stride) *
380                                                sizeof(uint32_t), av_buffer_allocz);
381     h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
382                                              sizeof(int16_t), av_buffer_allocz);
383     h->ref_index_pool  = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
384
385     if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
386         !h->ref_index_pool) {
387         av_buffer_pool_uninit(&h->qscale_table_pool);
388         av_buffer_pool_uninit(&h->mb_type_pool);
389         av_buffer_pool_uninit(&h->motion_val_pool);
390         av_buffer_pool_uninit(&h->ref_index_pool);
391         return AVERROR(ENOMEM);
392     }
393
394     return 0;
395 }
396
397 static int alloc_picture(H264Context *h, H264Picture *pic)
398 {
399     int i, ret = 0;
400
401     av_assert0(!pic->f.data[0]);
402
403     pic->tf.f = &pic->f;
404     ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
405                                                    AV_GET_BUFFER_FLAG_REF : 0);
406     if (ret < 0)
407         goto fail;
408
409     h->linesize   = pic->f.linesize[0];
410     h->uvlinesize = pic->f.linesize[1];
411
412     if (h->avctx->hwaccel) {
413         const AVHWAccel *hwaccel = h->avctx->hwaccel;
414         av_assert0(!pic->hwaccel_picture_private);
415         if (hwaccel->priv_data_size) {
416             pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
417             if (!pic->hwaccel_priv_buf)
418                 return AVERROR(ENOMEM);
419             pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
420         }
421     }
422
423     if (!h->qscale_table_pool) {
424         ret = init_table_pools(h);
425         if (ret < 0)
426             goto fail;
427     }
428
429     pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
430     pic->mb_type_buf      = av_buffer_pool_get(h->mb_type_pool);
431     if (!pic->qscale_table_buf || !pic->mb_type_buf)
432         goto fail;
433
434     pic->mb_type      = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
435     pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
436
437     for (i = 0; i < 2; i++) {
438         pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
439         pic->ref_index_buf[i]  = av_buffer_pool_get(h->ref_index_pool);
440         if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
441             goto fail;
442
443         pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
444         pic->ref_index[i]  = pic->ref_index_buf[i]->data;
445     }
446
447     return 0;
448 fail:
449     unref_picture(h, pic);
450     return (ret < 0) ? ret : AVERROR(ENOMEM);
451 }
452
453 static inline int pic_is_unused(H264Context *h, H264Picture *pic)
454 {
455     if (!pic->f.buf[0])
456         return 1;
457     if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
458         return 1;
459     return 0;
460 }
461
462 static int find_unused_picture(H264Context *h)
463 {
464     int i;
465
466     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
467         if (pic_is_unused(h, &h->DPB[i]))
468             break;
469     }
470     if (i == H264_MAX_PICTURE_COUNT)
471         return AVERROR_INVALIDDATA;
472
473     if (h->DPB[i].needs_realloc) {
474         h->DPB[i].needs_realloc = 0;
475         unref_picture(h, &h->DPB[i]);
476     }
477
478     return i;
479 }
480
481 /**
482  * Check if the top & left blocks are available if needed and
483  * change the dc mode so it only uses the available blocks.
484  */
485 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
486 {
487     static const int8_t top[12] = {
488         -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
489     };
490     static const int8_t left[12] = {
491         0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
492     };
493     int i;
494
495     if (!(h->top_samples_available & 0x8000)) {
496         for (i = 0; i < 4; i++) {
497             int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
498             if (status < 0) {
499                 av_log(h->avctx, AV_LOG_ERROR,
500                        "top block unavailable for requested intra4x4 mode %d at %d %d\n",
501                        status, h->mb_x, h->mb_y);
502                 return AVERROR_INVALIDDATA;
503             } else if (status) {
504                 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
505             }
506         }
507     }
508
509     if ((h->left_samples_available & 0x8888) != 0x8888) {
510         static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
511         for (i = 0; i < 4; i++)
512             if (!(h->left_samples_available & mask[i])) {
513                 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
514                 if (status < 0) {
515                     av_log(h->avctx, AV_LOG_ERROR,
516                            "left block unavailable for requested intra4x4 mode %d at %d %d\n",
517                            status, h->mb_x, h->mb_y);
518                     return AVERROR_INVALIDDATA;
519                 } else if (status) {
520                     h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
521                 }
522             }
523     }
524
525     return 0;
526 } // FIXME cleanup like ff_h264_check_intra_pred_mode
527
528 /**
529  * Check if the top & left blocks are available if needed and
530  * change the dc mode so it only uses the available blocks.
531  */
532 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
533 {
534     static const int8_t top[4]  = { LEFT_DC_PRED8x8, 1, -1, -1 };
535     static const int8_t left[5] = { TOP_DC_PRED8x8, -1,  2, -1, DC_128_PRED8x8 };
536
537     if (mode > 3U) {
538         av_log(h->avctx, AV_LOG_ERROR,
539                "out of range intra chroma pred mode at %d %d\n",
540                h->mb_x, h->mb_y);
541         return AVERROR_INVALIDDATA;
542     }
543
544     if (!(h->top_samples_available & 0x8000)) {
545         mode = top[mode];
546         if (mode < 0) {
547             av_log(h->avctx, AV_LOG_ERROR,
548                    "top block unavailable for requested intra mode at %d %d\n",
549                    h->mb_x, h->mb_y);
550             return AVERROR_INVALIDDATA;
551         }
552     }
553
554     if ((h->left_samples_available & 0x8080) != 0x8080) {
555         mode = left[mode];
556         if (is_chroma && (h->left_samples_available & 0x8080)) {
557             // mad cow disease mode, aka MBAFF + constrained_intra_pred
558             mode = ALZHEIMER_DC_L0T_PRED8x8 +
559                    (!(h->left_samples_available & 0x8000)) +
560                    2 * (mode == DC_128_PRED8x8);
561         }
562         if (mode < 0) {
563             av_log(h->avctx, AV_LOG_ERROR,
564                    "left block unavailable for requested intra mode at %d %d\n",
565                    h->mb_x, h->mb_y);
566             return AVERROR_INVALIDDATA;
567         }
568     }
569
570     return mode;
571 }
572
573 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
574                                   int *dst_length, int *consumed, int length)
575 {
576     int i, si, di;
577     uint8_t *dst;
578     int bufidx;
579
580     // src[0]&0x80; // forbidden bit
581     h->nal_ref_idc   = src[0] >> 5;
582     h->nal_unit_type = src[0] & 0x1F;
583
584     src++;
585     length--;
586
587 #define STARTCODE_TEST                                                  \
588     if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {         \
589         if (src[i + 2] != 3) {                                          \
590             /* startcode, so we must be past the end */                 \
591             length = i;                                                 \
592         }                                                               \
593         break;                                                          \
594     }
595
596 #if HAVE_FAST_UNALIGNED
597 #define FIND_FIRST_ZERO                                                 \
598     if (i > 0 && !src[i])                                               \
599         i--;                                                            \
600     while (src[i])                                                      \
601         i++
602
603 #if HAVE_FAST_64BIT
604     for (i = 0; i + 1 < length; i += 9) {
605         if (!((~AV_RN64A(src + i) &
606                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
607               0x8000800080008080ULL))
608             continue;
609         FIND_FIRST_ZERO;
610         STARTCODE_TEST;
611         i -= 7;
612     }
613 #else
614     for (i = 0; i + 1 < length; i += 5) {
615         if (!((~AV_RN32A(src + i) &
616                (AV_RN32A(src + i) - 0x01000101U)) &
617               0x80008080U))
618             continue;
619         FIND_FIRST_ZERO;
620         STARTCODE_TEST;
621         i -= 3;
622     }
623 #endif
624 #else
625     for (i = 0; i + 1 < length; i += 2) {
626         if (src[i])
627             continue;
628         if (i > 0 && src[i - 1] == 0)
629             i--;
630         STARTCODE_TEST;
631     }
632 #endif
633
634     if (i >= length - 1) { // no escaped 0
635         *dst_length = length;
636         *consumed   = length + 1; // +1 for the header
637         return src;
638     }
639
640     // use second escape buffer for inter data
641     bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
642     av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
643                    length + FF_INPUT_BUFFER_PADDING_SIZE);
644     dst = h->rbsp_buffer[bufidx];
645
646     if (dst == NULL)
647         return NULL;
648
649     memcpy(dst, src, i);
650     si = di = i;
651     while (si + 2 < length) {
652         // remove escapes (very rare 1:2^22)
653         if (src[si + 2] > 3) {
654             dst[di++] = src[si++];
655             dst[di++] = src[si++];
656         } else if (src[si] == 0 && src[si + 1] == 0) {
657             if (src[si + 2] == 3) { // escape
658                 dst[di++]  = 0;
659                 dst[di++]  = 0;
660                 si        += 3;
661                 continue;
662             } else // next start code
663                 goto nsc;
664         }
665
666         dst[di++] = src[si++];
667     }
668     while (si < length)
669         dst[di++] = src[si++];
670
671 nsc:
672     memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
673
674     *dst_length = di;
675     *consumed   = si + 1; // +1 for the header
676     /* FIXME store exact number of bits in the getbitcontext
677      * (it is needed for decoding) */
678     return dst;
679 }
680
681 /**
682  * Identify the exact end of the bitstream
683  * @return the length of the trailing, or 0 if damaged
684  */
685 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
686 {
687     int v = *src;
688     int r;
689
690     tprintf(h->avctx, "rbsp trailing %X\n", v);
691
692     for (r = 1; r < 9; r++) {
693         if (v & 1)
694             return r;
695         v >>= 1;
696     }
697     return 0;
698 }
699
700 static inline int get_lowest_part_list_y(H264Context *h, H264Picture *pic, int n,
701                                          int height, int y_offset, int list)
702 {
703     int raw_my             = h->mv_cache[list][scan8[n]][1];
704     int filter_height_up   = (raw_my & 3) ? 2 : 0;
705     int filter_height_down = (raw_my & 3) ? 3 : 0;
706     int full_my            = (raw_my >> 2) + y_offset;
707     int top                = full_my - filter_height_up;
708     int bottom             = full_my + filter_height_down + height;
709
710     return FFMAX(abs(top), bottom);
711 }
712
713 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
714                                      int height, int y_offset, int list0,
715                                      int list1, int *nrefs)
716 {
717     int my;
718
719     y_offset += 16 * (h->mb_y >> MB_FIELD(h));
720
721     if (list0) {
722         int ref_n = h->ref_cache[0][scan8[n]];
723         H264Picture *ref = &h->ref_list[0][ref_n];
724
725         // Error resilience puts the current picture in the ref list.
726         // Don't try to wait on these as it will cause a deadlock.
727         // Fields can wait on each other, though.
728         if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
729             (ref->reference & 3) != h->picture_structure) {
730             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
731             if (refs[0][ref_n] < 0)
732                 nrefs[0] += 1;
733             refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
734         }
735     }
736
737     if (list1) {
738         int ref_n    = h->ref_cache[1][scan8[n]];
739         H264Picture *ref = &h->ref_list[1][ref_n];
740
741         if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
742             (ref->reference & 3) != h->picture_structure) {
743             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
744             if (refs[1][ref_n] < 0)
745                 nrefs[1] += 1;
746             refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
747         }
748     }
749 }
750
751 /**
752  * Wait until all reference frames are available for MC operations.
753  *
754  * @param h the H264 context
755  */
756 static void await_references(H264Context *h)
757 {
758     const int mb_xy   = h->mb_xy;
759     const int mb_type = h->cur_pic.mb_type[mb_xy];
760     int refs[2][48];
761     int nrefs[2] = { 0 };
762     int ref, list;
763
764     memset(refs, -1, sizeof(refs));
765
766     if (IS_16X16(mb_type)) {
767         get_lowest_part_y(h, refs, 0, 16, 0,
768                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
769     } else if (IS_16X8(mb_type)) {
770         get_lowest_part_y(h, refs, 0, 8, 0,
771                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
772         get_lowest_part_y(h, refs, 8, 8, 8,
773                           IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
774     } else if (IS_8X16(mb_type)) {
775         get_lowest_part_y(h, refs, 0, 16, 0,
776                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
777         get_lowest_part_y(h, refs, 4, 16, 0,
778                           IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
779     } else {
780         int i;
781
782         assert(IS_8X8(mb_type));
783
784         for (i = 0; i < 4; i++) {
785             const int sub_mb_type = h->sub_mb_type[i];
786             const int n           = 4 * i;
787             int y_offset          = (i & 2) << 2;
788
789             if (IS_SUB_8X8(sub_mb_type)) {
790                 get_lowest_part_y(h, refs, n, 8, y_offset,
791                                   IS_DIR(sub_mb_type, 0, 0),
792                                   IS_DIR(sub_mb_type, 0, 1),
793                                   nrefs);
794             } else if (IS_SUB_8X4(sub_mb_type)) {
795                 get_lowest_part_y(h, refs, n, 4, y_offset,
796                                   IS_DIR(sub_mb_type, 0, 0),
797                                   IS_DIR(sub_mb_type, 0, 1),
798                                   nrefs);
799                 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
800                                   IS_DIR(sub_mb_type, 0, 0),
801                                   IS_DIR(sub_mb_type, 0, 1),
802                                   nrefs);
803             } else if (IS_SUB_4X8(sub_mb_type)) {
804                 get_lowest_part_y(h, refs, n, 8, y_offset,
805                                   IS_DIR(sub_mb_type, 0, 0),
806                                   IS_DIR(sub_mb_type, 0, 1),
807                                   nrefs);
808                 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
809                                   IS_DIR(sub_mb_type, 0, 0),
810                                   IS_DIR(sub_mb_type, 0, 1),
811                                   nrefs);
812             } else {
813                 int j;
814                 assert(IS_SUB_4X4(sub_mb_type));
815                 for (j = 0; j < 4; j++) {
816                     int sub_y_offset = y_offset + 2 * (j & 2);
817                     get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
818                                       IS_DIR(sub_mb_type, 0, 0),
819                                       IS_DIR(sub_mb_type, 0, 1),
820                                       nrefs);
821                 }
822             }
823         }
824     }
825
826     for (list = h->list_count - 1; list >= 0; list--)
827         for (ref = 0; ref < 48 && nrefs[list]; ref++) {
828             int row = refs[list][ref];
829             if (row >= 0) {
830                 H264Picture *ref_pic  = &h->ref_list[list][ref];
831                 int ref_field         = ref_pic->reference - 1;
832                 int ref_field_picture = ref_pic->field_picture;
833                 int pic_height        = 16 * h->mb_height >> ref_field_picture;
834
835                 row <<= MB_MBAFF(h);
836                 nrefs[list]--;
837
838                 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
839                     ff_thread_await_progress(&ref_pic->tf,
840                                              FFMIN((row >> 1) - !(row & 1),
841                                                    pic_height - 1),
842                                              1);
843                     ff_thread_await_progress(&ref_pic->tf,
844                                              FFMIN((row >> 1), pic_height - 1),
845                                              0);
846                 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
847                     ff_thread_await_progress(&ref_pic->tf,
848                                              FFMIN(row * 2 + ref_field,
849                                                    pic_height - 1),
850                                              0);
851                 } else if (FIELD_PICTURE(h)) {
852                     ff_thread_await_progress(&ref_pic->tf,
853                                              FFMIN(row, pic_height - 1),
854                                              ref_field);
855                 } else {
856                     ff_thread_await_progress(&ref_pic->tf,
857                                              FFMIN(row, pic_height - 1),
858                                              0);
859                 }
860             }
861         }
862 }
863
864 static av_always_inline void mc_dir_part(H264Context *h, H264Picture *pic,
865                                          int n, int square, int height,
866                                          int delta, int list,
867                                          uint8_t *dest_y, uint8_t *dest_cb,
868                                          uint8_t *dest_cr,
869                                          int src_x_offset, int src_y_offset,
870                                          qpel_mc_func *qpix_op,
871                                          h264_chroma_mc_func chroma_op,
872                                          int pixel_shift, int chroma_idc)
873 {
874     const int mx      = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
875     int my            = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
876     const int luma_xy = (mx & 3) + ((my & 3) << 2);
877     ptrdiff_t offset  = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
878     uint8_t *src_y    = pic->f.data[0] + offset;
879     uint8_t *src_cb, *src_cr;
880     int extra_width  = 0;
881     int extra_height = 0;
882     int emu = 0;
883     const int full_mx    = mx >> 2;
884     const int full_my    = my >> 2;
885     const int pic_width  = 16 * h->mb_width;
886     const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
887     int ysh;
888
889     if (mx & 7)
890         extra_width -= 3;
891     if (my & 7)
892         extra_height -= 3;
893
894     if (full_mx                <          0 - extra_width  ||
895         full_my                <          0 - extra_height ||
896         full_mx + 16 /*FIXME*/ > pic_width  + extra_width  ||
897         full_my + 16 /*FIXME*/ > pic_height + extra_height) {
898         h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
899                                  src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
900                                  h->mb_linesize, h->mb_linesize,
901                                  16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
902                                  full_my - 2, pic_width, pic_height);
903         src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
904         emu   = 1;
905     }
906
907     qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
908     if (!square)
909         qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
910
911     if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
912         return;
913
914     if (chroma_idc == 3 /* yuv444 */) {
915         src_cb = pic->f.data[1] + offset;
916         if (emu) {
917             h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
918                                      src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
919                                      h->mb_linesize, h->mb_linesize,
920                                      16 + 5, 16 + 5 /*FIXME*/,
921                                      full_mx - 2, full_my - 2,
922                                      pic_width, pic_height);
923             src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
924         }
925         qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
926         if (!square)
927             qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
928
929         src_cr = pic->f.data[2] + offset;
930         if (emu) {
931             h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
932                                      src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
933                                      h->mb_linesize, h->mb_linesize,
934                                      16 + 5, 16 + 5 /*FIXME*/,
935                                      full_mx - 2, full_my - 2,
936                                      pic_width, pic_height);
937             src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
938         }
939         qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
940         if (!square)
941             qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
942         return;
943     }
944
945     ysh = 3 - (chroma_idc == 2 /* yuv422 */);
946     if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
947         // chroma offset when predicting from a field of opposite parity
948         my  += 2 * ((h->mb_y & 1) - (pic->reference - 1));
949         emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
950     }
951
952     src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
953              (my >> ysh) * h->mb_uvlinesize;
954     src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
955              (my >> ysh) * h->mb_uvlinesize;
956
957     if (emu) {
958         h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
959                                  h->mb_uvlinesize, h->mb_uvlinesize,
960                                  9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
961                                  pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
962         src_cb = h->edge_emu_buffer;
963     }
964     chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
965               height >> (chroma_idc == 1 /* yuv420 */),
966               mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
967
968     if (emu) {
969         h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
970                                  h->mb_uvlinesize, h->mb_uvlinesize,
971                                  9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
972                                  pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
973         src_cr = h->edge_emu_buffer;
974     }
975     chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
976               mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
977 }
978
979 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
980                                          int height, int delta,
981                                          uint8_t *dest_y, uint8_t *dest_cb,
982                                          uint8_t *dest_cr,
983                                          int x_offset, int y_offset,
984                                          qpel_mc_func *qpix_put,
985                                          h264_chroma_mc_func chroma_put,
986                                          qpel_mc_func *qpix_avg,
987                                          h264_chroma_mc_func chroma_avg,
988                                          int list0, int list1,
989                                          int pixel_shift, int chroma_idc)
990 {
991     qpel_mc_func *qpix_op         = qpix_put;
992     h264_chroma_mc_func chroma_op = chroma_put;
993
994     dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
995     if (chroma_idc == 3 /* yuv444 */) {
996         dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
997         dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
998     } else if (chroma_idc == 2 /* yuv422 */) {
999         dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1000         dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1001     } else { /* yuv420 */
1002         dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1003         dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1004     }
1005     x_offset += 8 * h->mb_x;
1006     y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1007
1008     if (list0) {
1009         H264Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1010         mc_dir_part(h, ref, n, square, height, delta, 0,
1011                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
1012                     qpix_op, chroma_op, pixel_shift, chroma_idc);
1013
1014         qpix_op   = qpix_avg;
1015         chroma_op = chroma_avg;
1016     }
1017
1018     if (list1) {
1019         H264Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1020         mc_dir_part(h, ref, n, square, height, delta, 1,
1021                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
1022                     qpix_op, chroma_op, pixel_shift, chroma_idc);
1023     }
1024 }
1025
1026 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1027                                               int height, int delta,
1028                                               uint8_t *dest_y, uint8_t *dest_cb,
1029                                               uint8_t *dest_cr,
1030                                               int x_offset, int y_offset,
1031                                               qpel_mc_func *qpix_put,
1032                                               h264_chroma_mc_func chroma_put,
1033                                               h264_weight_func luma_weight_op,
1034                                               h264_weight_func chroma_weight_op,
1035                                               h264_biweight_func luma_weight_avg,
1036                                               h264_biweight_func chroma_weight_avg,
1037                                               int list0, int list1,
1038                                               int pixel_shift, int chroma_idc)
1039 {
1040     int chroma_height;
1041
1042     dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1043     if (chroma_idc == 3 /* yuv444 */) {
1044         chroma_height     = height;
1045         chroma_weight_avg = luma_weight_avg;
1046         chroma_weight_op  = luma_weight_op;
1047         dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1048         dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1049     } else if (chroma_idc == 2 /* yuv422 */) {
1050         chroma_height = height;
1051         dest_cb      += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1052         dest_cr      += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1053     } else { /* yuv420 */
1054         chroma_height = height >> 1;
1055         dest_cb      += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1056         dest_cr      += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1057     }
1058     x_offset += 8 * h->mb_x;
1059     y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1060
1061     if (list0 && list1) {
1062         /* don't optimize for luma-only case, since B-frames usually
1063          * use implicit weights => chroma too. */
1064         uint8_t *tmp_cb = h->bipred_scratchpad;
1065         uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1066         uint8_t *tmp_y  = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1067         int refn0       = h->ref_cache[0][scan8[n]];
1068         int refn1       = h->ref_cache[1][scan8[n]];
1069
1070         mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1071                     dest_y, dest_cb, dest_cr,
1072                     x_offset, y_offset, qpix_put, chroma_put,
1073                     pixel_shift, chroma_idc);
1074         mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1075                     tmp_y, tmp_cb, tmp_cr,
1076                     x_offset, y_offset, qpix_put, chroma_put,
1077                     pixel_shift, chroma_idc);
1078
1079         if (h->use_weight == 2) {
1080             int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1081             int weight1 = 64 - weight0;
1082             luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1083                             height, 5, weight0, weight1, 0);
1084             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1085                               chroma_height, 5, weight0, weight1, 0);
1086             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1087                               chroma_height, 5, weight0, weight1, 0);
1088         } else {
1089             luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1090                             h->luma_log2_weight_denom,
1091                             h->luma_weight[refn0][0][0],
1092                             h->luma_weight[refn1][1][0],
1093                             h->luma_weight[refn0][0][1] +
1094                             h->luma_weight[refn1][1][1]);
1095             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1096                               h->chroma_log2_weight_denom,
1097                               h->chroma_weight[refn0][0][0][0],
1098                               h->chroma_weight[refn1][1][0][0],
1099                               h->chroma_weight[refn0][0][0][1] +
1100                               h->chroma_weight[refn1][1][0][1]);
1101             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1102                               h->chroma_log2_weight_denom,
1103                               h->chroma_weight[refn0][0][1][0],
1104                               h->chroma_weight[refn1][1][1][0],
1105                               h->chroma_weight[refn0][0][1][1] +
1106                               h->chroma_weight[refn1][1][1][1]);
1107         }
1108     } else {
1109         int list     = list1 ? 1 : 0;
1110         int refn     = h->ref_cache[list][scan8[n]];
1111         H264Picture *ref = &h->ref_list[list][refn];
1112         mc_dir_part(h, ref, n, square, height, delta, list,
1113                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
1114                     qpix_put, chroma_put, pixel_shift, chroma_idc);
1115
1116         luma_weight_op(dest_y, h->mb_linesize, height,
1117                        h->luma_log2_weight_denom,
1118                        h->luma_weight[refn][list][0],
1119                        h->luma_weight[refn][list][1]);
1120         if (h->use_weight_chroma) {
1121             chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1122                              h->chroma_log2_weight_denom,
1123                              h->chroma_weight[refn][list][0][0],
1124                              h->chroma_weight[refn][list][0][1]);
1125             chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1126                              h->chroma_log2_weight_denom,
1127                              h->chroma_weight[refn][list][1][0],
1128                              h->chroma_weight[refn][list][1][1]);
1129         }
1130     }
1131 }
1132
1133 static av_always_inline void prefetch_motion(H264Context *h, int list,
1134                                              int pixel_shift, int chroma_idc)
1135 {
1136     /* fetch pixels for estimated mv 4 macroblocks ahead
1137      * optimized for 64byte cache lines */
1138     const int refn = h->ref_cache[list][scan8[0]];
1139     if (refn >= 0) {
1140         const int mx  = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1141         const int my  = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1142         uint8_t **src = h->ref_list[list][refn].f.data;
1143         int off       = (mx << pixel_shift) +
1144                         (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1145                         (64 << pixel_shift);
1146         h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1147         if (chroma_idc == 3 /* yuv444 */) {
1148             h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1149             h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1150         } else {
1151             off = ((mx >> 1) << pixel_shift) +
1152                   ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
1153                   (64 << pixel_shift);
1154             h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1155         }
1156     }
1157 }
1158
1159 static void free_tables(H264Context *h, int free_rbsp)
1160 {
1161     int i;
1162     H264Context *hx;
1163
1164     av_freep(&h->intra4x4_pred_mode);
1165     av_freep(&h->chroma_pred_mode_table);
1166     av_freep(&h->cbp_table);
1167     av_freep(&h->mvd_table[0]);
1168     av_freep(&h->mvd_table[1]);
1169     av_freep(&h->direct_table);
1170     av_freep(&h->non_zero_count);
1171     av_freep(&h->slice_table_base);
1172     h->slice_table = NULL;
1173     av_freep(&h->list_counts);
1174
1175     av_freep(&h->mb2b_xy);
1176     av_freep(&h->mb2br_xy);
1177
1178     av_buffer_pool_uninit(&h->qscale_table_pool);
1179     av_buffer_pool_uninit(&h->mb_type_pool);
1180     av_buffer_pool_uninit(&h->motion_val_pool);
1181     av_buffer_pool_uninit(&h->ref_index_pool);
1182
1183     if (free_rbsp && h->DPB) {
1184         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1185             unref_picture(h, &h->DPB[i]);
1186         av_freep(&h->DPB);
1187     } else if (h->DPB) {
1188         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1189             h->DPB[i].needs_realloc = 1;
1190     }
1191
1192     h->cur_pic_ptr = NULL;
1193
1194     for (i = 0; i < H264_MAX_THREADS; i++) {
1195         hx = h->thread_context[i];
1196         if (!hx)
1197             continue;
1198         av_freep(&hx->top_borders[1]);
1199         av_freep(&hx->top_borders[0]);
1200         av_freep(&hx->bipred_scratchpad);
1201         av_freep(&hx->edge_emu_buffer);
1202         av_freep(&hx->dc_val_base);
1203         av_freep(&hx->er.mb_index2xy);
1204         av_freep(&hx->er.error_status_table);
1205         av_freep(&hx->er.er_temp_buffer);
1206         av_freep(&hx->er.mbintra_table);
1207         av_freep(&hx->er.mbskip_table);
1208
1209         if (free_rbsp) {
1210             av_freep(&hx->rbsp_buffer[1]);
1211             av_freep(&hx->rbsp_buffer[0]);
1212             hx->rbsp_buffer_size[0] = 0;
1213             hx->rbsp_buffer_size[1] = 0;
1214         }
1215         if (i)
1216             av_freep(&h->thread_context[i]);
1217     }
1218 }
1219
1220 static void init_dequant8_coeff_table(H264Context *h)
1221 {
1222     int i, j, q, x;
1223     const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1224
1225     for (i = 0; i < 6; i++) {
1226         h->dequant8_coeff[i] = h->dequant8_buffer[i];
1227         for (j = 0; j < i; j++)
1228             if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1229                         64 * sizeof(uint8_t))) {
1230                 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1231                 break;
1232             }
1233         if (j < i)
1234             continue;
1235
1236         for (q = 0; q < max_qp + 1; q++) {
1237             int shift = div6[q];
1238             int idx   = rem6[q];
1239             for (x = 0; x < 64; x++)
1240                 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1241                     ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1242                      h->pps.scaling_matrix8[i][x]) << shift;
1243         }
1244     }
1245 }
1246
1247 static void init_dequant4_coeff_table(H264Context *h)
1248 {
1249     int i, j, q, x;
1250     const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1251     for (i = 0; i < 6; i++) {
1252         h->dequant4_coeff[i] = h->dequant4_buffer[i];
1253         for (j = 0; j < i; j++)
1254             if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1255                         16 * sizeof(uint8_t))) {
1256                 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1257                 break;
1258             }
1259         if (j < i)
1260             continue;
1261
1262         for (q = 0; q < max_qp + 1; q++) {
1263             int shift = div6[q] + 2;
1264             int idx   = rem6[q];
1265             for (x = 0; x < 16; x++)
1266                 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1267                     ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1268                      h->pps.scaling_matrix4[i][x]) << shift;
1269         }
1270     }
1271 }
1272
1273 static void init_dequant_tables(H264Context *h)
1274 {
1275     int i, x;
1276     init_dequant4_coeff_table(h);
1277     if (h->pps.transform_8x8_mode)
1278         init_dequant8_coeff_table(h);
1279     if (h->sps.transform_bypass) {
1280         for (i = 0; i < 6; i++)
1281             for (x = 0; x < 16; x++)
1282                 h->dequant4_coeff[i][0][x] = 1 << 6;
1283         if (h->pps.transform_8x8_mode)
1284             for (i = 0; i < 6; i++)
1285                 for (x = 0; x < 64; x++)
1286                     h->dequant8_coeff[i][0][x] = 1 << 6;
1287     }
1288 }
1289
1290 int ff_h264_alloc_tables(H264Context *h)
1291 {
1292     const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1293     const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
1294     int x, y, i;
1295
1296     FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1297                       row_mb_num * 8 * sizeof(uint8_t), fail)
1298     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1299                       big_mb_num * 48 * sizeof(uint8_t), fail)
1300     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1301                       (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1302     FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1303                       big_mb_num * sizeof(uint16_t), fail)
1304     FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1305                       big_mb_num * sizeof(uint8_t), fail)
1306     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1307                       16 * row_mb_num * sizeof(uint8_t), fail);
1308     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1309                       16 * row_mb_num * sizeof(uint8_t), fail);
1310     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1311                       4 * big_mb_num * sizeof(uint8_t), fail);
1312     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1313                       big_mb_num * sizeof(uint8_t), fail)
1314
1315     memset(h->slice_table_base, -1,
1316            (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1317     h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1318
1319     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1320                       big_mb_num * sizeof(uint32_t), fail);
1321     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1322                       big_mb_num * sizeof(uint32_t), fail);
1323     for (y = 0; y < h->mb_height; y++)
1324         for (x = 0; x < h->mb_width; x++) {
1325             const int mb_xy = x + y * h->mb_stride;
1326             const int b_xy  = 4 * x + 4 * y * h->b_stride;
1327
1328             h->mb2b_xy[mb_xy]  = b_xy;
1329             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1330         }
1331
1332     if (!h->dequant4_coeff[0])
1333         init_dequant_tables(h);
1334
1335     if (!h->DPB) {
1336         h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
1337         if (!h->DPB)
1338             return AVERROR(ENOMEM);
1339         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1340             av_frame_unref(&h->DPB[i].f);
1341         av_frame_unref(&h->cur_pic.f);
1342     }
1343
1344     return 0;
1345
1346 fail:
1347     free_tables(h, 1);
1348     return AVERROR(ENOMEM);
1349 }
1350
1351 /**
1352  * Mimic alloc_tables(), but for every context thread.
1353  */
1354 static void clone_tables(H264Context *dst, H264Context *src, int i)
1355 {
1356     dst->intra4x4_pred_mode     = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1357     dst->non_zero_count         = src->non_zero_count;
1358     dst->slice_table            = src->slice_table;
1359     dst->cbp_table              = src->cbp_table;
1360     dst->mb2b_xy                = src->mb2b_xy;
1361     dst->mb2br_xy               = src->mb2br_xy;
1362     dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1363     dst->mvd_table[0]           = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1364     dst->mvd_table[1]           = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1365     dst->direct_table           = src->direct_table;
1366     dst->list_counts            = src->list_counts;
1367     dst->DPB                    = src->DPB;
1368     dst->cur_pic_ptr            = src->cur_pic_ptr;
1369     dst->cur_pic                = src->cur_pic;
1370     dst->bipred_scratchpad      = NULL;
1371     dst->edge_emu_buffer        = NULL;
1372     ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1373                       src->sps.chroma_format_idc);
1374 }
1375
1376 /**
1377  * Init context
1378  * Allocate buffers which are not shared amongst multiple threads.
1379  */
1380 static int context_init(H264Context *h)
1381 {
1382     ERContext *er = &h->er;
1383     int mb_array_size = h->mb_height * h->mb_stride;
1384     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1385     int c_size  = h->mb_stride * (h->mb_height + 1);
1386     int yc_size = y_size + 2   * c_size;
1387     int x, y, i;
1388
1389     FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1390                       h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1391     FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1392                       h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1393
1394     h->ref_cache[0][scan8[5]  + 1] =
1395     h->ref_cache[0][scan8[7]  + 1] =
1396     h->ref_cache[0][scan8[13] + 1] =
1397     h->ref_cache[1][scan8[5]  + 1] =
1398     h->ref_cache[1][scan8[7]  + 1] =
1399     h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1400
1401     if (CONFIG_ERROR_RESILIENCE) {
1402         /* init ER */
1403         er->avctx          = h->avctx;
1404         er->dsp            = &h->dsp;
1405         er->decode_mb      = h264_er_decode_mb;
1406         er->opaque         = h;
1407         er->quarter_sample = 1;
1408
1409         er->mb_num      = h->mb_num;
1410         er->mb_width    = h->mb_width;
1411         er->mb_height   = h->mb_height;
1412         er->mb_stride   = h->mb_stride;
1413         er->b8_stride   = h->mb_width * 2 + 1;
1414
1415         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1416                           fail); // error ressilience code looks cleaner with this
1417         for (y = 0; y < h->mb_height; y++)
1418             for (x = 0; x < h->mb_width; x++)
1419                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1420
1421         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1422                                                       h->mb_stride + h->mb_width;
1423
1424         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1425                           mb_array_size * sizeof(uint8_t), fail);
1426
1427         FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1428         memset(er->mbintra_table, 1, mb_array_size);
1429
1430         FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1431
1432         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1433                          fail);
1434
1435         FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1436         er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1437         er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1438         er->dc_val[2] = er->dc_val[1] + c_size;
1439         for (i = 0; i < yc_size; i++)
1440             h->dc_val_base[i] = 1024;
1441     }
1442
1443     return 0;
1444
1445 fail:
1446     return AVERROR(ENOMEM); // free_tables will clean up for us
1447 }
1448
1449 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1450                             int parse_extradata);
1451
1452 int ff_h264_decode_extradata(H264Context *h)
1453 {
1454     AVCodecContext *avctx = h->avctx;
1455     int ret;
1456
1457     if (avctx->extradata[0] == 1) {
1458         int i, cnt, nalsize;
1459         unsigned char *p = avctx->extradata;
1460
1461         h->is_avc = 1;
1462
1463         if (avctx->extradata_size < 7) {
1464             av_log(avctx, AV_LOG_ERROR,
1465                    "avcC %d too short\n", avctx->extradata_size);
1466             return AVERROR_INVALIDDATA;
1467         }
1468         /* sps and pps in the avcC always have length coded with 2 bytes,
1469          * so put a fake nal_length_size = 2 while parsing them */
1470         h->nal_length_size = 2;
1471         // Decode sps from avcC
1472         cnt = *(p + 5) & 0x1f; // Number of sps
1473         p  += 6;
1474         for (i = 0; i < cnt; i++) {
1475             nalsize = AV_RB16(p) + 2;
1476             if (p - avctx->extradata + nalsize > avctx->extradata_size)
1477                 return AVERROR_INVALIDDATA;
1478             ret = decode_nal_units(h, p, nalsize, 1);
1479             if (ret < 0) {
1480                 av_log(avctx, AV_LOG_ERROR,
1481                        "Decoding sps %d from avcC failed\n", i);
1482                 return ret;
1483             }
1484             p += nalsize;
1485         }
1486         // Decode pps from avcC
1487         cnt = *(p++); // Number of pps
1488         for (i = 0; i < cnt; i++) {
1489             nalsize = AV_RB16(p) + 2;
1490             if (p - avctx->extradata + nalsize > avctx->extradata_size)
1491                 return AVERROR_INVALIDDATA;
1492             ret = decode_nal_units(h, p, nalsize, 1);
1493             if (ret < 0) {
1494                 av_log(avctx, AV_LOG_ERROR,
1495                        "Decoding pps %d from avcC failed\n", i);
1496                 return ret;
1497             }
1498             p += nalsize;
1499         }
1500         // Now store right nal length size, that will be used to parse all other nals
1501         h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1502     } else {
1503         h->is_avc = 0;
1504         ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
1505         if (ret < 0)
1506             return ret;
1507     }
1508     return 0;
1509 }
1510
1511 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1512 {
1513     H264Context *h = avctx->priv_data;
1514     int i;
1515     int ret;
1516
1517     h->avctx = avctx;
1518
1519     h->bit_depth_luma    = 8;
1520     h->chroma_format_idc = 1;
1521
1522     ff_h264dsp_init(&h->h264dsp, 8, 1);
1523     ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1524     ff_h264qpel_init(&h->h264qpel, 8);
1525     ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1526
1527     h->dequant_coeff_pps = -1;
1528
1529     /* needed so that IDCT permutation is known early */
1530     if (CONFIG_ERROR_RESILIENCE)
1531         ff_dsputil_init(&h->dsp, h->avctx);
1532     ff_videodsp_init(&h->vdsp, 8);
1533
1534     memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1535     memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1536
1537     h->picture_structure   = PICT_FRAME;
1538     h->slice_context_count = 1;
1539     h->workaround_bugs     = avctx->workaround_bugs;
1540     h->flags               = avctx->flags;
1541
1542     /* set defaults */
1543     // s->decode_mb = ff_h263_decode_mb;
1544     if (!avctx->has_b_frames)
1545         h->low_delay = 1;
1546
1547     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1548
1549     ff_h264_decode_init_vlc();
1550
1551     ff_init_cabac_states();
1552
1553     h->pixel_shift        = 0;
1554     h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1555
1556     h->thread_context[0] = h;
1557     h->outputed_poc      = h->next_outputed_poc = INT_MIN;
1558     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1559         h->last_pocs[i] = INT_MIN;
1560     h->prev_poc_msb = 1 << 16;
1561     h->x264_build   = -1;
1562     ff_h264_reset_sei(h);
1563     h->recovery_frame = -1;
1564     h->frame_recovered = 0;
1565     if (avctx->codec_id == AV_CODEC_ID_H264) {
1566         if (avctx->ticks_per_frame == 1)
1567             h->avctx->time_base.den *= 2;
1568         avctx->ticks_per_frame = 2;
1569     }
1570
1571     if (avctx->extradata_size > 0 && avctx->extradata) {
1572        ret = ff_h264_decode_extradata(h);
1573        if (ret < 0)
1574            return ret;
1575     }
1576
1577     if (h->sps.bitstream_restriction_flag &&
1578         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1579         h->avctx->has_b_frames = h->sps.num_reorder_frames;
1580         h->low_delay           = 0;
1581     }
1582
1583     avctx->internal->allocate_progress = 1;
1584
1585     return 0;
1586 }
1587
1588 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1589 #undef REBASE_PICTURE
1590 #define REBASE_PICTURE(pic, new_ctx, old_ctx)             \
1591     ((pic && pic >= old_ctx->DPB &&                       \
1592       pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ?           \
1593      &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1594
1595 static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
1596                                H264Context *new_base,
1597                                H264Context *old_base)
1598 {
1599     int i;
1600
1601     for (i = 0; i < count; i++) {
1602         assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1603                 IN_RANGE(from[i], old_base->DPB,
1604                          sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
1605                 !from[i]));
1606         to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1607     }
1608 }
1609
1610 static int copy_parameter_set(void **to, void **from, int count, int size)
1611 {
1612     int i;
1613
1614     for (i = 0; i < count; i++) {
1615         if (to[i] && !from[i]) {
1616             av_freep(&to[i]);
1617         } else if (from[i] && !to[i]) {
1618             to[i] = av_malloc(size);
1619             if (!to[i])
1620                 return AVERROR(ENOMEM);
1621         }
1622
1623         if (from[i])
1624             memcpy(to[i], from[i], size);
1625     }
1626
1627     return 0;
1628 }
1629
1630 static int decode_init_thread_copy(AVCodecContext *avctx)
1631 {
1632     H264Context *h = avctx->priv_data;
1633
1634     if (!avctx->internal->is_copy)
1635         return 0;
1636     memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1637     memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1638
1639     h->context_initialized = 0;
1640
1641     return 0;
1642 }
1643
1644 #define copy_fields(to, from, start_field, end_field)                   \
1645     memcpy(&to->start_field, &from->start_field,                        \
1646            (char *)&to->end_field - (char *)&to->start_field)
1647
1648 static int h264_slice_header_init(H264Context *, int);
1649
1650 static int h264_set_parameter_from_sps(H264Context *h);
1651
1652 static int decode_update_thread_context(AVCodecContext *dst,
1653                                         const AVCodecContext *src)
1654 {
1655     H264Context *h = dst->priv_data, *h1 = src->priv_data;
1656     int inited = h->context_initialized, err = 0;
1657     int context_reinitialized = 0;
1658     int i, ret;
1659
1660     if (dst == src || !h1->context_initialized)
1661         return 0;
1662
1663     if (inited &&
1664         (h->width                 != h1->width                 ||
1665          h->height                != h1->height                ||
1666          h->mb_width              != h1->mb_width              ||
1667          h->mb_height             != h1->mb_height             ||
1668          h->sps.bit_depth_luma    != h1->sps.bit_depth_luma    ||
1669          h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1670          h->sps.colorspace        != h1->sps.colorspace)) {
1671
1672         /* set bits_per_raw_sample to the previous value. the check for changed
1673          * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1674          * the current value */
1675         h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1676
1677         av_freep(&h->bipred_scratchpad);
1678
1679         h->width     = h1->width;
1680         h->height    = h1->height;
1681         h->mb_height = h1->mb_height;
1682         h->mb_width  = h1->mb_width;
1683         h->mb_num    = h1->mb_num;
1684         h->mb_stride = h1->mb_stride;
1685         h->b_stride  = h1->b_stride;
1686
1687         if ((err = h264_slice_header_init(h, 1)) < 0) {
1688             av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1689             return err;
1690         }
1691         context_reinitialized = 1;
1692
1693         /* update linesize on resize. The decoder doesn't
1694          * necessarily call h264_frame_start in the new thread */
1695         h->linesize   = h1->linesize;
1696         h->uvlinesize = h1->uvlinesize;
1697
1698         /* copy block_offset since frame_start may not be called */
1699         memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1700     }
1701
1702     if (!inited) {
1703         for (i = 0; i < MAX_SPS_COUNT; i++)
1704             av_freep(h->sps_buffers + i);
1705
1706         for (i = 0; i < MAX_PPS_COUNT; i++)
1707             av_freep(h->pps_buffers + i);
1708
1709         memcpy(h, h1, sizeof(*h1));
1710         memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1711         memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1712         memset(&h->er, 0, sizeof(h->er));
1713         memset(&h->mb, 0, sizeof(h->mb));
1714         memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1715         memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1716         h->context_initialized = 0;
1717
1718         memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1719         av_frame_unref(&h->cur_pic.f);
1720         h->cur_pic.tf.f = &h->cur_pic.f;
1721
1722         h->avctx             = dst;
1723         h->DPB               = NULL;
1724         h->qscale_table_pool = NULL;
1725         h->mb_type_pool      = NULL;
1726         h->ref_index_pool    = NULL;
1727         h->motion_val_pool   = NULL;
1728
1729         ret = ff_h264_alloc_tables(h);
1730         if (ret < 0) {
1731             av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");
1732             return ret;
1733         }
1734         ret = context_init(h);
1735         if (ret < 0) {
1736             av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1737             return ret;
1738         }
1739
1740         for (i = 0; i < 2; i++) {
1741             h->rbsp_buffer[i]      = NULL;
1742             h->rbsp_buffer_size[i] = 0;
1743         }
1744         h->bipred_scratchpad = NULL;
1745         h->edge_emu_buffer   = NULL;
1746
1747         h->thread_context[0] = h;
1748
1749         h->context_initialized = 1;
1750     }
1751
1752     h->avctx->coded_height  = h1->avctx->coded_height;
1753     h->avctx->coded_width   = h1->avctx->coded_width;
1754     h->avctx->width         = h1->avctx->width;
1755     h->avctx->height        = h1->avctx->height;
1756     h->coded_picture_number = h1->coded_picture_number;
1757     h->first_field          = h1->first_field;
1758     h->picture_structure    = h1->picture_structure;
1759     h->qscale               = h1->qscale;
1760     h->droppable            = h1->droppable;
1761     h->low_delay            = h1->low_delay;
1762
1763     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1764         unref_picture(h, &h->DPB[i]);
1765         if (h1->DPB[i].f.buf[0] &&
1766             (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1767             return ret;
1768     }
1769
1770     h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1771     unref_picture(h, &h->cur_pic);
1772     if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1773         return ret;
1774
1775     h->workaround_bugs = h1->workaround_bugs;
1776     h->low_delay       = h1->low_delay;
1777     h->droppable       = h1->droppable;
1778
1779     /* frame_start may not be called for the next thread (if it's decoding
1780      * a bottom field) so this has to be allocated here */
1781     err = alloc_scratch_buffers(h, h1->linesize);
1782     if (err < 0)
1783         return err;
1784
1785     // extradata/NAL handling
1786     h->is_avc = h1->is_avc;
1787
1788     // SPS/PPS
1789     if ((ret = copy_parameter_set((void **)h->sps_buffers,
1790                                   (void **)h1->sps_buffers,
1791                                   MAX_SPS_COUNT, sizeof(SPS))) < 0)
1792         return ret;
1793     h->sps = h1->sps;
1794     if ((ret = copy_parameter_set((void **)h->pps_buffers,
1795                                   (void **)h1->pps_buffers,
1796                                   MAX_PPS_COUNT, sizeof(PPS))) < 0)
1797         return ret;
1798     h->pps = h1->pps;
1799
1800     // Dequantization matrices
1801     // FIXME these are big - can they be only copied when PPS changes?
1802     copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1803
1804     for (i = 0; i < 6; i++)
1805         h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1806                                (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1807
1808     for (i = 0; i < 6; i++)
1809         h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1810                                (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1811
1812     h->dequant_coeff_pps = h1->dequant_coeff_pps;
1813
1814     // POC timing
1815     copy_fields(h, h1, poc_lsb, redundant_pic_count);
1816
1817     // reference lists
1818     copy_fields(h, h1, short_ref, cabac_init_idc);
1819
1820     copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1821     copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1822     copy_picture_range(h->delayed_pic, h1->delayed_pic,
1823                        MAX_DELAYED_PIC_COUNT + 2, h, h1);
1824
1825     h->last_slice_type = h1->last_slice_type;
1826
1827     if (context_reinitialized)
1828         h264_set_parameter_from_sps(h);
1829
1830     if (!h->cur_pic_ptr)
1831         return 0;
1832
1833     if (!h->droppable) {
1834         err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1835         h->prev_poc_msb = h->poc_msb;
1836         h->prev_poc_lsb = h->poc_lsb;
1837     }
1838     h->prev_frame_num_offset = h->frame_num_offset;
1839     h->prev_frame_num        = h->frame_num;
1840     h->outputed_poc          = h->next_outputed_poc;
1841
1842     h->recovery_frame        = h1->recovery_frame;
1843     h->frame_recovered       = h1->frame_recovered;
1844
1845     return err;
1846 }
1847
1848 static int h264_frame_start(H264Context *h)
1849 {
1850     H264Picture *pic;
1851     int i, ret;
1852     const int pixel_shift = h->pixel_shift;
1853
1854     release_unused_pictures(h, 1);
1855     h->cur_pic_ptr = NULL;
1856
1857     i = find_unused_picture(h);
1858     if (i < 0) {
1859         av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1860         return i;
1861     }
1862     pic = &h->DPB[i];
1863
1864     pic->reference              = h->droppable ? 0 : h->picture_structure;
1865     pic->f.coded_picture_number = h->coded_picture_number++;
1866     pic->field_picture          = h->picture_structure != PICT_FRAME;
1867     /*
1868      * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1869      * in later.
1870      * See decode_nal_units().
1871      */
1872     pic->f.key_frame = 0;
1873     pic->mmco_reset  = 0;
1874     pic->recovered   = 0;
1875
1876     if ((ret = alloc_picture(h, pic)) < 0)
1877         return ret;
1878
1879     h->cur_pic_ptr = pic;
1880     unref_picture(h, &h->cur_pic);
1881     if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1882         return ret;
1883
1884     if (CONFIG_ERROR_RESILIENCE)
1885         ff_er_frame_start(&h->er);
1886
1887     assert(h->linesize && h->uvlinesize);
1888
1889     for (i = 0; i < 16; i++) {
1890         h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1891         h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1892     }
1893     for (i = 0; i < 16; i++) {
1894         h->block_offset[16 + i]      =
1895         h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1896         h->block_offset[48 + 16 + i] =
1897         h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1898     }
1899
1900     /* can't be in alloc_tables because linesize isn't known there.
1901      * FIXME: redo bipred weight to not require extra buffer? */
1902     for (i = 0; i < h->slice_context_count; i++)
1903         if (h->thread_context[i]) {
1904             ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1905             if (ret < 0)
1906                 return ret;
1907         }
1908
1909     /* Some macroblocks can be accessed before they're available in case
1910      * of lost slices, MBAFF or threading. */
1911     memset(h->slice_table, -1,
1912            (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1913
1914     // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1915     //             s->current_picture.f.reference /* || h->contains_intra */ || 1;
1916
1917     /* We mark the current picture as non-reference after allocating it, so
1918      * that if we break out due to an error it can be released automatically
1919      * in the next ff_MPV_frame_start().
1920      */
1921     h->cur_pic_ptr->reference = 0;
1922
1923     h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1924
1925     h->next_output_pic = NULL;
1926
1927     assert(h->cur_pic_ptr->long_ref == 0);
1928
1929     return 0;
1930 }
1931
1932 /**
1933  * Run setup operations that must be run after slice header decoding.
1934  * This includes finding the next displayed frame.
1935  *
1936  * @param h h264 master context
1937  * @param setup_finished enough NALs have been read that we can call
1938  * ff_thread_finish_setup()
1939  */
1940 static void decode_postinit(H264Context *h, int setup_finished)
1941 {
1942     H264Picture *out = h->cur_pic_ptr;
1943     H264Picture *cur = h->cur_pic_ptr;
1944     int i, pics, out_of_order, out_idx;
1945     int invalid = 0, cnt = 0;
1946
1947     h->cur_pic_ptr->f.pict_type = h->pict_type;
1948
1949     if (h->next_output_pic)
1950         return;
1951
1952     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1953         /* FIXME: if we have two PAFF fields in one packet, we can't start
1954          * the next thread here. If we have one field per packet, we can.
1955          * The check in decode_nal_units() is not good enough to find this
1956          * yet, so we assume the worst for now. */
1957         // if (setup_finished)
1958         //    ff_thread_finish_setup(h->avctx);
1959         return;
1960     }
1961
1962     cur->f.interlaced_frame = 0;
1963     cur->f.repeat_pict      = 0;
1964
1965     /* Signal interlacing information externally. */
1966     /* Prioritize picture timing SEI information over used
1967      * decoding process if it exists. */
1968
1969     if (h->sps.pic_struct_present_flag) {
1970         switch (h->sei_pic_struct) {
1971         case SEI_PIC_STRUCT_FRAME:
1972             break;
1973         case SEI_PIC_STRUCT_TOP_FIELD:
1974         case SEI_PIC_STRUCT_BOTTOM_FIELD:
1975             cur->f.interlaced_frame = 1;
1976             break;
1977         case SEI_PIC_STRUCT_TOP_BOTTOM:
1978         case SEI_PIC_STRUCT_BOTTOM_TOP:
1979             if (FIELD_OR_MBAFF_PICTURE(h))
1980                 cur->f.interlaced_frame = 1;
1981             else
1982                 // try to flag soft telecine progressive
1983                 cur->f.interlaced_frame = h->prev_interlaced_frame;
1984             break;
1985         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1986         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1987             /* Signal the possibility of telecined film externally
1988              * (pic_struct 5,6). From these hints, let the applications
1989              * decide if they apply deinterlacing. */
1990             cur->f.repeat_pict = 1;
1991             break;
1992         case SEI_PIC_STRUCT_FRAME_DOUBLING:
1993             cur->f.repeat_pict = 2;
1994             break;
1995         case SEI_PIC_STRUCT_FRAME_TRIPLING:
1996             cur->f.repeat_pict = 4;
1997             break;
1998         }
1999
2000         if ((h->sei_ct_type & 3) &&
2001             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2002             cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2003     } else {
2004         /* Derive interlacing flag from used decoding process. */
2005         cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2006     }
2007     h->prev_interlaced_frame = cur->f.interlaced_frame;
2008
2009     if (cur->field_poc[0] != cur->field_poc[1]) {
2010         /* Derive top_field_first from field pocs. */
2011         cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2012     } else {
2013         if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2014             /* Use picture timing SEI information. Even if it is a
2015              * information of a past frame, better than nothing. */
2016             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2017                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2018                 cur->f.top_field_first = 1;
2019             else
2020                 cur->f.top_field_first = 0;
2021         } else {
2022             /* Most likely progressive */
2023             cur->f.top_field_first = 0;
2024         }
2025     }
2026
2027     if (h->sei_frame_packing_present &&
2028         h->frame_packing_arrangement_type >= 0 &&
2029         h->frame_packing_arrangement_type <= 6 &&
2030         h->content_interpretation_type > 0 &&
2031         h->content_interpretation_type < 3) {
2032         AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
2033         if (!stereo)
2034             return;
2035
2036         switch (h->frame_packing_arrangement_type) {
2037         case 0:
2038             stereo->type = AV_STEREO3D_CHECKERBOARD;
2039             break;
2040         case 1:
2041             stereo->type = AV_STEREO3D_LINES;
2042             break;
2043         case 2:
2044             stereo->type = AV_STEREO3D_COLUMNS;
2045             break;
2046         case 3:
2047             if (h->quincunx_subsampling)
2048                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2049             else
2050                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
2051             break;
2052         case 4:
2053             stereo->type = AV_STEREO3D_TOPBOTTOM;
2054             break;
2055         case 5:
2056             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
2057             break;
2058         case 6:
2059             stereo->type = AV_STEREO3D_2D;
2060             break;
2061         }
2062
2063         if (h->content_interpretation_type == 2)
2064             stereo->flags = AV_STEREO3D_FLAG_INVERT;
2065     }
2066
2067     // FIXME do something with unavailable reference frames
2068
2069     /* Sort B-frames into display order */
2070
2071     if (h->sps.bitstream_restriction_flag &&
2072         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2073         h->avctx->has_b_frames = h->sps.num_reorder_frames;
2074         h->low_delay           = 0;
2075     }
2076
2077     if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2078         !h->sps.bitstream_restriction_flag) {
2079         h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2080         h->low_delay           = 0;
2081     }
2082
2083     pics = 0;
2084     while (h->delayed_pic[pics])
2085         pics++;
2086
2087     assert(pics <= MAX_DELAYED_PIC_COUNT);
2088
2089     h->delayed_pic[pics++] = cur;
2090     if (cur->reference == 0)
2091         cur->reference = DELAYED_PIC_REF;
2092
2093     /* Frame reordering. This code takes pictures from coding order and sorts
2094      * them by their incremental POC value into display order. It supports POC
2095      * gaps, MMCO reset codes and random resets.
2096      * A "display group" can start either with a IDR frame (f.key_frame = 1),
2097      * and/or can be closed down with a MMCO reset code. In sequences where
2098      * there is no delay, we can't detect that (since the frame was already
2099      * output to the user), so we also set h->mmco_reset to detect the MMCO
2100      * reset code.
2101      * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
2102      * we increase the delay between input and output. All frames affected by
2103      * the lag (e.g. those that should have been output before another frame
2104      * that we already returned to the user) will be dropped. This is a bug
2105      * that we will fix later. */
2106     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2107         cnt     += out->poc < h->last_pocs[i];
2108         invalid += out->poc == INT_MIN;
2109     }
2110     if (!h->mmco_reset && !cur->f.key_frame &&
2111         cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
2112         h->mmco_reset = 2;
2113         if (pics > 1)
2114             h->delayed_pic[pics - 2]->mmco_reset = 2;
2115     }
2116     if (h->mmco_reset || cur->f.key_frame) {
2117         for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2118             h->last_pocs[i] = INT_MIN;
2119         cnt     = 0;
2120         invalid = MAX_DELAYED_PIC_COUNT;
2121     }
2122     out     = h->delayed_pic[0];
2123     out_idx = 0;
2124     for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
2125                 h->delayed_pic[i] &&
2126                 !h->delayed_pic[i - 1]->mmco_reset &&
2127                 !h->delayed_pic[i]->f.key_frame;
2128          i++)
2129         if (h->delayed_pic[i]->poc < out->poc) {
2130             out     = h->delayed_pic[i];
2131             out_idx = i;
2132         }
2133     if (h->avctx->has_b_frames == 0 &&
2134         (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
2135         h->next_outputed_poc = INT_MIN;
2136     out_of_order = !out->f.key_frame && !h->mmco_reset &&
2137                    (out->poc < h->next_outputed_poc);
2138
2139     if (h->sps.bitstream_restriction_flag &&
2140         h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
2141     } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
2142                h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
2143         if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
2144             h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
2145         }
2146         h->low_delay = 0;
2147     } else if (h->low_delay &&
2148                ((h->next_outputed_poc != INT_MIN &&
2149                  out->poc > h->next_outputed_poc + 2) ||
2150                 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
2151         h->low_delay = 0;
2152         h->avctx->has_b_frames++;
2153     }
2154
2155     if (pics > h->avctx->has_b_frames) {
2156         out->reference &= ~DELAYED_PIC_REF;
2157         // for frame threading, the owner must be the second field's thread or
2158         // else the first thread can release the picture and reuse it unsafely
2159         for (i = out_idx; h->delayed_pic[i]; i++)
2160             h->delayed_pic[i] = h->delayed_pic[i + 1];
2161     }
2162     memmove(h->last_pocs, &h->last_pocs[1],
2163             sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
2164     h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
2165     if (!out_of_order && pics > h->avctx->has_b_frames) {
2166         h->next_output_pic = out;
2167         if (out->mmco_reset) {
2168             if (out_idx > 0) {
2169                 h->next_outputed_poc                    = out->poc;
2170                 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
2171             } else {
2172                 h->next_outputed_poc = INT_MIN;
2173             }
2174         } else {
2175             if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
2176                 h->next_outputed_poc = INT_MIN;
2177             } else {
2178                 h->next_outputed_poc = out->poc;
2179             }
2180         }
2181         h->mmco_reset = 0;
2182     } else {
2183         av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
2184     }
2185
2186     if (h->next_output_pic) {
2187         if (h->next_output_pic->recovered) {
2188             // We have reached an recovery point and all frames after it in
2189             // display order are "recovered".
2190             h->frame_recovered |= FRAME_RECOVERED_SEI;
2191         }
2192         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2193     }
2194
2195     if (setup_finished && !h->avctx->hwaccel)
2196         ff_thread_finish_setup(h->avctx);
2197 }
2198
2199 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2200                                               uint8_t *src_cb, uint8_t *src_cr,
2201                                               int linesize, int uvlinesize,
2202                                               int simple)
2203 {
2204     uint8_t *top_border;
2205     int top_idx = 1;
2206     const int pixel_shift = h->pixel_shift;
2207     int chroma444 = CHROMA444(h);
2208     int chroma422 = CHROMA422(h);
2209
2210     src_y  -= linesize;
2211     src_cb -= uvlinesize;
2212     src_cr -= uvlinesize;
2213
2214     if (!simple && FRAME_MBAFF(h)) {
2215         if (h->mb_y & 1) {
2216             if (!MB_MBAFF(h)) {
2217                 top_border = h->top_borders[0][h->mb_x];
2218                 AV_COPY128(top_border, src_y + 15 * linesize);
2219                 if (pixel_shift)
2220                     AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2221                 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2222                     if (chroma444) {
2223                         if (pixel_shift) {
2224                             AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2225                             AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2226                             AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2227                             AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2228                         } else {
2229                             AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2230                             AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2231                         }
2232                     } else if (chroma422) {
2233                         if (pixel_shift) {
2234                             AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2235                             AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2236                         } else {
2237                             AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2238                             AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2239                         }
2240                     } else {
2241                         if (pixel_shift) {
2242                             AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2243                             AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2244                         } else {
2245                             AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2246                             AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2247                         }
2248                     }
2249                 }
2250             }
2251         } else if (MB_MBAFF(h)) {
2252             top_idx = 0;
2253         } else
2254             return;
2255     }
2256
2257     top_border = h->top_borders[top_idx][h->mb_x];
2258     /* There are two lines saved, the line above the top macroblock
2259      * of a pair, and the line above the bottom macroblock. */
2260     AV_COPY128(top_border, src_y + 16 * linesize);
2261     if (pixel_shift)
2262         AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2263
2264     if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2265         if (chroma444) {
2266             if (pixel_shift) {
2267                 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2268                 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2269                 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2270                 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2271             } else {
2272                 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2273                 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2274             }
2275         } else if (chroma422) {
2276             if (pixel_shift) {
2277                 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2278                 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2279             } else {
2280                 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2281                 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2282             }
2283         } else {
2284             if (pixel_shift) {
2285                 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2286                 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2287             } else {
2288                 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2289                 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2290             }
2291         }
2292     }
2293 }
2294
2295 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2296                                             uint8_t *src_cb, uint8_t *src_cr,
2297                                             int linesize, int uvlinesize,
2298                                             int xchg, int chroma444,
2299                                             int simple, int pixel_shift)
2300 {
2301     int deblock_topleft;
2302     int deblock_top;
2303     int top_idx = 1;
2304     uint8_t *top_border_m1;
2305     uint8_t *top_border;
2306
2307     if (!simple && FRAME_MBAFF(h)) {
2308         if (h->mb_y & 1) {
2309             if (!MB_MBAFF(h))
2310                 return;
2311         } else {
2312             top_idx = MB_MBAFF(h) ? 0 : 1;
2313         }
2314     }
2315
2316     if (h->deblocking_filter == 2) {
2317         deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2318         deblock_top     = h->top_type;
2319     } else {
2320         deblock_topleft = (h->mb_x > 0);
2321         deblock_top     = (h->mb_y > !!MB_FIELD(h));
2322     }
2323
2324     src_y  -= linesize   + 1 + pixel_shift;
2325     src_cb -= uvlinesize + 1 + pixel_shift;
2326     src_cr -= uvlinesize + 1 + pixel_shift;
2327
2328     top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2329     top_border    = h->top_borders[top_idx][h->mb_x];
2330
2331 #define XCHG(a, b, xchg)                        \
2332     if (pixel_shift) {                          \
2333         if (xchg) {                             \
2334             AV_SWAP64(b + 0, a + 0);            \
2335             AV_SWAP64(b + 8, a + 8);            \
2336         } else {                                \
2337             AV_COPY128(b, a);                   \
2338         }                                       \
2339     } else if (xchg)                            \
2340         AV_SWAP64(b, a);                        \
2341     else                                        \
2342         AV_COPY64(b, a);
2343
2344     if (deblock_top) {
2345         if (deblock_topleft) {
2346             XCHG(top_border_m1 + (8 << pixel_shift),
2347                  src_y - (7 << pixel_shift), 1);
2348         }
2349         XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2350         XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2351         if (h->mb_x + 1 < h->mb_width) {
2352             XCHG(h->top_borders[top_idx][h->mb_x + 1],
2353                  src_y + (17 << pixel_shift), 1);
2354         }
2355     }
2356     if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2357         if (chroma444) {
2358             if (deblock_top) {
2359                 if (deblock_topleft) {
2360                     XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2361                     XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2362                 }
2363                 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2364                 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2365                 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2366                 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2367                 if (h->mb_x + 1 < h->mb_width) {
2368                     XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2369                     XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2370                 }
2371             }
2372         } else {
2373             if (deblock_top) {
2374                 if (deblock_topleft) {
2375                     XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2376                     XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2377                 }
2378                 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2379                 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2380             }
2381         }
2382     }
2383 }
2384
2385 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2386                                         int index)
2387 {
2388     if (high_bit_depth) {
2389         return AV_RN32A(((int32_t *)mb) + index);
2390     } else
2391         return AV_RN16A(mb + index);
2392 }
2393
2394 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2395                                          int index, int value)
2396 {
2397     if (high_bit_depth) {
2398         AV_WN32A(((int32_t *)mb) + index, value);
2399     } else
2400         AV_WN16A(mb + index, value);
2401 }
2402
2403 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2404                                                        int mb_type, int is_h264,
2405                                                        int simple,
2406                                                        int transform_bypass,
2407                                                        int pixel_shift,
2408                                                        int *block_offset,
2409                                                        int linesize,
2410                                                        uint8_t *dest_y, int p)
2411 {
2412     void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2413     void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2414     int i;
2415     int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2416     block_offset += 16 * p;
2417     if (IS_INTRA4x4(mb_type)) {
2418         if (IS_8x8DCT(mb_type)) {
2419             if (transform_bypass) {
2420                 idct_dc_add =
2421                 idct_add    = h->h264dsp.h264_add_pixels8_clear;
2422             } else {
2423                 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2424                 idct_add    = h->h264dsp.h264_idct8_add;
2425             }
2426             for (i = 0; i < 16; i += 4) {
2427                 uint8_t *const ptr = dest_y + block_offset[i];
2428                 const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
2429                 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2430                     h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2431                 } else {
2432                     const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2433                     h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2434                                          (h->topright_samples_available << i) & 0x4000, linesize);
2435                     if (nnz) {
2436                         if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2437                             idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2438                         else
2439                             idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2440                     }
2441                 }
2442             }
2443         } else {
2444             if (transform_bypass) {
2445                 idct_dc_add  =
2446                 idct_add     = h->h264dsp.h264_add_pixels4_clear;
2447             } else {
2448                 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2449                 idct_add    = h->h264dsp.h264_idct_add;
2450             }
2451             for (i = 0; i < 16; i++) {
2452                 uint8_t *const ptr = dest_y + block_offset[i];
2453                 const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
2454
2455                 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2456                     h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2457                 } else {
2458                     uint8_t *topright;
2459                     int nnz, tr;
2460                     uint64_t tr_high;
2461                     if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2462                         const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2463                         assert(h->mb_y || linesize <= block_offset[i]);
2464                         if (!topright_avail) {
2465                             if (pixel_shift) {
2466                                 tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2467                                 topright = (uint8_t *)&tr_high;
2468                             } else {
2469                                 tr       = ptr[3 - linesize] * 0x01010101u;
2470                                 topright = (uint8_t *)&tr;
2471                             }
2472                         } else
2473                             topright = ptr + (4 << pixel_shift) - linesize;
2474                     } else
2475                         topright = NULL;
2476
2477                     h->hpc.pred4x4[dir](ptr, topright, linesize);
2478                     nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2479                     if (nnz) {
2480                         if (is_h264) {
2481                             if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2482                                 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2483                             else
2484                                 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2485                         } else if (CONFIG_SVQ3_DECODER)
2486                             ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2487                     }
2488                 }
2489             }
2490         }
2491     } else {
2492         h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2493         if (is_h264) {
2494             if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2495                 if (!transform_bypass)
2496                     h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2497                                                          h->mb_luma_dc[p],
2498                                                          h->dequant4_coeff[p][qscale][0]);
2499                 else {
2500                     static const uint8_t dc_mapping[16] = {
2501                          0 * 16,  1 * 16,  4 * 16,  5 * 16,
2502                          2 * 16,  3 * 16,  6 * 16,  7 * 16,
2503                          8 * 16,  9 * 16, 12 * 16, 13 * 16,
2504                         10 * 16, 11 * 16, 14 * 16, 15 * 16
2505                     };
2506                     for (i = 0; i < 16; i++)
2507                         dctcoef_set(h->mb + (p * 256 << pixel_shift),
2508                                     pixel_shift, dc_mapping[i],
2509                                     dctcoef_get(h->mb_luma_dc[p],
2510                                                 pixel_shift, i));
2511                 }
2512             }
2513         } else if (CONFIG_SVQ3_DECODER)
2514             ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2515                                            h->mb_luma_dc[p], qscale);
2516     }
2517 }
2518
2519 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2520                                                     int is_h264, int simple,
2521                                                     int transform_bypass,
2522                                                     int pixel_shift,
2523                                                     int *block_offset,
2524                                                     int linesize,
2525                                                     uint8_t *dest_y, int p)
2526 {
2527     void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2528     int i;
2529     block_offset += 16 * p;
2530     if (!IS_INTRA4x4(mb_type)) {
2531         if (is_h264) {
2532             if (IS_INTRA16x16(mb_type)) {
2533                 if (transform_bypass) {
2534                     if (h->sps.profile_idc == 244 &&
2535                         (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2536                          h->intra16x16_pred_mode == HOR_PRED8x8)) {
2537                         h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2538                                                                       h->mb + (p * 256 << pixel_shift),
2539                                                                       linesize);
2540                     } else {
2541                         for (i = 0; i < 16; i++)
2542                             if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2543                                 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2544                                 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2545                                                                   h->mb + (i * 16 + p * 256 << pixel_shift),
2546                                                                   linesize);
2547                     }
2548                 } else {
2549                     h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2550                                                     h->mb + (p * 256 << pixel_shift),
2551                                                     linesize,
2552                                                     h->non_zero_count_cache + p * 5 * 8);
2553                 }
2554             } else if (h->cbp & 15) {
2555                 if (transform_bypass) {
2556                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2557                     idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2558                                                   : h->h264dsp.h264_add_pixels4_clear;
2559                     for (i = 0; i < 16; i += di)
2560                         if (h->non_zero_count_cache[scan8[i + p * 16]])
2561                             idct_add(dest_y + block_offset[i],
2562                                      h->mb + (i * 16 + p * 256 << pixel_shift),
2563                                      linesize);
2564                 } else {
2565                     if (IS_8x8DCT(mb_type))
2566                         h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2567                                                    h->mb + (p * 256 << pixel_shift),
2568                                                    linesize,
2569                                                    h->non_zero_count_cache + p * 5 * 8);
2570                     else
2571                         h->h264dsp.h264_idct_add16(dest_y, block_offset,
2572                                                    h->mb + (p * 256 << pixel_shift),
2573                                                    linesize,
2574                                                    h->non_zero_count_cache + p * 5 * 8);
2575                 }
2576             }
2577         } else if (CONFIG_SVQ3_DECODER) {
2578             for (i = 0; i < 16; i++)
2579                 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2580                     // FIXME benchmark weird rule, & below
2581                     uint8_t *const ptr = dest_y + block_offset[i];
2582                     ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2583                                        h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2584                 }
2585         }
2586     }
2587 }
2588
2589 #define BITS   8
2590 #define SIMPLE 1
2591 #include "h264_mb_template.c"
2592
2593 #undef  BITS
2594 #define BITS   16
2595 #include "h264_mb_template.c"
2596
2597 #undef  SIMPLE
2598 #define SIMPLE 0
2599 #include "h264_mb_template.c"
2600
2601 void ff_h264_hl_decode_mb(H264Context *h)
2602 {
2603     const int mb_xy   = h->mb_xy;
2604     const int mb_type = h->cur_pic.mb_type[mb_xy];
2605     int is_complex    = CONFIG_SMALL || h->is_complex ||
2606                         IS_INTRA_PCM(mb_type) || h->qscale == 0;
2607
2608     if (CHROMA444(h)) {
2609         if (is_complex || h->pixel_shift)
2610             hl_decode_mb_444_complex(h);
2611         else
2612             hl_decode_mb_444_simple_8(h);
2613     } else if (is_complex) {
2614         hl_decode_mb_complex(h);
2615     } else if (h->pixel_shift) {
2616         hl_decode_mb_simple_16(h);
2617     } else
2618         hl_decode_mb_simple_8(h);
2619 }
2620
2621 int ff_pred_weight_table(H264Context *h)
2622 {
2623     int list, i;
2624     int luma_def, chroma_def;
2625
2626     h->use_weight             = 0;
2627     h->use_weight_chroma      = 0;
2628     h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2629     if (h->sps.chroma_format_idc)
2630         h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2631     luma_def   = 1 << h->luma_log2_weight_denom;
2632     chroma_def = 1 << h->chroma_log2_weight_denom;
2633
2634     for (list = 0; list < 2; list++) {
2635         h->luma_weight_flag[list]   = 0;
2636         h->chroma_weight_flag[list] = 0;
2637         for (i = 0; i < h->ref_count[list]; i++) {
2638             int luma_weight_flag, chroma_weight_flag;
2639
2640             luma_weight_flag = get_bits1(&h->gb);
2641             if (luma_weight_flag) {
2642                 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2643                 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2644                 if (h->luma_weight[i][list][0] != luma_def ||
2645                     h->luma_weight[i][list][1] != 0) {
2646                     h->use_weight             = 1;
2647                     h->luma_weight_flag[list] = 1;
2648                 }
2649             } else {
2650                 h->luma_weight[i][list][0] = luma_def;
2651                 h->luma_weight[i][list][1] = 0;
2652             }
2653
2654             if (h->sps.chroma_format_idc) {
2655                 chroma_weight_flag = get_bits1(&h->gb);
2656                 if (chroma_weight_flag) {
2657                     int j;
2658                     for (j = 0; j < 2; j++) {
2659                         h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2660                         h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2661                         if (h->chroma_weight[i][list][j][0] != chroma_def ||
2662                             h->chroma_weight[i][list][j][1] != 0) {
2663                             h->use_weight_chroma        = 1;
2664                             h->chroma_weight_flag[list] = 1;
2665                         }
2666                     }
2667                 } else {
2668                     int j;
2669                     for (j = 0; j < 2; j++) {
2670                         h->chroma_weight[i][list][j][0] = chroma_def;
2671                         h->chroma_weight[i][list][j][1] = 0;
2672                     }
2673                 }
2674             }
2675         }
2676         if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2677             break;
2678     }
2679     h->use_weight = h->use_weight || h->use_weight_chroma;
2680     return 0;
2681 }
2682
2683 /**
2684  * Initialize implicit_weight table.
2685  * @param field  0/1 initialize the weight for interlaced MBAFF
2686  *                -1 initializes the rest
2687  */
2688 static void implicit_weight_table(H264Context *h, int field)
2689 {
2690     int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2691
2692     for (i = 0; i < 2; i++) {
2693         h->luma_weight_flag[i]   = 0;
2694         h->chroma_weight_flag[i] = 0;
2695     }
2696
2697     if (field < 0) {
2698         if (h->picture_structure == PICT_FRAME) {
2699             cur_poc = h->cur_pic_ptr->poc;
2700         } else {
2701             cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2702         }
2703         if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2704             h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2705             h->use_weight        = 0;
2706             h->use_weight_chroma = 0;
2707             return;
2708         }
2709         ref_start  = 0;
2710         ref_count0 = h->ref_count[0];
2711         ref_count1 = h->ref_count[1];
2712     } else {
2713         cur_poc    = h->cur_pic_ptr->field_poc[field];
2714         ref_start  = 16;
2715         ref_count0 = 16 + 2 * h->ref_count[0];
2716         ref_count1 = 16 + 2 * h->ref_count[1];
2717     }
2718
2719     h->use_weight               = 2;
2720     h->use_weight_chroma        = 2;
2721     h->luma_log2_weight_denom   = 5;
2722     h->chroma_log2_weight_denom = 5;
2723
2724     for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2725         int poc0 = h->ref_list[0][ref0].poc;
2726         for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2727             int w = 32;
2728             if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2729                 int poc1 = h->ref_list[1][ref1].poc;
2730                 int td   = av_clip(poc1 - poc0, -128, 127);
2731                 if (td) {
2732                     int tb = av_clip(cur_poc - poc0, -128, 127);
2733                     int tx = (16384 + (FFABS(td) >> 1)) / td;
2734                     int dist_scale_factor = (tb * tx + 32) >> 8;
2735                     if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2736                         w = 64 - dist_scale_factor;
2737                 }
2738             }
2739             if (field < 0) {
2740                 h->implicit_weight[ref0][ref1][0] =
2741                 h->implicit_weight[ref0][ref1][1] = w;
2742             } else {
2743                 h->implicit_weight[ref0][ref1][field] = w;
2744             }
2745         }
2746     }
2747 }
2748
2749 /**
2750  * instantaneous decoder refresh.
2751  */
2752 static void idr(H264Context *h)
2753 {
2754     ff_h264_remove_all_refs(h);
2755     h->prev_frame_num        = 0;
2756     h->prev_frame_num_offset = 0;
2757     h->prev_poc_msb          =
2758     h->prev_poc_lsb          = 0;
2759 }
2760
2761 /* forget old pics after a seek */
2762 static void flush_change(H264Context *h)
2763 {
2764     int i;
2765     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2766         h->last_pocs[i] = INT_MIN;
2767     h->outputed_poc          = h->next_outputed_poc = INT_MIN;
2768     h->prev_interlaced_frame = 1;
2769     idr(h);
2770     if (h->cur_pic_ptr)
2771         h->cur_pic_ptr->reference = 0;
2772     h->first_field = 0;
2773     memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2774     memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2775     memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2776     memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2777     ff_h264_reset_sei(h);
2778     h->recovery_frame = -1;
2779     h->frame_recovered = 0;
2780 }
2781
2782 /* forget old pics after a seek */
2783 static void flush_dpb(AVCodecContext *avctx)
2784 {
2785     H264Context *h = avctx->priv_data;
2786     int i;
2787
2788     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2789         if (h->delayed_pic[i])
2790             h->delayed_pic[i]->reference = 0;
2791         h->delayed_pic[i] = NULL;
2792     }
2793
2794     flush_change(h);
2795
2796     if (h->DPB)
2797         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
2798             unref_picture(h, &h->DPB[i]);
2799     h->cur_pic_ptr = NULL;
2800     unref_picture(h, &h->cur_pic);
2801
2802     h->mb_x = h->mb_y = 0;
2803
2804     h->parse_context.state             = -1;
2805     h->parse_context.frame_start_found = 0;
2806     h->parse_context.overread          = 0;
2807     h->parse_context.overread_index    = 0;
2808     h->parse_context.index             = 0;
2809     h->parse_context.last_index        = 0;
2810
2811     free_tables(h, 1);
2812     h->context_initialized = 0;
2813 }
2814
2815 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2816 {
2817     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2818     int field_poc[2];
2819
2820     h->frame_num_offset = h->prev_frame_num_offset;
2821     if (h->frame_num < h->prev_frame_num)
2822         h->frame_num_offset += max_frame_num;
2823
2824     if (h->sps.poc_type == 0) {
2825         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2826
2827         if (h->poc_lsb < h->prev_poc_lsb &&
2828             h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2829             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2830         else if (h->poc_lsb > h->prev_poc_lsb &&
2831                  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2832             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2833         else
2834             h->poc_msb = h->prev_poc_msb;
2835         field_poc[0] =
2836         field_poc[1] = h->poc_msb + h->poc_lsb;
2837         if (h->picture_structure == PICT_FRAME)
2838             field_poc[1] += h->delta_poc_bottom;
2839     } else if (h->sps.poc_type == 1) {
2840         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2841         int i;
2842
2843         if (h->sps.poc_cycle_length != 0)
2844             abs_frame_num = h->frame_num_offset + h->frame_num;
2845         else
2846             abs_frame_num = 0;
2847
2848         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2849             abs_frame_num--;
2850
2851         expected_delta_per_poc_cycle = 0;
2852         for (i = 0; i < h->sps.poc_cycle_length; i++)
2853             // FIXME integrate during sps parse
2854             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2855
2856         if (abs_frame_num > 0) {
2857             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2858             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2859
2860             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2861             for (i = 0; i <= frame_num_in_poc_cycle; i++)
2862                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2863         } else
2864             expectedpoc = 0;
2865
2866         if (h->nal_ref_idc == 0)
2867             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2868
2869         field_poc[0] = expectedpoc + h->delta_poc[0];
2870         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2871
2872         if (h->picture_structure == PICT_FRAME)
2873             field_poc[1] += h->delta_poc[1];
2874     } else {
2875         int poc = 2 * (h->frame_num_offset + h->frame_num);
2876
2877         if (!h->nal_ref_idc)
2878             poc--;
2879
2880         field_poc[0] = poc;
2881         field_poc[1] = poc;
2882     }
2883
2884     if (h->picture_structure != PICT_BOTTOM_FIELD)
2885         pic_field_poc[0] = field_poc[0];
2886     if (h->picture_structure != PICT_TOP_FIELD)
2887         pic_field_poc[1] = field_poc[1];
2888     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2889
2890     return 0;
2891 }
2892
2893 /**
2894  * initialize scan tables
2895  */
2896 static void init_scan_tables(H264Context *h)
2897 {
2898     int i;
2899     for (i = 0; i < 16; i++) {
2900 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
2901         h->zigzag_scan[i] = TRANSPOSE(zigzag_scan[i]);
2902         h->field_scan[i]  = TRANSPOSE(field_scan[i]);
2903 #undef TRANSPOSE
2904     }
2905     for (i = 0; i < 64; i++) {
2906 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
2907         h->zigzag_scan8x8[i]       = TRANSPOSE(ff_zigzag_direct[i]);
2908         h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
2909         h->field_scan8x8[i]        = TRANSPOSE(field_scan8x8[i]);
2910         h->field_scan8x8_cavlc[i]  = TRANSPOSE(field_scan8x8_cavlc[i]);
2911 #undef TRANSPOSE
2912     }
2913     if (h->sps.transform_bypass) { // FIXME same ugly
2914         h->zigzag_scan_q0          = zigzag_scan;
2915         h->zigzag_scan8x8_q0       = ff_zigzag_direct;
2916         h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2917         h->field_scan_q0           = field_scan;
2918         h->field_scan8x8_q0        = field_scan8x8;
2919         h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
2920     } else {
2921         h->zigzag_scan_q0          = h->zigzag_scan;
2922         h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
2923         h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2924         h->field_scan_q0           = h->field_scan;
2925         h->field_scan8x8_q0        = h->field_scan8x8;
2926         h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
2927     }
2928 }
2929
2930 #if CONFIG_ERROR_RESILIENCE
2931 static void h264_set_erpic(ERPicture *dst, H264Picture *src)
2932 {
2933     int i;
2934
2935     if (!src)
2936         return;
2937
2938     dst->f = &src->f;
2939     dst->tf = &src->tf;
2940
2941     for (i = 0; i < 2; i++) {
2942         dst->motion_val[i] = src->motion_val[i];
2943         dst->ref_index[i] = src->ref_index[i];
2944     }
2945
2946     dst->mb_type = src->mb_type;
2947     dst->field_picture = src->field_picture;
2948 }
2949 #endif /* CONFIG_ERROR_RESILIENCE */
2950
2951 static int field_end(H264Context *h, int in_setup)
2952 {
2953     AVCodecContext *const avctx = h->avctx;
2954     int err = 0;
2955     h->mb_y = 0;
2956
2957     if (!in_setup && !h->droppable)
2958         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2959                                   h->picture_structure == PICT_BOTTOM_FIELD);
2960
2961     if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2962         if (!h->droppable) {
2963             err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2964             h->prev_poc_msb = h->poc_msb;
2965             h->prev_poc_lsb = h->poc_lsb;
2966         }
2967         h->prev_frame_num_offset = h->frame_num_offset;
2968         h->prev_frame_num        = h->frame_num;
2969         h->outputed_poc          = h->next_outputed_poc;
2970     }
2971
2972     if (avctx->hwaccel) {
2973         if (avctx->hwaccel->end_frame(avctx) < 0)
2974             av_log(avctx, AV_LOG_ERROR,
2975                    "hardware accelerator failed to decode picture\n");
2976     }
2977
2978     /*
2979      * FIXME: Error handling code does not seem to support interlaced
2980      * when slices span multiple rows
2981      * The ff_er_add_slice calls don't work right for bottom
2982      * fields; they cause massive erroneous error concealing
2983      * Error marking covers both fields (top and bottom).
2984      * This causes a mismatched s->error_count
2985      * and a bad error table. Further, the error count goes to
2986      * INT_MAX when called for bottom field, because mb_y is
2987      * past end by one (callers fault) and resync_mb_y != 0
2988      * causes problems for the first MB line, too.
2989      */
2990     if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h)) {
2991         h264_set_erpic(&h->er.cur_pic, h->cur_pic_ptr);
2992         h264_set_erpic(&h->er.last_pic,
2993                        h->ref_count[0] ? &h->ref_list[0][0] : NULL);
2994         h264_set_erpic(&h->er.next_pic,
2995                        h->ref_count[1] ? &h->ref_list[1][0] : NULL);
2996         ff_er_frame_end(&h->er);
2997     }
2998     emms_c();
2999
3000     h->current_slice = 0;
3001
3002     return err;
3003 }
3004
3005 /**
3006  * Replicate H264 "master" context to thread contexts.
3007  */
3008 static int clone_slice(H264Context *dst, H264Context *src)
3009 {
3010     memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3011     dst->cur_pic_ptr = src->cur_pic_ptr;
3012     dst->cur_pic     = src->cur_pic;
3013     dst->linesize    = src->linesize;
3014     dst->uvlinesize  = src->uvlinesize;
3015     dst->first_field = src->first_field;
3016
3017     dst->prev_poc_msb          = src->prev_poc_msb;
3018     dst->prev_poc_lsb          = src->prev_poc_lsb;
3019     dst->prev_frame_num_offset = src->prev_frame_num_offset;
3020     dst->prev_frame_num        = src->prev_frame_num;
3021     dst->short_ref_count       = src->short_ref_count;
3022
3023     memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
3024     memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
3025     memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3026
3027     memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
3028     memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
3029
3030     return 0;
3031 }
3032
3033 /**
3034  * Compute profile from profile_idc and constraint_set?_flags.
3035  *
3036  * @param sps SPS
3037  *
3038  * @return profile as defined by FF_PROFILE_H264_*
3039  */
3040 int ff_h264_get_profile(SPS *sps)
3041 {
3042     int profile = sps->profile_idc;
3043
3044     switch (sps->profile_idc) {
3045     case FF_PROFILE_H264_BASELINE:
3046         // constraint_set1_flag set to 1
3047         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3048         break;
3049     case FF_PROFILE_H264_HIGH_10:
3050     case FF_PROFILE_H264_HIGH_422:
3051     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3052         // constraint_set3_flag set to 1
3053         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3054         break;
3055     }
3056
3057     return profile;
3058 }
3059
3060 static int h264_set_parameter_from_sps(H264Context *h)
3061 {
3062     if (h->flags & CODEC_FLAG_LOW_DELAY ||
3063         (h->sps.bitstream_restriction_flag &&
3064          !h->sps.num_reorder_frames)) {
3065         if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3066             av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3067                    "Reenabling low delay requires a codec flush.\n");
3068         else
3069             h->low_delay = 1;
3070     }
3071
3072     if (h->avctx->has_b_frames < 2)
3073         h->avctx->has_b_frames = !h->low_delay;
3074
3075     if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3076         h->cur_chroma_format_idc      != h->sps.chroma_format_idc) {
3077         if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3078             h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3079             h->cur_chroma_format_idc      = h->sps.chroma_format_idc;
3080             h->pixel_shift                = h->sps.bit_depth_luma > 8;
3081
3082             ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3083                             h->sps.chroma_format_idc);
3084             ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3085             ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3086             ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3087                               h->sps.chroma_format_idc);
3088             if (CONFIG_ERROR_RESILIENCE)
3089                 ff_dsputil_init(&h->dsp, h->avctx);
3090             ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3091         } else {
3092             av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
3093                    h->sps.bit_depth_luma);
3094             return AVERROR_INVALIDDATA;
3095         }
3096     }
3097     return 0;
3098 }
3099
3100 static enum AVPixelFormat get_pixel_format(H264Context *h)
3101 {
3102     switch (h->sps.bit_depth_luma) {
3103     case 9:
3104         if (CHROMA444(h)) {
3105             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3106                 return AV_PIX_FMT_GBRP9;
3107             } else
3108                 return AV_PIX_FMT_YUV444P9;
3109         } else if (CHROMA422(h))
3110             return AV_PIX_FMT_YUV422P9;
3111         else
3112             return AV_PIX_FMT_YUV420P9;
3113         break;
3114     case 10:
3115         if (CHROMA444(h)) {
3116             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3117                 return AV_PIX_FMT_GBRP10;
3118             } else
3119                 return AV_PIX_FMT_YUV444P10;
3120         } else if (CHROMA422(h))
3121             return AV_PIX_FMT_YUV422P10;
3122         else
3123             return AV_PIX_FMT_YUV420P10;
3124         break;
3125     case 8:
3126         if (CHROMA444(h)) {
3127             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3128                 return AV_PIX_FMT_GBRP;
3129             } else
3130                 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3131                                                                  : AV_PIX_FMT_YUV444P;
3132         } else if (CHROMA422(h)) {
3133             return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3134                                                              : AV_PIX_FMT_YUV422P;
3135         } else {
3136             return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
3137                                         h->avctx->codec->pix_fmts :
3138                                         h->avctx->color_range == AVCOL_RANGE_JPEG ?
3139                                         h264_hwaccel_pixfmt_list_jpeg_420 :
3140                                         h264_hwaccel_pixfmt_list_420);
3141         }
3142         break;
3143     default:
3144         av_log(h->avctx, AV_LOG_ERROR,
3145                "Unsupported bit depth %d\n", h->sps.bit_depth_luma);
3146         return AVERROR_INVALIDDATA;
3147     }
3148 }
3149
3150 /* export coded and cropped frame dimensions to AVCodecContext */
3151 static int init_dimensions(H264Context *h)
3152 {
3153     int width  = h->width  - (h->sps.crop_right + h->sps.crop_left);
3154     int height = h->height - (h->sps.crop_top   + h->sps.crop_bottom);
3155
3156     /* handle container cropping */
3157     if (!h->sps.crop &&
3158         FFALIGN(h->avctx->width,  16) == h->width &&
3159         FFALIGN(h->avctx->height, 16) == h->height) {
3160         width  = h->avctx->width;
3161         height = h->avctx->height;
3162     }
3163
3164     if (width <= 0 || height <= 0) {
3165         av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3166                width, height);
3167         if (h->avctx->err_recognition & AV_EF_EXPLODE)
3168             return AVERROR_INVALIDDATA;
3169
3170         av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3171         h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3172         h->sps.crop        = 0;
3173
3174         width  = h->width;
3175         height = h->height;
3176     }
3177
3178     h->avctx->coded_width  = h->width;
3179     h->avctx->coded_height = h->height;
3180     h->avctx->width        = width;
3181     h->avctx->height       = height;
3182
3183     return 0;
3184 }
3185
3186 static int h264_slice_header_init(H264Context *h, int reinit)
3187 {
3188     int nb_slices = (HAVE_THREADS &&
3189                      h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3190                     h->avctx->thread_count : 1;
3191     int i, ret;
3192
3193     h->avctx->sample_aspect_ratio = h->sps.sar;
3194     av_assert0(h->avctx->sample_aspect_ratio.den);
3195     av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3196                                      &h->chroma_x_shift, &h->chroma_y_shift);
3197
3198     if (h->sps.timing_info_present_flag) {
3199         int64_t den = h->sps.time_scale;
3200         if (h->x264_build < 44U)
3201             den *= 2;
3202         av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3203                   h->sps.num_units_in_tick, den, 1 << 30);
3204     }
3205
3206     h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3207
3208     if (reinit)
3209         free_tables(h, 0);
3210     h->first_field           = 0;
3211     h->prev_interlaced_frame = 1;
3212
3213     init_scan_tables(h);
3214     ret = ff_h264_alloc_tables(h);
3215     if (ret < 0) {
3216         av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
3217         return ret;
3218     }
3219
3220     if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3221         int max_slices;
3222         if (h->mb_height)
3223             max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
3224         else
3225             max_slices = H264_MAX_THREADS;
3226         av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
3227                " reducing to %d\n", nb_slices, max_slices);
3228         nb_slices = max_slices;
3229     }
3230     h->slice_context_count = nb_slices;
3231
3232     if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3233         ret = context_init(h);
3234         if (ret < 0) {
3235             av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3236             return ret;
3237         }
3238     } else {
3239         for (i = 1; i < h->slice_context_count; i++) {
3240             H264Context *c;
3241             c                    = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3242             if (!c)
3243                 return AVERROR(ENOMEM);
3244             c->avctx             = h->avctx;
3245             c->dsp               = h->dsp;
3246             c->vdsp              = h->vdsp;
3247             c->h264dsp           = h->h264dsp;
3248             c->h264qpel          = h->h264qpel;
3249             c->h264chroma        = h->h264chroma;
3250             c->sps               = h->sps;
3251             c->pps               = h->pps;
3252             c->pixel_shift       = h->pixel_shift;
3253             c->width             = h->width;
3254             c->height            = h->height;
3255             c->linesize          = h->linesize;
3256             c->uvlinesize        = h->uvlinesize;
3257             c->chroma_x_shift    = h->chroma_x_shift;
3258             c->chroma_y_shift    = h->chroma_y_shift;
3259             c->qscale            = h->qscale;
3260             c->droppable         = h->droppable;
3261             c->data_partitioning = h->data_partitioning;
3262             c->low_delay         = h->low_delay;
3263             c->mb_width          = h->mb_width;
3264             c->mb_height         = h->mb_height;
3265             c->mb_stride         = h->mb_stride;
3266             c->mb_num            = h->mb_num;
3267             c->flags             = h->flags;
3268             c->workaround_bugs   = h->workaround_bugs;
3269             c->pict_type         = h->pict_type;
3270
3271             init_scan_tables(c);
3272             clone_tables(c, h, i);
3273             c->context_initialized = 1;
3274         }
3275
3276         for (i = 0; i < h->slice_context_count; i++)
3277             if ((ret = context_init(h->thread_context[i])) < 0) {
3278                 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3279                 return ret;
3280             }
3281     }
3282
3283     h->context_initialized = 1;
3284
3285     return 0;
3286 }
3287
3288 int ff_set_ref_count(H264Context *h)
3289 {
3290     int ref_count[2], list_count;
3291     int num_ref_idx_active_override_flag, max_refs;
3292
3293     // set defaults, might be overridden a few lines later
3294     ref_count[0] = h->pps.ref_count[0];
3295     ref_count[1] = h->pps.ref_count[1];
3296
3297     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3298         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3299             h->direct_spatial_mv_pred = get_bits1(&h->gb);
3300         num_ref_idx_active_override_flag = get_bits1(&h->gb);
3301
3302         if (num_ref_idx_active_override_flag) {
3303             ref_count[0] = get_ue_golomb(&h->gb) + 1;
3304             if (ref_count[0] < 1)
3305                 return AVERROR_INVALIDDATA;
3306             if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3307                 ref_count[1] = get_ue_golomb(&h->gb) + 1;
3308                 if (ref_count[1] < 1)
3309                     return AVERROR_INVALIDDATA;
3310             }
3311         }
3312
3313         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3314             list_count = 2;
3315         else
3316             list_count = 1;
3317     } else {
3318         list_count   = 0;
3319         ref_count[0] = ref_count[1] = 0;
3320     }
3321
3322     max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
3323
3324     if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
3325         av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
3326         h->ref_count[0] = h->ref_count[1] = 0;
3327         return AVERROR_INVALIDDATA;
3328     }
3329
3330     if (list_count != h->list_count ||
3331         ref_count[0] != h->ref_count[0] ||
3332         ref_count[1] != h->ref_count[1]) {
3333         h->ref_count[0] = ref_count[0];
3334         h->ref_count[1] = ref_count[1];
3335         h->list_count   = list_count;
3336         return 1;
3337     }
3338
3339     return 0;
3340 }
3341
3342 /**
3343  * Decode a slice header.
3344  * This will (re)intialize the decoder and call h264_frame_start() as needed.
3345  *
3346  * @param h h264context
3347  * @param h0 h264 master context (differs from 'h' when doing sliced based
3348  *           parallel decoding)
3349  *
3350  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3351  */
3352 static int decode_slice_header(H264Context *h, H264Context *h0)
3353 {
3354     unsigned int first_mb_in_slice;
3355     unsigned int pps_id;
3356     int ret;
3357     unsigned int slice_type, tmp, i, j;
3358     int default_ref_list_done = 0;
3359     int last_pic_structure, last_pic_droppable;
3360     int needs_reinit = 0;
3361     int field_pic_flag, bottom_field_flag;
3362
3363     h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3364     h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3365
3366     first_mb_in_slice = get_ue_golomb(&h->gb);
3367
3368     if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3369         if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
3370             field_end(h, 1);
3371         }
3372
3373         h0->current_slice = 0;
3374         if (!h0->first_field) {
3375             if (h->cur_pic_ptr && !h->droppable) {
3376                 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3377                                           h->picture_structure == PICT_BOTTOM_FIELD);
3378             }
3379             h->cur_pic_ptr = NULL;
3380         }
3381     }
3382
3383     slice_type = get_ue_golomb_31(&h->gb);
3384     if (slice_type > 9) {
3385         av_log(h->avctx, AV_LOG_ERROR,
3386                "slice type %d too large at %d %d\n",
3387                slice_type, h->mb_x, h->mb_y);
3388         return AVERROR_INVALIDDATA;
3389     }
3390     if (slice_type > 4) {
3391         slice_type -= 5;
3392         h->slice_type_fixed = 1;
3393     } else
3394         h->slice_type_fixed = 0;
3395
3396     slice_type = golomb_to_pict_type[slice_type];
3397     if (slice_type == AV_PICTURE_TYPE_I ||
3398         (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3399         default_ref_list_done = 1;
3400     }
3401     h->slice_type     = slice_type;
3402     h->slice_type_nos = slice_type & 3;
3403
3404     if (h->nal_unit_type  == NAL_IDR_SLICE &&
3405         h->slice_type_nos != AV_PICTURE_TYPE_I) {
3406         av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
3407         return AVERROR_INVALIDDATA;
3408     }
3409
3410     // to make a few old functions happy, it's wrong though
3411     h->pict_type = h->slice_type;
3412
3413     pps_id = get_ue_golomb(&h->gb);
3414     if (pps_id >= MAX_PPS_COUNT) {
3415         av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
3416         return AVERROR_INVALIDDATA;
3417     }
3418     if (!h0->pps_buffers[pps_id]) {
3419         av_log(h->avctx, AV_LOG_ERROR,
3420                "non-existing PPS %u referenced\n",
3421                pps_id);
3422         return AVERROR_INVALIDDATA;
3423     }
3424     h->pps = *h0->pps_buffers[pps_id];
3425
3426     if (!h0->sps_buffers[h->pps.sps_id]) {
3427         av_log(h->avctx, AV_LOG_ERROR,
3428                "non-existing SPS %u referenced\n",
3429                h->pps.sps_id);
3430         return AVERROR_INVALIDDATA;
3431     }
3432
3433     if (h->pps.sps_id != h->sps.sps_id ||
3434         h0->sps_buffers[h->pps.sps_id]->new) {
3435         h0->sps_buffers[h->pps.sps_id]->new = 0;
3436
3437         h->sps = *h0->sps_buffers[h->pps.sps_id];
3438
3439         if (h->bit_depth_luma    != h->sps.bit_depth_luma ||
3440             h->chroma_format_idc != h->sps.chroma_format_idc) {
3441             h->bit_depth_luma    = h->sps.bit_depth_luma;
3442             h->chroma_format_idc = h->sps.chroma_format_idc;
3443             needs_reinit         = 1;
3444         }
3445         if ((ret = h264_set_parameter_from_sps(h)) < 0)
3446             return ret;
3447     }
3448
3449     h->avctx->profile = ff_h264_get_profile(&h->sps);
3450     h->avctx->level   = h->sps.level_idc;
3451     h->avctx->refs    = h->sps.ref_frame_count;
3452
3453     if (h->mb_width  != h->sps.mb_width ||
3454         h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
3455         needs_reinit = 1;
3456
3457     h->mb_width  = h->sps.mb_width;
3458     h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3459     h->mb_num    = h->mb_width * h->mb_height;
3460     h->mb_stride = h->mb_width + 1;
3461
3462     h->b_stride = h->mb_width * 4;
3463
3464     h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3465
3466     h->width  = 16 * h->mb_width;
3467     h->height = 16 * h->mb_height;
3468
3469     ret = init_dimensions(h);
3470     if (ret < 0)
3471         return ret;
3472
3473     if (h->sps.video_signal_type_present_flag) {
3474         h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
3475                                                   : AVCOL_RANGE_MPEG;
3476         if (h->sps.colour_description_present_flag) {
3477             if (h->avctx->colorspace != h->sps.colorspace)
3478                 needs_reinit = 1;
3479             h->avctx->color_primaries = h->sps.color_primaries;
3480             h->avctx->color_trc       = h->sps.color_trc;
3481             h->avctx->colorspace      = h->sps.colorspace;
3482         }
3483     }
3484
3485     if (h->context_initialized &&
3486         (h->width  != h->avctx->coded_width   ||
3487          h->height != h->avctx->coded_height  ||
3488          needs_reinit)) {
3489         if (h != h0) {
3490             av_log(h->avctx, AV_LOG_ERROR,
3491                    "changing width %d -> %d / height %d -> %d on "
3492                    "slice %d\n",
3493                    h->width, h->avctx->coded_width,
3494                    h->height, h->avctx->coded_height,
3495                    h0->current_slice + 1);
3496             return AVERROR_INVALIDDATA;
3497         }
3498
3499         flush_change(h);
3500
3501         if ((ret = get_pixel_format(h)) < 0)
3502             return ret;
3503         h->avctx->pix_fmt = ret;
3504
3505         av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3506                "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3507
3508         if ((ret = h264_slice_header_init(h, 1)) < 0) {
3509             av_log(h->avctx, AV_LOG_ERROR,
3510                    "h264_slice_header_init() failed\n");
3511             return ret;
3512         }
3513     }
3514     if (!h->context_initialized) {
3515         if (h != h0) {
3516             av_log(h->avctx, AV_LOG_ERROR,
3517                    "Cannot (re-)initialize context during parallel decoding.\n");
3518             return AVERROR_PATCHWELCOME;
3519         }
3520
3521         if ((ret = get_pixel_format(h)) < 0)
3522             return ret;
3523         h->avctx->pix_fmt = ret;
3524
3525         if ((ret = h264_slice_header_init(h, 0)) < 0) {
3526             av_log(h->avctx, AV_LOG_ERROR,
3527                    "h264_slice_header_init() failed\n");
3528             return ret;
3529         }
3530     }
3531
3532     if (h == h0 && h->dequant_coeff_pps != pps_id) {
3533         h->dequant_coeff_pps = pps_id;
3534         init_dequant_tables(h);
3535     }
3536
3537     h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3538
3539     h->mb_mbaff        = 0;
3540     h->mb_aff_frame    = 0;
3541     last_pic_structure = h0->picture_structure;
3542     last_pic_droppable = h0->droppable;
3543     h->droppable       = h->nal_ref_idc == 0;
3544     if (h->sps.frame_mbs_only_flag) {
3545         h->picture_structure = PICT_FRAME;
3546     } else {
3547         field_pic_flag = get_bits1(&h->gb);
3548         if (field_pic_flag) {
3549             bottom_field_flag = get_bits1(&h->gb);
3550             h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3551         } else {
3552             h->picture_structure = PICT_FRAME;
3553             h->mb_aff_frame      = h->sps.mb_aff;
3554         }
3555     }
3556     h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3557
3558     if (h0->current_slice != 0) {
3559         if (last_pic_structure != h->picture_structure ||
3560             last_pic_droppable != h->droppable) {
3561             av_log(h->avctx, AV_LOG_ERROR,
3562                    "Changing field mode (%d -> %d) between slices is not allowed\n",
3563                    last_pic_structure, h->picture_structure);
3564             h->picture_structure = last_pic_structure;
3565             h->droppable         = last_pic_droppable;
3566             return AVERROR_INVALIDDATA;
3567         } else if (!h0->cur_pic_ptr) {
3568             av_log(h->avctx, AV_LOG_ERROR,
3569                    "unset cur_pic_ptr on slice %d\n",
3570                    h0->current_slice + 1);
3571             return AVERROR_INVALIDDATA;
3572         }
3573     } else {
3574         /* Shorten frame num gaps so we don't have to allocate reference
3575          * frames just to throw them away */
3576         if (h->frame_num != h->prev_frame_num) {
3577             int unwrap_prev_frame_num = h->prev_frame_num;
3578             int max_frame_num         = 1 << h->sps.log2_max_frame_num;
3579
3580             if (unwrap_prev_frame_num > h->frame_num)
3581                 unwrap_prev_frame_num -= max_frame_num;
3582
3583             if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3584                 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3585                 if (unwrap_prev_frame_num < 0)
3586                     unwrap_prev_frame_num += max_frame_num;
3587
3588                 h->prev_frame_num = unwrap_prev_frame_num;
3589             }
3590         }
3591
3592         /* See if we have a decoded first field looking for a pair...
3593          * Here, we're using that to see if we should mark previously
3594          * decode frames as "finished".
3595          * We have to do that before the "dummy" in-between frame allocation,
3596          * since that can modify s->current_picture_ptr. */
3597         if (h0->first_field) {
3598             assert(h0->cur_pic_ptr);
3599             assert(h0->cur_pic_ptr->f.buf[0]);
3600             assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3601
3602             /* figure out if we have a complementary field pair */
3603             if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3604                 /* Previous field is unmatched. Don't display it, but let it
3605                  * remain for reference if marked as such. */
3606                 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3607                     ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3608                                               last_pic_structure == PICT_TOP_FIELD);
3609                 }
3610             } else {
3611                 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3612                     /* This and previous field were reference, but had
3613                      * different frame_nums. Consider this field first in
3614                      * pair. Throw away previous field except for reference
3615                      * purposes. */
3616                     if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3617                         ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3618                                                   last_pic_structure == PICT_TOP_FIELD);
3619                     }
3620                 } else {
3621                     /* Second field in complementary pair */
3622                     if (!((last_pic_structure   == PICT_TOP_FIELD &&
3623                            h->picture_structure == PICT_BOTTOM_FIELD) ||
3624                           (last_pic_structure   == PICT_BOTTOM_FIELD &&
3625                            h->picture_structure == PICT_TOP_FIELD))) {
3626                         av_log(h->avctx, AV_LOG_ERROR,
3627                                "Invalid field mode combination %d/%d\n",
3628                                last_pic_structure, h->picture_structure);
3629                         h->picture_structure = last_pic_structure;
3630                         h->droppable         = last_pic_droppable;
3631                         return AVERROR_INVALIDDATA;
3632                     } else if (last_pic_droppable != h->droppable) {
3633                         avpriv_request_sample(h->avctx,
3634                                               "Found reference and non-reference fields in the same frame, which");
3635                         h->picture_structure = last_pic_structure;
3636                         h->droppable         = last_pic_droppable;
3637                         return AVERROR_PATCHWELCOME;
3638                     }
3639                 }
3640             }
3641         }
3642
3643         while (h->frame_num != h->prev_frame_num &&
3644                h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3645             H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3646             av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3647                    h->frame_num, h->prev_frame_num);
3648             ret = h264_frame_start(h);
3649             if (ret < 0) {
3650                 h0->first_field = 0;
3651                 return ret;
3652             }
3653
3654             h->prev_frame_num++;
3655             h->prev_frame_num        %= 1 << h->sps.log2_max_frame_num;
3656             h->cur_pic_ptr->frame_num = h->prev_frame_num;
3657             ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3658             ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3659             ret = ff_generate_sliding_window_mmcos(h, 1);
3660             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3661                 return ret;
3662             ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3663             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3664                 return ret;
3665             /* Error concealment: If a ref is missing, copy the previous ref
3666              * in its place.
3667              * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3668              * many assumptions about there being no actual duplicates.
3669              * FIXME: This does not copy padding for out-of-frame motion
3670              * vectors.  Given we are concealing a lost frame, this probably
3671              * is not noticeable by comparison, but it should be fixed. */
3672             if (h->short_ref_count) {
3673                 if (prev) {
3674                     av_image_copy(h->short_ref[0]->f.data,
3675                                   h->short_ref[0]->f.linesize,
3676                                   (const uint8_t **)prev->f.data,
3677                                   prev->f.linesize,
3678                                   h->avctx->pix_fmt,
3679                                   h->mb_width  * 16,
3680                                   h->mb_height * 16);
3681                     h->short_ref[0]->poc = prev->poc + 2;
3682                 }
3683                 h->short_ref[0]->frame_num = h->prev_frame_num;
3684             }
3685         }
3686
3687         /* See if we have a decoded first field looking for a pair...
3688          * We're using that to see whether to continue decoding in that
3689          * frame, or to allocate a new one. */
3690         if (h0->first_field) {
3691             assert(h0->cur_pic_ptr);
3692             assert(h0->cur_pic_ptr->f.buf[0]);
3693             assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3694
3695             /* figure out if we have a complementary field pair */
3696             if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3697                 /* Previous field is unmatched. Don't display it, but let it
3698                  * remain for reference if marked as such. */
3699                 h0->cur_pic_ptr = NULL;
3700                 h0->first_field = FIELD_PICTURE(h);
3701             } else {
3702                 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3703                     /* This and the previous field had different frame_nums.
3704                      * Consider this field first in pair. Throw away previous
3705                      * one except for reference purposes. */
3706                     h0->first_field = 1;
3707                     h0->cur_pic_ptr = NULL;
3708                 } else {
3709                     /* Second field in complementary pair */
3710                     h0->first_field = 0;
3711                 }
3712             }
3713         } else {
3714             /* Frame or first field in a potentially complementary pair */
3715             h0->first_field = FIELD_PICTURE(h);
3716         }
3717
3718         if (!FIELD_PICTURE(h) || h0->first_field) {
3719             if (h264_frame_start(h) < 0) {
3720                 h0->first_field = 0;
3721                 return AVERROR_INVALIDDATA;
3722             }
3723         } else {
3724             release_unused_pictures(h, 0);
3725         }
3726     }
3727     if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3728         return ret;
3729
3730     h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3731
3732     assert(h->mb_num == h->mb_width * h->mb_height);
3733     if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3734         first_mb_in_slice >= h->mb_num) {
3735         av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3736         return AVERROR_INVALIDDATA;
3737     }
3738     h->resync_mb_x = h->mb_x =  first_mb_in_slice % h->mb_width;
3739     h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3740                                FIELD_OR_MBAFF_PICTURE(h);
3741     if (h->picture_structure == PICT_BOTTOM_FIELD)
3742         h->resync_mb_y = h->mb_y = h->mb_y + 1;
3743     assert(h->mb_y < h->mb_height);
3744
3745     if (h->picture_structure == PICT_FRAME) {
3746         h->curr_pic_num = h->frame_num;
3747         h->max_pic_num  = 1 << h->sps.log2_max_frame_num;
3748     } else {
3749         h->curr_pic_num = 2 * h->frame_num + 1;
3750         h->max_pic_num  = 1 << (h->sps.log2_max_frame_num + 1);
3751     }
3752
3753     if (h->nal_unit_type == NAL_IDR_SLICE)
3754         get_ue_golomb(&h->gb); /* idr_pic_id */
3755
3756     if (h->sps.poc_type == 0) {
3757         h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3758
3759         if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3760             h->delta_poc_bottom = get_se_golomb(&h->gb);
3761     }
3762
3763     if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3764         h->delta_poc[0] = get_se_golomb(&h->gb);
3765
3766         if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3767             h->delta_poc[1] = get_se_golomb(&h->gb);
3768     }
3769
3770     ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3771
3772     if (h->pps.redundant_pic_cnt_present)
3773         h->redundant_pic_count = get_ue_golomb(&h->gb);
3774
3775     ret = ff_set_ref_count(h);
3776     if (ret < 0)
3777         return ret;
3778     else if (ret == 1)
3779         default_ref_list_done = 0;
3780
3781     if (!default_ref_list_done)
3782         ff_h264_fill_default_ref_list(h);
3783
3784     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3785        ret = ff_h264_decode_ref_pic_list_reordering(h);
3786        if (ret < 0) {
3787            h->ref_count[1] = h->ref_count[0] = 0;
3788            return ret;
3789        }
3790     }
3791
3792     if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3793         (h->pps.weighted_bipred_idc == 1 &&
3794          h->slice_type_nos == AV_PICTURE_TYPE_B))
3795         ff_pred_weight_table(h);
3796     else if (h->pps.weighted_bipred_idc == 2 &&
3797              h->slice_type_nos == AV_PICTURE_TYPE_B) {
3798         implicit_weight_table(h, -1);
3799     } else {
3800         h->use_weight = 0;
3801         for (i = 0; i < 2; i++) {
3802             h->luma_weight_flag[i]   = 0;
3803             h->chroma_weight_flag[i] = 0;
3804         }
3805     }
3806
3807     // If frame-mt is enabled, only update mmco tables for the first slice
3808     // in a field. Subsequent slices can temporarily clobber h->mmco_index
3809     // or h->mmco, which will cause ref list mix-ups and decoding errors
3810     // further down the line. This may break decoding if the first slice is
3811     // corrupt, thus we only do this if frame-mt is enabled.
3812     if (h->nal_ref_idc) {
3813         ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3814                                              !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3815                                              h0->current_slice == 0);
3816         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3817             return AVERROR_INVALIDDATA;
3818     }
3819
3820     if (FRAME_MBAFF(h)) {
3821         ff_h264_fill_mbaff_ref_list(h);
3822
3823         if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3824             implicit_weight_table(h, 0);
3825             implicit_weight_table(h, 1);
3826         }
3827     }
3828
3829     if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3830         ff_h264_direct_dist_scale_factor(h);
3831     ff_h264_direct_ref_list_init(h);
3832
3833     if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3834         tmp = get_ue_golomb_31(&h->gb);
3835         if (tmp > 2) {
3836             av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
3837             return AVERROR_INVALIDDATA;
3838         }
3839         h->cabac_init_idc = tmp;
3840     }
3841
3842     h->last_qscale_diff = 0;
3843     tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3844     if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3845         av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3846         return AVERROR_INVALIDDATA;
3847     }
3848     h->qscale       = tmp;
3849     h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3850     h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3851     // FIXME qscale / qp ... stuff
3852     if (h->slice_type == AV_PICTURE_TYPE_SP)
3853         get_bits1(&h->gb); /* sp_for_switch_flag */
3854     if (h->slice_type == AV_PICTURE_TYPE_SP ||
3855         h->slice_type == AV_PICTURE_TYPE_SI)
3856         get_se_golomb(&h->gb); /* slice_qs_delta */
3857
3858     h->deblocking_filter     = 1;
3859     h->slice_alpha_c0_offset = 0;
3860     h->slice_beta_offset     = 0;
3861     if (h->pps.deblocking_filter_parameters_present) {
3862         tmp = get_ue_golomb_31(&h->gb);
3863         if (tmp > 2) {
3864             av_log(h->avctx, AV_LOG_ERROR,
3865                    "deblocking_filter_idc %u out of range\n", tmp);
3866             return AVERROR_INVALIDDATA;
3867         }
3868         h->deblocking_filter = tmp;
3869         if (h->deblocking_filter < 2)
3870             h->deblocking_filter ^= 1;  // 1<->0
3871
3872         if (h->deblocking_filter) {
3873             h->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2;
3874             h->slice_beta_offset     = get_se_golomb(&h->gb) * 2;
3875             if (h->slice_alpha_c0_offset >  12 ||
3876                 h->slice_alpha_c0_offset < -12 ||
3877                 h->slice_beta_offset >  12     ||
3878                 h->slice_beta_offset < -12) {
3879                 av_log(h->avctx, AV_LOG_ERROR,
3880                        "deblocking filter parameters %d %d out of range\n",
3881                        h->slice_alpha_c0_offset, h->slice_beta_offset);
3882                 return AVERROR_INVALIDDATA;
3883             }
3884         }
3885     }
3886
3887     if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3888         (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3889          h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3890         (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&
3891          h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3892         (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3893          h->nal_ref_idc == 0))
3894         h->deblocking_filter = 0;
3895
3896     if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3897         if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3898             /* Cheat slightly for speed:
3899              * Do not bother to deblock across slices. */
3900             h->deblocking_filter = 2;
3901         } else {
3902             h0->max_contexts = 1;
3903             if (!h0->single_decode_warning) {
3904                 av_log(h->avctx, AV_LOG_INFO,
3905                        "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3906                 h0->single_decode_warning = 1;
3907             }
3908             if (h != h0) {
3909                 av_log(h->avctx, AV_LOG_ERROR,
3910                        "Deblocking switched inside frame.\n");
3911                 return 1;
3912             }
3913         }
3914     }
3915     h->qp_thresh = 15 -
3916                    FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3917                    FFMAX3(0,
3918                           h->pps.chroma_qp_index_offset[0],
3919                           h->pps.chroma_qp_index_offset[1]) +
3920                    6 * (h->sps.bit_depth_luma - 8);
3921
3922     h0->last_slice_type = slice_type;
3923     h->slice_num        = ++h0->current_slice;
3924     if (h->slice_num >= MAX_SLICES) {
3925         av_log(h->avctx, AV_LOG_ERROR,
3926                "Too many slices, increase MAX_SLICES and recompile\n");
3927     }
3928
3929     for (j = 0; j < 2; j++) {
3930         int id_list[16];
3931         int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3932         for (i = 0; i < 16; i++) {
3933             id_list[i] = 60;
3934             if (j < h->list_count && i < h->ref_count[j] &&
3935                 h->ref_list[j][i].f.buf[0]) {
3936                 int k;
3937                 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
3938                 for (k = 0; k < h->short_ref_count; k++)
3939                     if (h->short_ref[k]->f.buf[0]->buffer == buf) {
3940                         id_list[i] = k;
3941                         break;
3942                     }
3943                 for (k = 0; k < h->long_ref_count; k++)
3944                     if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
3945                         id_list[i] = h->short_ref_count + k;
3946                         break;
3947                     }
3948             }
3949         }
3950
3951         ref2frm[0] =
3952         ref2frm[1] = -1;
3953         for (i = 0; i < 16; i++)
3954             ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
3955         ref2frm[18 + 0] =
3956         ref2frm[18 + 1] = -1;
3957         for (i = 16; i < 48; i++)
3958             ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3959                              (h->ref_list[j][i].reference & 3);
3960     }
3961
3962     if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
3963         av_log(h->avctx, AV_LOG_DEBUG,
3964                "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
3965                h->slice_num,
3966                (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3967                first_mb_in_slice,
3968                av_get_picture_type_char(h->slice_type),
3969                h->slice_type_fixed ? " fix" : "",
3970                h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3971                pps_id, h->frame_num,
3972                h->cur_pic_ptr->field_poc[0],
3973                h->cur_pic_ptr->field_poc[1],
3974                h->ref_count[0], h->ref_count[1],
3975                h->qscale,
3976                h->deblocking_filter,
3977                h->slice_alpha_c0_offset, h->slice_beta_offset,
3978                h->use_weight,
3979                h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3980                h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3981     }
3982
3983     return 0;
3984 }
3985
3986 int ff_h264_get_slice_type(const H264Context *h)
3987 {
3988     switch (h->slice_type) {
3989     case AV_PICTURE_TYPE_P:
3990         return 0;
3991     case AV_PICTURE_TYPE_B:
3992         return 1;
3993     case AV_PICTURE_TYPE_I:
3994         return 2;
3995     case AV_PICTURE_TYPE_SP:
3996         return 3;
3997     case AV_PICTURE_TYPE_SI:
3998         return 4;
3999     default:
4000         return AVERROR_INVALIDDATA;
4001     }
4002 }
4003
4004 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4005                                                       int mb_type, int top_xy,
4006                                                       int left_xy[LEFT_MBS],
4007                                                       int top_type,
4008                                                       int left_type[LEFT_MBS],
4009                                                       int mb_xy, int list)
4010 {
4011     int b_stride = h->b_stride;
4012     int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4013     int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4014     if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4015         if (USES_LIST(top_type, list)) {
4016             const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;
4017             const int b8_xy = 4 * top_xy + 2;
4018             int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
4019             AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4020             ref_cache[0 - 1 * 8] =
4021             ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4022             ref_cache[2 - 1 * 8] =
4023             ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4024         } else {
4025             AV_ZERO128(mv_dst - 1 * 8);
4026             AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4027         }
4028
4029         if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4030             if (USES_LIST(left_type[LTOP], list)) {
4031                 const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;
4032                 const int b8_xy = 4 * left_xy[LTOP] + 1;
4033                 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
4034                 AV_COPY32(mv_dst - 1 +  0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4035                 AV_COPY32(mv_dst - 1 +  8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4036                 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4037                 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4038                 ref_cache[-1 +  0] =
4039                 ref_cache[-1 +  8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4040                 ref_cache[-1 + 16] =
4041                 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4042             } else {
4043                 AV_ZERO32(mv_dst - 1 +  0);
4044                 AV_ZERO32(mv_dst - 1 +  8);
4045                 AV_ZERO32(mv_dst - 1 + 16);
4046                 AV_ZERO32(mv_dst - 1 + 24);
4047                 ref_cache[-1 +  0] =
4048                 ref_cache[-1 +  8] =
4049                 ref_cache[-1 + 16] =
4050                 ref_cache[-1 + 24] = LIST_NOT_USED;
4051             }
4052         }
4053     }
4054
4055     if (!USES_LIST(mb_type, list)) {
4056         fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4057         AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4058         AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4059         AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4060         AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4061         return;
4062     }
4063
4064     {
4065         int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4066         int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
4067         uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4068         uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4069         AV_WN32A(&ref_cache[0 * 8], ref01);
4070         AV_WN32A(&ref_cache[1 * 8], ref01);
4071         AV_WN32A(&ref_cache[2 * 8], ref23);
4072         AV_WN32A(&ref_cache[3 * 8], ref23);
4073     }
4074
4075     {
4076         int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4077         AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4078         AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4079         AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4080         AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4081     }
4082 }
4083
4084 /**
4085  *
4086  * @return non zero if the loop filter can be skipped
4087  */
4088 static int fill_filter_caches(H264Context *h, int mb_type)
4089 {
4090     const int mb_xy = h->mb_xy;
4091     int top_xy, left_xy[LEFT_MBS];
4092     int top_type, left_type[LEFT_MBS];
4093     uint8_t *nnz;
4094     uint8_t *nnz_cache;
4095
4096     top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4097
4098     /* Wow, what a mess, why didn't they simplify the interlacing & intra
4099      * stuff, I can't imagine that these complex rules are worth it. */
4100
4101     left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4102     if (FRAME_MBAFF(h)) {
4103         const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4104         const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4105         if (h->mb_y & 1) {
4106             if (left_mb_field_flag != curr_mb_field_flag)
4107                 left_xy[LTOP] -= h->mb_stride;
4108         } else {
4109             if (curr_mb_field_flag)
4110                 top_xy += h->mb_stride &
4111                           (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4112             if (left_mb_field_flag != curr_mb_field_flag)
4113                 left_xy[LBOT] += h->mb_stride;
4114         }
4115     }
4116
4117     h->top_mb_xy        = top_xy;
4118     h->left_mb_xy[LTOP] = left_xy[LTOP];
4119     h->left_mb_xy[LBOT] = left_xy[LBOT];
4120     {
4121         /* For sufficiently low qp, filtering wouldn't do anything.
4122          * This is a conservative estimate: could also check beta_offset
4123          * and more accurate chroma_qp. */
4124         int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4125         int qp        = h->cur_pic.qscale_table[mb_xy];
4126         if (qp <= qp_thresh &&
4127             (left_xy[LTOP] < 0 ||
4128              ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4129             (top_xy < 0 ||
4130              ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4131             if (!FRAME_MBAFF(h))
4132                 return 1;
4133             if ((left_xy[LTOP] < 0 ||
4134                  ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4135                 (top_xy < h->mb_stride ||
4136                  ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4137                 return 1;
4138         }
4139     }
4140
4141     top_type        = h->cur_pic.mb_type[top_xy];
4142     left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4143     left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4144     if (h->deblocking_filter == 2) {
4145         if (h->slice_table[top_xy] != h->slice_num)
4146             top_type = 0;
4147         if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4148             left_type[LTOP] = left_type[LBOT] = 0;
4149     } else {
4150         if (h->slice_table[top_xy] == 0xFFFF)
4151             top_type = 0;
4152         if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4153             left_type[LTOP] = left_type[LBOT] = 0;
4154     }
4155     h->top_type        = top_type;
4156     h->left_type[LTOP] = left_type[LTOP];
4157     h->left_type[LBOT] = left_type[LBOT];
4158
4159     if (IS_INTRA(mb_type))
4160         return 0;
4161
4162     fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4163                              top_type, left_type, mb_xy, 0);
4164     if (h->list_count == 2)
4165         fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4166                                  top_type, left_type, mb_xy, 1);
4167
4168     nnz       = h->non_zero_count[mb_xy];
4169     nnz_cache = h->non_zero_count_cache;
4170     AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4171     AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4172     AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4173     AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4174     h->cbp = h->cbp_table[mb_xy];
4175
4176     if (top_type) {
4177         nnz = h->non_zero_count[top_xy];
4178         AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4179     }
4180
4181     if (left_type[LTOP]) {
4182         nnz = h->non_zero_count[left_xy[LTOP]];
4183         nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4184         nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4185         nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4186         nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4187     }
4188
4189     /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4190      * from what the loop filter needs */
4191     if (!CABAC(h) && h->pps.transform_8x8_mode) {
4192         if (IS_8x8DCT(top_type)) {
4193             nnz_cache[4 + 8 * 0] =
4194             nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4195             nnz_cache[6 + 8 * 0] =
4196             nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4197         }
4198         if (IS_8x8DCT(left_type[LTOP])) {
4199             nnz_cache[3 + 8 * 1] =
4200             nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4201         }
4202         if (IS_8x8DCT(left_type[LBOT])) {
4203             nnz_cache[3 + 8 * 3] =
4204             nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4205         }
4206
4207         if (IS_8x8DCT(mb_type)) {
4208             nnz_cache[scan8[0]] =
4209             nnz_cache[scan8[1]] =
4210             nnz_cache[scan8[2]] =
4211             nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4212
4213             nnz_cache[scan8[0 + 4]] =
4214             nnz_cache[scan8[1 + 4]] =
4215             nnz_cache[scan8[2 + 4]] =
4216             nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4217
4218             nnz_cache[scan8[0 + 8]] =
4219             nnz_cache[scan8[1 + 8]] =
4220             nnz_cache[scan8[2 + 8]] =
4221             nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4222
4223             nnz_cache[scan8[0 + 12]] =
4224             nnz_cache[scan8[1 + 12]] =
4225             nnz_cache[scan8[2 + 12]] =
4226             nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4227         }
4228     }
4229
4230     return 0;
4231 }
4232
4233 static void loop_filter(H264Context *h, int start_x, int end_x)
4234 {
4235     uint8_t *dest_y, *dest_cb, *dest_cr;
4236     int linesize, uvlinesize, mb_x, mb_y;
4237     const int end_mb_y       = h->mb_y + FRAME_MBAFF(h);
4238     const int old_slice_type = h->slice_type;
4239     const int pixel_shift    = h->pixel_shift;
4240     const int block_h        = 16 >> h->chroma_y_shift;
4241
4242     if (h->deblocking_filter) {
4243         for (mb_x = start_x; mb_x < end_x; mb_x++)
4244             for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4245                 int mb_xy, mb_type;
4246                 mb_xy         = h->mb_xy = mb_x + mb_y * h->mb_stride;
4247                 h->slice_num  = h->slice_table[mb_xy];
4248                 mb_type       = h->cur_pic.mb_type[mb_xy];
4249                 h->list_count = h->list_counts[mb_xy];
4250
4251                 if (FRAME_MBAFF(h))
4252                     h->mb_mbaff               =
4253                     h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4254
4255                 h->mb_x = mb_x;
4256                 h->mb_y = mb_y;
4257                 dest_y  = h->cur_pic.f.data[0] +
4258                           ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4259                 dest_cb = h->cur_pic.f.data[1] +
4260                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4261                           mb_y * h->uvlinesize * block_h;
4262                 dest_cr = h->cur_pic.f.data[2] +
4263                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4264                           mb_y * h->uvlinesize * block_h;
4265                 // FIXME simplify above
4266
4267                 if (MB_FIELD(h)) {
4268                     linesize   = h->mb_linesize   = h->linesize   * 2;
4269                     uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4270                     if (mb_y & 1) { // FIXME move out of this function?
4271                         dest_y  -= h->linesize   * 15;
4272                         dest_cb -= h->uvlinesize * (block_h - 1);
4273                         dest_cr -= h->uvlinesize * (block_h - 1);
4274                     }
4275                 } else {
4276                     linesize   = h->mb_linesize   = h->linesize;
4277                     uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4278                 }
4279                 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4280                                  uvlinesize, 0);
4281                 if (fill_filter_caches(h, mb_type))
4282                     continue;
4283                 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4284                 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4285
4286                 if (FRAME_MBAFF(h)) {
4287                     ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4288                                       linesize, uvlinesize);
4289                 } else {
4290                     ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4291                                            dest_cr, linesize, uvlinesize);
4292                 }
4293             }
4294     }
4295     h->slice_type   = old_slice_type;
4296     h->mb_x         = end_x;
4297     h->mb_y         = end_mb_y - FRAME_MBAFF(h);
4298     h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4299     h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4300 }
4301
4302 static void predict_field_decoding_flag(H264Context *h)
4303 {
4304     const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4305     int mb_type     = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4306                       h->cur_pic.mb_type[mb_xy - 1] :
4307                       (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4308                       h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4309     h->mb_mbaff     = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4310 }
4311
4312 /**
4313  * Draw edges and report progress for the last MB row.
4314  */
4315 static void decode_finish_row(H264Context *h)
4316 {
4317     int top            = 16 * (h->mb_y      >> FIELD_PICTURE(h));
4318     int pic_height     = 16 *  h->mb_height >> FIELD_PICTURE(h);
4319     int height         =  16      << FRAME_MBAFF(h);
4320     int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4321
4322     if (h->deblocking_filter) {
4323         if ((top + height) >= pic_height)
4324             height += deblock_border;
4325         top -= deblock_border;
4326     }
4327
4328     if (top >= pic_height || (top + height) < 0)
4329         return;
4330
4331     height = FFMIN(height, pic_height - top);
4332     if (top < 0) {
4333         height = top + height;
4334         top    = 0;
4335     }
4336
4337     ff_h264_draw_horiz_band(h, top, height);
4338
4339     if (h->droppable)
4340         return;
4341
4342     ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4343                               h->picture_structure == PICT_BOTTOM_FIELD);
4344 }
4345
4346 static void er_add_slice(H264Context *h, int startx, int starty,
4347                          int endx, int endy, int status)
4348 {
4349 #if CONFIG_ERROR_RESILIENCE
4350     ERContext *er = &h->er;
4351
4352     er->ref_count = h->ref_count[0];
4353     ff_er_add_slice(er, startx, starty, endx, endy, status);
4354 #endif
4355 }
4356
4357 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4358 {
4359     H264Context *h = *(void **)arg;
4360     int lf_x_start = h->mb_x;
4361
4362     h->mb_skip_run = -1;
4363
4364     h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4365                     avctx->codec_id != AV_CODEC_ID_H264 ||
4366                     (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4367
4368     if (h->pps.cabac) {
4369         /* realign */
4370         align_get_bits(&h->gb);
4371
4372         /* init cabac */
4373         ff_init_cabac_decoder(&h->cabac,
4374                               h->gb.buffer + get_bits_count(&h->gb) / 8,
4375                               (get_bits_left(&h->gb) + 7) / 8);
4376
4377         ff_h264_init_cabac_states(h);
4378
4379         for (;;) {
4380             // START_TIMER
4381             int ret = ff_h264_decode_mb_cabac(h);
4382             int eos;
4383             // STOP_TIMER("decode_mb_cabac")
4384
4385             if (ret >= 0)
4386                 ff_h264_hl_decode_mb(h);
4387
4388             // FIXME optimal? or let mb_decode decode 16x32 ?
4389             if (ret >= 0 && FRAME_MBAFF(h)) {
4390                 h->mb_y++;
4391
4392                 ret = ff_h264_decode_mb_cabac(h);
4393
4394                 if (ret >= 0)
4395                     ff_h264_hl_decode_mb(h);
4396                 h->mb_y--;
4397             }
4398             eos = get_cabac_terminate(&h->cabac);
4399
4400             if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4401                 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4402                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4403                              h->mb_y, ER_MB_END);
4404                 if (h->mb_x >= lf_x_start)
4405                     loop_filter(h, lf_x_start, h->mb_x + 1);
4406                 return 0;
4407             }
4408             if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4409                 av_log(h->avctx, AV_LOG_ERROR,
4410                        "error while decoding MB %d %d, bytestream %td\n",
4411                        h->mb_x, h->mb_y,
4412                        h->cabac.bytestream_end - h->cabac.bytestream);
4413                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4414                              h->mb_y, ER_MB_ERROR);
4415                 return AVERROR_INVALIDDATA;
4416             }
4417
4418             if (++h->mb_x >= h->mb_width) {
4419                 loop_filter(h, lf_x_start, h->mb_x);
4420                 h->mb_x = lf_x_start = 0;
4421                 decode_finish_row(h);
4422                 ++h->mb_y;
4423                 if (FIELD_OR_MBAFF_PICTURE(h)) {
4424                     ++h->mb_y;
4425                     if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4426                         predict_field_decoding_flag(h);
4427                 }
4428             }
4429
4430             if (eos || h->mb_y >= h->mb_height) {
4431                 tprintf(h->avctx, "slice end %d %d\n",
4432                         get_bits_count(&h->gb), h->gb.size_in_bits);
4433                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4434                              h->mb_y, ER_MB_END);
4435                 if (h->mb_x > lf_x_start)
4436                     loop_filter(h, lf_x_start, h->mb_x);
4437                 return 0;
4438             }
4439         }
4440     } else {
4441         for (;;) {
4442             int ret = ff_h264_decode_mb_cavlc(h);
4443
4444             if (ret >= 0)
4445                 ff_h264_hl_decode_mb(h);
4446
4447             // FIXME optimal? or let mb_decode decode 16x32 ?
4448             if (ret >= 0 && FRAME_MBAFF(h)) {
4449                 h->mb_y++;
4450                 ret = ff_h264_decode_mb_cavlc(h);
4451
4452                 if (ret >= 0)
4453                     ff_h264_hl_decode_mb(h);
4454                 h->mb_y--;
4455             }
4456
4457             if (ret < 0) {
4458                 av_log(h->avctx, AV_LOG_ERROR,
4459                        "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4460                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4461                              h->mb_y, ER_MB_ERROR);
4462                 return ret;
4463             }
4464
4465             if (++h->mb_x >= h->mb_width) {
4466                 loop_filter(h, lf_x_start, h->mb_x);
4467                 h->mb_x = lf_x_start = 0;
4468                 decode_finish_row(h);
4469                 ++h->mb_y;
4470                 if (FIELD_OR_MBAFF_PICTURE(h)) {
4471                     ++h->mb_y;
4472                     if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4473                         predict_field_decoding_flag(h);
4474                 }
4475                 if (h->mb_y >= h->mb_height) {
4476                     tprintf(h->avctx, "slice end %d %d\n",
4477                             get_bits_count(&h->gb), h->gb.size_in_bits);
4478
4479                     if (get_bits_left(&h->gb) == 0) {
4480                         er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4481                                      h->mb_x - 1, h->mb_y,
4482                                      ER_MB_END);
4483
4484                         return 0;
4485                     } else {
4486                         er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4487                                      h->mb_x - 1, h->mb_y,
4488                                      ER_MB_END);
4489
4490                         return AVERROR_INVALIDDATA;
4491                     }
4492                 }
4493             }
4494
4495             if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4496                 tprintf(h->avctx, "slice end %d %d\n",
4497                         get_bits_count(&h->gb), h->gb.size_in_bits);
4498
4499                 if (get_bits_left(&h->gb) == 0) {
4500                     er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4501                                  h->mb_x - 1, h->mb_y,
4502                                  ER_MB_END);
4503                     if (h->mb_x > lf_x_start)
4504                         loop_filter(h, lf_x_start, h->mb_x);
4505
4506                     return 0;
4507                 } else {
4508                     er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4509                                  h->mb_y, ER_MB_ERROR);
4510
4511                     return AVERROR_INVALIDDATA;
4512                 }
4513             }
4514         }
4515     }
4516 }
4517
4518 /**
4519  * Call decode_slice() for each context.
4520  *
4521  * @param h h264 master context
4522  * @param context_count number of contexts to execute
4523  */
4524 static int execute_decode_slices(H264Context *h, unsigned context_count)
4525 {
4526     AVCodecContext *const avctx = h->avctx;
4527     H264Context *hx;
4528     int i;
4529
4530     if (h->mb_y >= h->mb_height) {
4531         av_log(h->avctx, AV_LOG_ERROR,
4532                "Input contains more MB rows than the frame height.\n");
4533         return AVERROR_INVALIDDATA;
4534     }
4535
4536     if (h->avctx->hwaccel)
4537         return 0;
4538     if (context_count == 1) {
4539         return decode_slice(avctx, &h);
4540     } else {
4541         for (i = 1; i < context_count; i++) {
4542             hx                 = h->thread_context[i];
4543             hx->er.error_count = 0;
4544         }
4545
4546         avctx->execute(avctx, decode_slice, h->thread_context,
4547                        NULL, context_count, sizeof(void *));
4548
4549         /* pull back stuff from slices to master context */
4550         hx                   = h->thread_context[context_count - 1];
4551         h->mb_x              = hx->mb_x;
4552         h->mb_y              = hx->mb_y;
4553         h->droppable         = hx->droppable;
4554         h->picture_structure = hx->picture_structure;
4555         for (i = 1; i < context_count; i++)
4556             h->er.error_count += h->thread_context[i]->er.error_count;
4557     }
4558
4559     return 0;
4560 }
4561
4562 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4563                             int parse_extradata)
4564 {
4565     AVCodecContext *const avctx = h->avctx;
4566     H264Context *hx; ///< thread context
4567     int buf_index;
4568     unsigned context_count;
4569     int next_avc;
4570     int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4571     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4572     int nal_index;
4573     int ret = 0;
4574
4575     h->max_contexts = h->slice_context_count;
4576     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4577         h->current_slice = 0;
4578         if (!h->first_field)
4579             h->cur_pic_ptr = NULL;
4580         ff_h264_reset_sei(h);
4581     }
4582
4583     for (; pass <= 1; pass++) {
4584         buf_index     = 0;
4585         context_count = 0;
4586         next_avc      = h->is_avc ? 0 : buf_size;
4587         nal_index     = 0;
4588         for (;;) {
4589             int consumed;
4590             int dst_length;
4591             int bit_length;
4592             const uint8_t *ptr;
4593             int i, nalsize = 0;
4594             int err;
4595
4596             if (buf_index >= next_avc) {
4597                 if (buf_index >= buf_size - h->nal_length_size)
4598                     break;
4599                 nalsize = 0;
4600                 for (i = 0; i < h->nal_length_size; i++)
4601                     nalsize = (nalsize << 8) | buf[buf_index++];
4602                 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4603                     av_log(h->avctx, AV_LOG_ERROR,
4604                            "AVC: nal size %d\n", nalsize);
4605                     break;
4606                 }
4607                 next_avc = buf_index + nalsize;
4608             } else {
4609                 // start code prefix search
4610                 for (; buf_index + 3 < next_avc; buf_index++)
4611                     // This should always succeed in the first iteration.
4612                     if (buf[buf_index]     == 0 &&
4613                         buf[buf_index + 1] == 0 &&
4614                         buf[buf_index + 2] == 1)
4615                         break;
4616
4617                 if (buf_index + 3 >= buf_size) {
4618                     buf_index = buf_size;
4619                     break;
4620                 }
4621
4622                 buf_index += 3;
4623                 if (buf_index >= next_avc)
4624                     continue;
4625             }
4626
4627             hx = h->thread_context[context_count];
4628
4629             ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4630                                      &consumed, next_avc - buf_index);
4631             if (ptr == NULL || dst_length < 0) {
4632                 ret = -1;
4633                 goto end;
4634             }
4635             i = buf_index + consumed;
4636             if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4637                 buf[i]     == 0x00 && buf[i + 1] == 0x00 &&
4638                 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4639                 h->workaround_bugs |= FF_BUG_TRUNCATED;
4640
4641             if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4642                 while (dst_length > 0 && ptr[dst_length - 1] == 0)
4643                     dst_length--;
4644             bit_length = !dst_length ? 0
4645                                      : (8 * dst_length -
4646                                         decode_rbsp_trailing(h, ptr + dst_length - 1));
4647
4648             if (h->avctx->debug & FF_DEBUG_STARTCODE)
4649                 av_log(h->avctx, AV_LOG_DEBUG,
4650                        "NAL %d at %d/%d length %d\n",
4651                        hx->nal_unit_type, buf_index, buf_size, dst_length);
4652
4653             if (h->is_avc && (nalsize != consumed) && nalsize)
4654                 av_log(h->avctx, AV_LOG_DEBUG,
4655                        "AVC: Consumed only %d bytes instead of %d\n",
4656                        consumed, nalsize);
4657
4658             buf_index += consumed;
4659             nal_index++;
4660
4661             if (pass == 0) {
4662                 /* packets can sometimes contain multiple PPS/SPS,
4663                  * e.g. two PAFF field pictures in one packet, or a demuxer
4664                  * which splits NALs strangely if so, when frame threading we
4665                  * can't start the next thread until we've read all of them */
4666                 switch (hx->nal_unit_type) {
4667                 case NAL_SPS:
4668                 case NAL_PPS:
4669                     nals_needed = nal_index;
4670                     break;
4671                 case NAL_DPA:
4672                 case NAL_IDR_SLICE:
4673                 case NAL_SLICE:
4674                     init_get_bits(&hx->gb, ptr, bit_length);
4675                     if (!get_ue_golomb(&hx->gb))
4676                         nals_needed = nal_index;
4677                 }
4678                 continue;
4679             }
4680
4681             if (avctx->skip_frame >= AVDISCARD_NONREF &&
4682                 h->nal_ref_idc == 0 &&
4683                 h->nal_unit_type != NAL_SEI)
4684                 continue;
4685
4686 again:
4687             /* Ignore every NAL unit type except PPS and SPS during extradata
4688              * parsing. Decoding slices is not possible in codec init
4689              * with frame-mt */
4690             if (parse_extradata && HAVE_THREADS &&
4691                 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
4692                 (hx->nal_unit_type != NAL_PPS &&
4693                  hx->nal_unit_type != NAL_SPS)) {
4694                 if (hx->nal_unit_type < NAL_AUD ||
4695                     hx->nal_unit_type > NAL_AUXILIARY_SLICE)
4696                     av_log(avctx, AV_LOG_INFO,
4697                            "Ignoring NAL unit %d during extradata parsing\n",
4698                            hx->nal_unit_type);
4699                 hx->nal_unit_type = NAL_FF_IGNORE;
4700             }
4701             err = 0;
4702             switch (hx->nal_unit_type) {
4703             case NAL_IDR_SLICE:
4704                 if (h->nal_unit_type != NAL_IDR_SLICE) {
4705                     av_log(h->avctx, AV_LOG_ERROR,
4706                            "Invalid mix of idr and non-idr slices\n");
4707                     ret = -1;
4708                     goto end;
4709                 }
4710                 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4711             case NAL_SLICE:
4712                 init_get_bits(&hx->gb, ptr, bit_length);
4713                 hx->intra_gb_ptr      =
4714                 hx->inter_gb_ptr      = &hx->gb;
4715                 hx->data_partitioning = 0;
4716
4717                 if ((err = decode_slice_header(hx, h)))
4718                     break;
4719
4720                 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
4721                     h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4722                                         ((1 << h->sps.log2_max_frame_num) - 1);
4723                 }
4724
4725                 h->cur_pic_ptr->f.key_frame |=
4726                     (hx->nal_unit_type == NAL_IDR_SLICE) ||
4727                     (h->sei_recovery_frame_cnt >= 0);
4728
4729                 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4730                     h->recovery_frame == h->frame_num) {
4731                     h->recovery_frame         = -1;
4732                     h->cur_pic_ptr->recovered = 1;
4733                 }
4734                 // If we have an IDR, all frames after it in decoded order are
4735                 // "recovered".
4736                 if (hx->nal_unit_type == NAL_IDR_SLICE)
4737                     h->frame_recovered |= FRAME_RECOVERED_IDR;
4738                 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4739
4740                 if (h->current_slice == 1) {
4741                     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4742                         decode_postinit(h, nal_index >= nals_needed);
4743
4744                     if (h->avctx->hwaccel &&
4745                         (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4746                         return ret;
4747                 }
4748
4749                 if (hx->redundant_pic_count == 0 &&
4750                     (avctx->skip_frame < AVDISCARD_NONREF ||
4751                      hx->nal_ref_idc) &&
4752                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
4753                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4754                     (avctx->skip_frame < AVDISCARD_NONKEY ||
4755                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4756                     avctx->skip_frame < AVDISCARD_ALL) {
4757                     if (avctx->hwaccel) {
4758                         ret = avctx->hwaccel->decode_slice(avctx,
4759                                                            &buf[buf_index - consumed],
4760                                                            consumed);
4761                         if (ret < 0)
4762                             return ret;
4763                     } else
4764                         context_count++;
4765                 }
4766                 break;
4767             case NAL_DPA:
4768                 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
4769                     av_log(h->avctx, AV_LOG_ERROR,
4770                            "Decoding in chunks is not supported for "
4771                            "partitioned slices.\n");
4772                     return AVERROR(ENOSYS);
4773                 }
4774
4775                 init_get_bits(&hx->gb, ptr, bit_length);
4776                 hx->intra_gb_ptr =
4777                 hx->inter_gb_ptr = NULL;
4778
4779                 if ((err = decode_slice_header(hx, h)) < 0) {
4780                     /* make sure data_partitioning is cleared if it was set
4781                      * before, so we don't try decoding a slice without a valid
4782                      * slice header later */
4783                     h->data_partitioning = 0;
4784                     break;
4785                 }
4786
4787                 hx->data_partitioning = 1;
4788                 break;
4789             case NAL_DPB:
4790                 init_get_bits(&hx->intra_gb, ptr, bit_length);
4791                 hx->intra_gb_ptr = &hx->intra_gb;
4792                 break;
4793             case NAL_DPC:
4794                 init_get_bits(&hx->inter_gb, ptr, bit_length);
4795                 hx->inter_gb_ptr = &hx->inter_gb;
4796
4797                 if (hx->redundant_pic_count == 0 &&
4798                     hx->intra_gb_ptr &&
4799                     hx->data_partitioning &&
4800                     h->cur_pic_ptr && h->context_initialized &&
4801                     (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4802                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
4803                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4804                     (avctx->skip_frame < AVDISCARD_NONKEY ||
4805                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4806                     avctx->skip_frame < AVDISCARD_ALL)
4807                     context_count++;
4808                 break;
4809             case NAL_SEI:
4810                 init_get_bits(&h->gb, ptr, bit_length);
4811                 ff_h264_decode_sei(h);
4812                 break;
4813             case NAL_SPS:
4814                 init_get_bits(&h->gb, ptr, bit_length);
4815                 ret = ff_h264_decode_seq_parameter_set(h);
4816                 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
4817                     av_log(h->avctx, AV_LOG_DEBUG,
4818                            "SPS decoding failure, trying again with the complete NAL\n");
4819                     init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
4820                                   8 * (nalsize - 1));
4821                     ff_h264_decode_seq_parameter_set(h);
4822                 }
4823
4824                 ret = h264_set_parameter_from_sps(h);
4825                 if (ret < 0)
4826                     goto end;
4827
4828                 break;
4829             case NAL_PPS:
4830                 init_get_bits(&h->gb, ptr, bit_length);
4831                 ff_h264_decode_picture_parameter_set(h, bit_length);
4832                 break;
4833             case NAL_AUD:
4834             case NAL_END_SEQUENCE:
4835             case NAL_END_STREAM:
4836             case NAL_FILLER_DATA:
4837             case NAL_SPS_EXT:
4838             case NAL_AUXILIARY_SLICE:
4839                 break;
4840             case NAL_FF_IGNORE:
4841                 break;
4842             default:
4843                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4844                        hx->nal_unit_type, bit_length);
4845             }
4846
4847             if (context_count == h->max_contexts) {
4848                 execute_decode_slices(h, context_count);
4849                 context_count = 0;
4850             }
4851
4852             if (err < 0) {
4853                 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4854                 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
4855             } else if (err == 1) {
4856                 /* Slice could not be decoded in parallel mode, copy down
4857                  * NAL unit stuff to context 0 and restart. Note that
4858                  * rbsp_buffer is not transferred, but since we no longer
4859                  * run in parallel mode this should not be an issue. */
4860                 h->nal_unit_type = hx->nal_unit_type;
4861                 h->nal_ref_idc   = hx->nal_ref_idc;
4862                 hx               = h;
4863                 goto again;
4864             }
4865         }
4866     }
4867     if (context_count)
4868         execute_decode_slices(h, context_count);
4869
4870 end:
4871     /* clean up */
4872     if (h->cur_pic_ptr && !h->droppable) {
4873         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
4874                                   h->picture_structure == PICT_BOTTOM_FIELD);
4875     }
4876
4877     return (ret < 0) ? ret : buf_index;
4878 }
4879
4880 /**
4881  * Return the number of bytes consumed for building the current frame.
4882  */
4883 static int get_consumed_bytes(int pos, int buf_size)
4884 {
4885     if (pos == 0)
4886         pos = 1;          // avoid infinite loops (i doubt that is needed but ...)
4887     if (pos + 10 > buf_size)
4888         pos = buf_size;                   // oops ;)
4889
4890     return pos;
4891 }
4892
4893 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
4894 {
4895     int i;
4896     int ret = av_frame_ref(dst, src);
4897     if (ret < 0)
4898         return ret;
4899
4900     if (!h->sps.crop)
4901         return 0;
4902
4903     for (i = 0; i < 3; i++) {
4904         int hshift = (i > 0) ? h->chroma_x_shift : 0;
4905         int vshift = (i > 0) ? h->chroma_y_shift : 0;
4906         int off    = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
4907                      (h->sps.crop_top >> vshift) * dst->linesize[i];
4908         dst->data[i] += off;
4909     }
4910     return 0;
4911 }
4912
4913 static int h264_decode_frame(AVCodecContext *avctx, void *data,
4914                              int *got_frame, AVPacket *avpkt)
4915 {
4916     const uint8_t *buf = avpkt->data;
4917     int buf_size       = avpkt->size;
4918     H264Context *h     = avctx->priv_data;
4919     AVFrame *pict      = data;
4920     int buf_index      = 0;
4921     int ret;
4922
4923     h->flags = avctx->flags;
4924     /* reset data partitioning here, to ensure GetBitContexts from previous
4925      * packets do not get used. */
4926     h->data_partitioning = 0;
4927
4928     /* end of stream, output what is still in the buffers */
4929 out:
4930     if (buf_size == 0) {
4931         H264Picture *out;
4932         int i, out_idx;
4933
4934         h->cur_pic_ptr = NULL;
4935
4936         // FIXME factorize this with the output code below
4937         out     = h->delayed_pic[0];
4938         out_idx = 0;
4939         for (i = 1;
4940              h->delayed_pic[i] &&
4941              !h->delayed_pic[i]->f.key_frame &&
4942              !h->delayed_pic[i]->mmco_reset;
4943              i++)
4944             if (h->delayed_pic[i]->poc < out->poc) {
4945                 out     = h->delayed_pic[i];
4946                 out_idx = i;
4947             }
4948
4949         for (i = out_idx; h->delayed_pic[i]; i++)
4950             h->delayed_pic[i] = h->delayed_pic[i + 1];
4951
4952         if (out) {
4953             ret = output_frame(h, pict, &out->f);
4954             if (ret < 0)
4955                 return ret;
4956             *got_frame = 1;
4957         }
4958
4959         return buf_index;
4960     }
4961
4962     buf_index = decode_nal_units(h, buf, buf_size, 0);
4963     if (buf_index < 0)
4964         return AVERROR_INVALIDDATA;
4965
4966     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4967         buf_size = 0;
4968         goto out;
4969     }
4970
4971     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
4972         if (avctx->skip_frame >= AVDISCARD_NONREF)
4973             return 0;
4974         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4975         return AVERROR_INVALIDDATA;
4976     }
4977
4978     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
4979         (h->mb_y >= h->mb_height && h->mb_height)) {
4980         if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
4981             decode_postinit(h, 1);
4982
4983         field_end(h, 0);
4984
4985         *got_frame = 0;
4986         if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
4987                                    h->next_output_pic->recovered)) {
4988             if (!h->next_output_pic->recovered)
4989                 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
4990
4991             ret = output_frame(h, pict, &h->next_output_pic->f);
4992             if (ret < 0)
4993                 return ret;
4994             *got_frame = 1;
4995         }
4996     }
4997
4998     assert(pict->buf[0] || !*got_frame);
4999
5000     return get_consumed_bytes(buf_index, buf_size);
5001 }
5002
5003 av_cold void ff_h264_free_context(H264Context *h)
5004 {
5005     int i;
5006
5007     free_tables(h, 1); // FIXME cleanup init stuff perhaps
5008
5009     for (i = 0; i < MAX_SPS_COUNT; i++)
5010         av_freep(h->sps_buffers + i);
5011
5012     for (i = 0; i < MAX_PPS_COUNT; i++)
5013         av_freep(h->pps_buffers + i);
5014 }
5015
5016 static av_cold int h264_decode_end(AVCodecContext *avctx)
5017 {
5018     H264Context *h = avctx->priv_data;
5019
5020     ff_h264_free_context(h);
5021
5022     unref_picture(h, &h->cur_pic);
5023
5024     return 0;
5025 }
5026
5027 static const AVProfile profiles[] = {
5028     { FF_PROFILE_H264_BASELINE,             "Baseline"              },
5029     { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
5030     { FF_PROFILE_H264_MAIN,                 "Main"                  },
5031     { FF_PROFILE_H264_EXTENDED,             "Extended"              },
5032     { FF_PROFILE_H264_HIGH,                 "High"                  },
5033     { FF_PROFILE_H264_HIGH_10,              "High 10"               },
5034     { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
5035     { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
5036     { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
5037     { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
5038     { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
5039     { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
5040     { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
5041     { FF_PROFILE_UNKNOWN },
5042 };
5043
5044 AVCodec ff_h264_decoder = {
5045     .name                  = "h264",
5046     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5047     .type                  = AVMEDIA_TYPE_VIDEO,
5048     .id                    = AV_CODEC_ID_H264,
5049     .priv_data_size        = sizeof(H264Context),
5050     .init                  = ff_h264_decode_init,
5051     .close                 = h264_decode_end,
5052     .decode                = h264_decode_frame,
5053     .capabilities          = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5054                              CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5055                              CODEC_CAP_FRAME_THREADS,
5056     .flush                 = flush_dpb,
5057     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5058     .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5059     .profiles              = NULL_IF_CONFIG_SMALL(profiles),
5060 };