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