]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
Merge remote-tracking branch 'qatar/master'
[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 ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1976         return ret;
1977
1978     if (CONFIG_ERROR_RESILIENCE) {
1979         ff_er_frame_start(&h->er);
1980         h->er.last_pic =
1981         h->er.next_pic = NULL;
1982     }
1983
1984     assert(h->linesize && h->uvlinesize);
1985
1986     for (i = 0; i < 16; i++) {
1987         h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1988         h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1989     }
1990     for (i = 0; i < 16; i++) {
1991         h->block_offset[16 + i]      =
1992         h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1993         h->block_offset[48 + 16 + i] =
1994         h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1995     }
1996
1997     // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1998     //             h->cur_pic.reference /* || h->contains_intra */ || 1;
1999
2000     /* We mark the current picture as non-reference after allocating it, so
2001      * that if we break out due to an error it can be released automatically
2002      * in the next ff_MPV_frame_start().
2003      */
2004     h->cur_pic_ptr->reference = 0;
2005
2006     h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
2007
2008     h->next_output_pic = NULL;
2009
2010     assert(h->cur_pic_ptr->long_ref == 0);
2011
2012     return 0;
2013 }
2014
2015 /**
2016  * Run setup operations that must be run after slice header decoding.
2017  * This includes finding the next displayed frame.
2018  *
2019  * @param h h264 master context
2020  * @param setup_finished enough NALs have been read that we can call
2021  * ff_thread_finish_setup()
2022  */
2023 static void decode_postinit(H264Context *h, int setup_finished)
2024 {
2025     Picture *out = h->cur_pic_ptr;
2026     Picture *cur = h->cur_pic_ptr;
2027     int i, pics, out_of_order, out_idx;
2028
2029     h->cur_pic_ptr->f.pict_type = h->pict_type;
2030
2031     if (h->next_output_pic)
2032         return;
2033
2034     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2035         /* FIXME: if we have two PAFF fields in one packet, we can't start
2036          * the next thread here. If we have one field per packet, we can.
2037          * The check in decode_nal_units() is not good enough to find this
2038          * yet, so we assume the worst for now. */
2039         // if (setup_finished)
2040         //    ff_thread_finish_setup(h->avctx);
2041         return;
2042     }
2043
2044     cur->f.interlaced_frame = 0;
2045     cur->f.repeat_pict      = 0;
2046
2047     /* Signal interlacing information externally. */
2048     /* Prioritize picture timing SEI information over used
2049      * decoding process if it exists. */
2050
2051     if (h->sps.pic_struct_present_flag) {
2052         switch (h->sei_pic_struct) {
2053         case SEI_PIC_STRUCT_FRAME:
2054             break;
2055         case SEI_PIC_STRUCT_TOP_FIELD:
2056         case SEI_PIC_STRUCT_BOTTOM_FIELD:
2057             cur->f.interlaced_frame = 1;
2058             break;
2059         case SEI_PIC_STRUCT_TOP_BOTTOM:
2060         case SEI_PIC_STRUCT_BOTTOM_TOP:
2061             if (FIELD_OR_MBAFF_PICTURE(h))
2062                 cur->f.interlaced_frame = 1;
2063             else
2064                 // try to flag soft telecine progressive
2065                 cur->f.interlaced_frame = h->prev_interlaced_frame;
2066             break;
2067         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
2068         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
2069             /* Signal the possibility of telecined film externally
2070              * (pic_struct 5,6). From these hints, let the applications
2071              * decide if they apply deinterlacing. */
2072             cur->f.repeat_pict = 1;
2073             break;
2074         case SEI_PIC_STRUCT_FRAME_DOUBLING:
2075             cur->f.repeat_pict = 2;
2076             break;
2077         case SEI_PIC_STRUCT_FRAME_TRIPLING:
2078             cur->f.repeat_pict = 4;
2079             break;
2080         }
2081
2082         if ((h->sei_ct_type & 3) &&
2083             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2084             cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2085     } else {
2086         /* Derive interlacing flag from used decoding process. */
2087         cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2088     }
2089     h->prev_interlaced_frame = cur->f.interlaced_frame;
2090
2091     if (cur->field_poc[0] != cur->field_poc[1]) {
2092         /* Derive top_field_first from field pocs. */
2093         cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2094     } else {
2095         if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2096             /* Use picture timing SEI information. Even if it is a
2097              * information of a past frame, better than nothing. */
2098             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2099                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2100                 cur->f.top_field_first = 1;
2101             else
2102                 cur->f.top_field_first = 0;
2103         } else {
2104             /* Most likely progressive */
2105             cur->f.top_field_first = 0;
2106         }
2107     }
2108
2109     if (h->sei_frame_packing_present &&
2110         h->frame_packing_arrangement_type >= 0 &&
2111         h->frame_packing_arrangement_type <= 6 &&
2112         h->content_interpretation_type > 0 &&
2113         h->content_interpretation_type < 3) {
2114         AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
2115         if (!stereo)
2116             return;
2117
2118         switch (h->frame_packing_arrangement_type) {
2119         case 0:
2120             stereo->type = AV_STEREO3D_CHECKERBOARD;
2121             break;
2122         case 1:
2123             stereo->type = AV_STEREO3D_LINES;
2124             break;
2125         case 2:
2126             stereo->type = AV_STEREO3D_COLUMNS;
2127             break;
2128         case 3:
2129             if (h->quincunx_subsampling)
2130                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2131             else
2132                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
2133             break;
2134         case 4:
2135             stereo->type = AV_STEREO3D_TOPBOTTOM;
2136             break;
2137         case 5:
2138             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
2139             break;
2140         case 6:
2141             stereo->type = AV_STEREO3D_2D;
2142             break;
2143         }
2144
2145         if (h->content_interpretation_type == 2)
2146             stereo->flags = AV_STEREO3D_FLAG_INVERT;
2147     }
2148
2149     cur->mmco_reset = h->mmco_reset;
2150     h->mmco_reset = 0;
2151
2152     // FIXME do something with unavailable reference frames
2153
2154     /* Sort B-frames into display order */
2155
2156     if (h->sps.bitstream_restriction_flag &&
2157         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2158         h->avctx->has_b_frames = h->sps.num_reorder_frames;
2159         h->low_delay           = 0;
2160     }
2161
2162     if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2163         !h->sps.bitstream_restriction_flag) {
2164         h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2165         h->low_delay           = 0;
2166     }
2167
2168     for (i = 0; 1; i++) {
2169         if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2170             if(i)
2171                 h->last_pocs[i-1] = cur->poc;
2172             break;
2173         } else if(i) {
2174             h->last_pocs[i-1]= h->last_pocs[i];
2175         }
2176     }
2177     out_of_order = MAX_DELAYED_PIC_COUNT - i;
2178     if(   cur->f.pict_type == AV_PICTURE_TYPE_B
2179        || (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))
2180         out_of_order = FFMAX(out_of_order, 1);
2181     if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2182         av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2183         for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2184             h->last_pocs[i] = INT_MIN;
2185         h->last_pocs[0] = cur->poc;
2186         cur->mmco_reset = 1;
2187     } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2188         av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2189         h->avctx->has_b_frames = out_of_order;
2190         h->low_delay = 0;
2191     }
2192
2193     pics = 0;
2194     while (h->delayed_pic[pics])
2195         pics++;
2196
2197     av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2198
2199     h->delayed_pic[pics++] = cur;
2200     if (cur->reference == 0)
2201         cur->reference = DELAYED_PIC_REF;
2202
2203     out     = h->delayed_pic[0];
2204     out_idx = 0;
2205     for (i = 1; h->delayed_pic[i] &&
2206                 !h->delayed_pic[i]->f.key_frame &&
2207                 !h->delayed_pic[i]->mmco_reset;
2208          i++)
2209         if (h->delayed_pic[i]->poc < out->poc) {
2210             out     = h->delayed_pic[i];
2211             out_idx = i;
2212         }
2213     if (h->avctx->has_b_frames == 0 &&
2214         (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2215         h->next_outputed_poc = INT_MIN;
2216     out_of_order = out->poc < h->next_outputed_poc;
2217
2218     if (out_of_order || pics > h->avctx->has_b_frames) {
2219         out->reference &= ~DELAYED_PIC_REF;
2220         // for frame threading, the owner must be the second field's thread or
2221         // else the first thread can release the picture and reuse it unsafely
2222         for (i = out_idx; h->delayed_pic[i]; i++)
2223             h->delayed_pic[i] = h->delayed_pic[i + 1];
2224     }
2225     if (!out_of_order && pics > h->avctx->has_b_frames) {
2226         h->next_output_pic = out;
2227         if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2228             h->next_outputed_poc = INT_MIN;
2229         } else
2230             h->next_outputed_poc = out->poc;
2231     } else {
2232         av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2233     }
2234
2235     if (h->next_output_pic) {
2236         if (h->next_output_pic->recovered) {
2237             // We have reached an recovery point and all frames after it in
2238             // display order are "recovered".
2239             h->frame_recovered |= FRAME_RECOVERED_SEI;
2240         }
2241         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2242     }
2243
2244     if (setup_finished && !h->avctx->hwaccel)
2245         ff_thread_finish_setup(h->avctx);
2246 }
2247
2248 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2249                                               uint8_t *src_cb, uint8_t *src_cr,
2250                                               int linesize, int uvlinesize,
2251                                               int simple)
2252 {
2253     uint8_t *top_border;
2254     int top_idx = 1;
2255     const int pixel_shift = h->pixel_shift;
2256     int chroma444 = CHROMA444(h);
2257     int chroma422 = CHROMA422(h);
2258
2259     src_y  -= linesize;
2260     src_cb -= uvlinesize;
2261     src_cr -= uvlinesize;
2262
2263     if (!simple && FRAME_MBAFF(h)) {
2264         if (h->mb_y & 1) {
2265             if (!MB_MBAFF(h)) {
2266                 top_border = h->top_borders[0][h->mb_x];
2267                 AV_COPY128(top_border, src_y + 15 * linesize);
2268                 if (pixel_shift)
2269                     AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2270                 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2271                     if (chroma444) {
2272                         if (pixel_shift) {
2273                             AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2274                             AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2275                             AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2276                             AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2277                         } else {
2278                             AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2279                             AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2280                         }
2281                     } else if (chroma422) {
2282                         if (pixel_shift) {
2283                             AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2284                             AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2285                         } else {
2286                             AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2287                             AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2288                         }
2289                     } else {
2290                         if (pixel_shift) {
2291                             AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2292                             AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2293                         } else {
2294                             AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2295                             AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2296                         }
2297                     }
2298                 }
2299             }
2300         } else if (MB_MBAFF(h)) {
2301             top_idx = 0;
2302         } else
2303             return;
2304     }
2305
2306     top_border = h->top_borders[top_idx][h->mb_x];
2307     /* There are two lines saved, the line above the top macroblock
2308      * of a pair, and the line above the bottom macroblock. */
2309     AV_COPY128(top_border, src_y + 16 * linesize);
2310     if (pixel_shift)
2311         AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2312
2313     if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2314         if (chroma444) {
2315             if (pixel_shift) {
2316                 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2317                 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2318                 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2319                 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2320             } else {
2321                 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2322                 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2323             }
2324         } else if (chroma422) {
2325             if (pixel_shift) {
2326                 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2327                 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2328             } else {
2329                 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2330                 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2331             }
2332         } else {
2333             if (pixel_shift) {
2334                 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2335                 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2336             } else {
2337                 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2338                 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2339             }
2340         }
2341     }
2342 }
2343
2344 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2345                                             uint8_t *src_cb, uint8_t *src_cr,
2346                                             int linesize, int uvlinesize,
2347                                             int xchg, int chroma444,
2348                                             int simple, int pixel_shift)
2349 {
2350     int deblock_topleft;
2351     int deblock_top;
2352     int top_idx = 1;
2353     uint8_t *top_border_m1;
2354     uint8_t *top_border;
2355
2356     if (!simple && FRAME_MBAFF(h)) {
2357         if (h->mb_y & 1) {
2358             if (!MB_MBAFF(h))
2359                 return;
2360         } else {
2361             top_idx = MB_MBAFF(h) ? 0 : 1;
2362         }
2363     }
2364
2365     if (h->deblocking_filter == 2) {
2366         deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2367         deblock_top     = h->top_type;
2368     } else {
2369         deblock_topleft = (h->mb_x > 0);
2370         deblock_top     = (h->mb_y > !!MB_FIELD(h));
2371     }
2372
2373     src_y  -= linesize   + 1 + pixel_shift;
2374     src_cb -= uvlinesize + 1 + pixel_shift;
2375     src_cr -= uvlinesize + 1 + pixel_shift;
2376
2377     top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2378     top_border    = h->top_borders[top_idx][h->mb_x];
2379
2380 #define XCHG(a, b, xchg)                        \
2381     if (pixel_shift) {                          \
2382         if (xchg) {                             \
2383             AV_SWAP64(b + 0, a + 0);            \
2384             AV_SWAP64(b + 8, a + 8);            \
2385         } else {                                \
2386             AV_COPY128(b, a);                   \
2387         }                                       \
2388     } else if (xchg)                            \
2389         AV_SWAP64(b, a);                        \
2390     else                                        \
2391         AV_COPY64(b, a);
2392
2393     if (deblock_top) {
2394         if (deblock_topleft) {
2395             XCHG(top_border_m1 + (8 << pixel_shift),
2396                  src_y - (7 << pixel_shift), 1);
2397         }
2398         XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2399         XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2400         if (h->mb_x + 1 < h->mb_width) {
2401             XCHG(h->top_borders[top_idx][h->mb_x + 1],
2402                  src_y + (17 << pixel_shift), 1);
2403         }
2404         if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2405             if (chroma444) {
2406                 if (deblock_topleft) {
2407                     XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2408                     XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2409                 }
2410                 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2411                 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2412                 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2413                 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2414                 if (h->mb_x + 1 < h->mb_width) {
2415                     XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2416                     XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2417                 }
2418             } else {
2419                 if (deblock_topleft) {
2420                     XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2421                     XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2422                 }
2423                 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2424                 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2425             }
2426         }
2427     }
2428 }
2429
2430 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2431                                         int index)
2432 {
2433     if (high_bit_depth) {
2434         return AV_RN32A(((int32_t *)mb) + index);
2435     } else
2436         return AV_RN16A(mb + index);
2437 }
2438
2439 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2440                                          int index, int value)
2441 {
2442     if (high_bit_depth) {
2443         AV_WN32A(((int32_t *)mb) + index, value);
2444     } else
2445         AV_WN16A(mb + index, value);
2446 }
2447
2448 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2449                                                        int mb_type, int is_h264,
2450                                                        int simple,
2451                                                        int transform_bypass,
2452                                                        int pixel_shift,
2453                                                        int *block_offset,
2454                                                        int linesize,
2455                                                        uint8_t *dest_y, int p)
2456 {
2457     void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2458     void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2459     int i;
2460     int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2461     block_offset += 16 * p;
2462     if (IS_INTRA4x4(mb_type)) {
2463         if (IS_8x8DCT(mb_type)) {
2464             if (transform_bypass) {
2465                 idct_dc_add =
2466                 idct_add    = h->h264dsp.h264_add_pixels8_clear;
2467             } else {
2468                 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2469                 idct_add    = h->h264dsp.h264_idct8_add;
2470             }
2471             for (i = 0; i < 16; i += 4) {
2472                 uint8_t *const ptr = dest_y + block_offset[i];
2473                 const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
2474                 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2475                     h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2476                 } else {
2477                     const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2478                     h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2479                                          (h->topright_samples_available << i) & 0x4000, linesize);
2480                     if (nnz) {
2481                         if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2482                             idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2483                         else
2484                             idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2485                     }
2486                 }
2487             }
2488         } else {
2489             if (transform_bypass) {
2490                 idct_dc_add  =
2491                 idct_add     = h->h264dsp.h264_add_pixels4_clear;
2492             } else {
2493                 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2494                 idct_add    = h->h264dsp.h264_idct_add;
2495             }
2496             for (i = 0; i < 16; i++) {
2497                 uint8_t *const ptr = dest_y + block_offset[i];
2498                 const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
2499
2500                 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2501                     h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2502                 } else {
2503                     uint8_t *topright;
2504                     int nnz, tr;
2505                     uint64_t tr_high;
2506                     if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2507                         const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2508                         av_assert2(h->mb_y || linesize <= block_offset[i]);
2509                         if (!topright_avail) {
2510                             if (pixel_shift) {
2511                                 tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2512                                 topright = (uint8_t *)&tr_high;
2513                             } else {
2514                                 tr       = ptr[3 - linesize] * 0x01010101u;
2515                                 topright = (uint8_t *)&tr;
2516                             }
2517                         } else
2518                             topright = ptr + (4 << pixel_shift) - linesize;
2519                     } else
2520                         topright = NULL;
2521
2522                     h->hpc.pred4x4[dir](ptr, topright, linesize);
2523                     nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2524                     if (nnz) {
2525                         if (is_h264) {
2526                             if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2527                                 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2528                             else
2529                                 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2530                         } else if (CONFIG_SVQ3_DECODER)
2531                             ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2532                     }
2533                 }
2534             }
2535         }
2536     } else {
2537         h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2538         if (is_h264) {
2539             if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2540                 if (!transform_bypass)
2541                     h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2542                                                          h->mb_luma_dc[p],
2543                                                          h->dequant4_coeff[p][qscale][0]);
2544                 else {
2545                     static const uint8_t dc_mapping[16] = {
2546                          0 * 16,  1 * 16,  4 * 16,  5 * 16,
2547                          2 * 16,  3 * 16,  6 * 16,  7 * 16,
2548                          8 * 16,  9 * 16, 12 * 16, 13 * 16,
2549                         10 * 16, 11 * 16, 14 * 16, 15 * 16
2550                     };
2551                     for (i = 0; i < 16; i++)
2552                         dctcoef_set(h->mb + (p * 256 << pixel_shift),
2553                                     pixel_shift, dc_mapping[i],
2554                                     dctcoef_get(h->mb_luma_dc[p],
2555                                                 pixel_shift, i));
2556                 }
2557             }
2558         } else if (CONFIG_SVQ3_DECODER)
2559             ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2560                                            h->mb_luma_dc[p], qscale);
2561     }
2562 }
2563
2564 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2565                                                     int is_h264, int simple,
2566                                                     int transform_bypass,
2567                                                     int pixel_shift,
2568                                                     int *block_offset,
2569                                                     int linesize,
2570                                                     uint8_t *dest_y, int p)
2571 {
2572     void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2573     int i;
2574     block_offset += 16 * p;
2575     if (!IS_INTRA4x4(mb_type)) {
2576         if (is_h264) {
2577             if (IS_INTRA16x16(mb_type)) {
2578                 if (transform_bypass) {
2579                     if (h->sps.profile_idc == 244 &&
2580                         (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2581                          h->intra16x16_pred_mode == HOR_PRED8x8)) {
2582                         h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2583                                                                       h->mb + (p * 256 << pixel_shift),
2584                                                                       linesize);
2585                     } else {
2586                         for (i = 0; i < 16; i++)
2587                             if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2588                                 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2589                                 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2590                                                                   h->mb + (i * 16 + p * 256 << pixel_shift),
2591                                                                   linesize);
2592                     }
2593                 } else {
2594                     h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2595                                                     h->mb + (p * 256 << pixel_shift),
2596                                                     linesize,
2597                                                     h->non_zero_count_cache + p * 5 * 8);
2598                 }
2599             } else if (h->cbp & 15) {
2600                 if (transform_bypass) {
2601                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2602                     idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2603                                                   : h->h264dsp.h264_add_pixels4_clear;
2604                     for (i = 0; i < 16; i += di)
2605                         if (h->non_zero_count_cache[scan8[i + p * 16]])
2606                             idct_add(dest_y + block_offset[i],
2607                                      h->mb + (i * 16 + p * 256 << pixel_shift),
2608                                      linesize);
2609                 } else {
2610                     if (IS_8x8DCT(mb_type))
2611                         h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2612                                                    h->mb + (p * 256 << pixel_shift),
2613                                                    linesize,
2614                                                    h->non_zero_count_cache + p * 5 * 8);
2615                     else
2616                         h->h264dsp.h264_idct_add16(dest_y, block_offset,
2617                                                    h->mb + (p * 256 << pixel_shift),
2618                                                    linesize,
2619                                                    h->non_zero_count_cache + p * 5 * 8);
2620                 }
2621             }
2622         } else if (CONFIG_SVQ3_DECODER) {
2623             for (i = 0; i < 16; i++)
2624                 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2625                     // FIXME benchmark weird rule, & below
2626                     uint8_t *const ptr = dest_y + block_offset[i];
2627                     ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2628                                        h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2629                 }
2630         }
2631     }
2632 }
2633
2634 #define BITS   8
2635 #define SIMPLE 1
2636 #include "h264_mb_template.c"
2637
2638 #undef  BITS
2639 #define BITS   16
2640 #include "h264_mb_template.c"
2641
2642 #undef  SIMPLE
2643 #define SIMPLE 0
2644 #include "h264_mb_template.c"
2645
2646 void ff_h264_hl_decode_mb(H264Context *h)
2647 {
2648     const int mb_xy   = h->mb_xy;
2649     const int mb_type = h->cur_pic.mb_type[mb_xy];
2650     int is_complex    = CONFIG_SMALL || h->is_complex ||
2651                         IS_INTRA_PCM(mb_type) || h->qscale == 0;
2652
2653     if (CHROMA444(h)) {
2654         if (is_complex || h->pixel_shift)
2655             hl_decode_mb_444_complex(h);
2656         else
2657             hl_decode_mb_444_simple_8(h);
2658     } else if (is_complex) {
2659         hl_decode_mb_complex(h);
2660     } else if (h->pixel_shift) {
2661         hl_decode_mb_simple_16(h);
2662     } else
2663         hl_decode_mb_simple_8(h);
2664 }
2665
2666 int ff_pred_weight_table(H264Context *h)
2667 {
2668     int list, i;
2669     int luma_def, chroma_def;
2670
2671     h->use_weight             = 0;
2672     h->use_weight_chroma      = 0;
2673     h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2674     if (h->sps.chroma_format_idc)
2675         h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2676     luma_def   = 1 << h->luma_log2_weight_denom;
2677     chroma_def = 1 << h->chroma_log2_weight_denom;
2678
2679     for (list = 0; list < 2; list++) {
2680         h->luma_weight_flag[list]   = 0;
2681         h->chroma_weight_flag[list] = 0;
2682         for (i = 0; i < h->ref_count[list]; i++) {
2683             int luma_weight_flag, chroma_weight_flag;
2684
2685             luma_weight_flag = get_bits1(&h->gb);
2686             if (luma_weight_flag) {
2687                 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2688                 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2689                 if (h->luma_weight[i][list][0] != luma_def ||
2690                     h->luma_weight[i][list][1] != 0) {
2691                     h->use_weight             = 1;
2692                     h->luma_weight_flag[list] = 1;
2693                 }
2694             } else {
2695                 h->luma_weight[i][list][0] = luma_def;
2696                 h->luma_weight[i][list][1] = 0;
2697             }
2698
2699             if (h->sps.chroma_format_idc) {
2700                 chroma_weight_flag = get_bits1(&h->gb);
2701                 if (chroma_weight_flag) {
2702                     int j;
2703                     for (j = 0; j < 2; j++) {
2704                         h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2705                         h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2706                         if (h->chroma_weight[i][list][j][0] != chroma_def ||
2707                             h->chroma_weight[i][list][j][1] != 0) {
2708                             h->use_weight_chroma        = 1;
2709                             h->chroma_weight_flag[list] = 1;
2710                         }
2711                     }
2712                 } else {
2713                     int j;
2714                     for (j = 0; j < 2; j++) {
2715                         h->chroma_weight[i][list][j][0] = chroma_def;
2716                         h->chroma_weight[i][list][j][1] = 0;
2717                     }
2718                 }
2719             }
2720         }
2721         if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2722             break;
2723     }
2724     h->use_weight = h->use_weight || h->use_weight_chroma;
2725     return 0;
2726 }
2727
2728 /**
2729  * Initialize implicit_weight table.
2730  * @param field  0/1 initialize the weight for interlaced MBAFF
2731  *                -1 initializes the rest
2732  */
2733 static void implicit_weight_table(H264Context *h, int field)
2734 {
2735     int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2736
2737     for (i = 0; i < 2; i++) {
2738         h->luma_weight_flag[i]   = 0;
2739         h->chroma_weight_flag[i] = 0;
2740     }
2741
2742     if (field < 0) {
2743         if (h->picture_structure == PICT_FRAME) {
2744             cur_poc = h->cur_pic_ptr->poc;
2745         } else {
2746             cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2747         }
2748         if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2749             h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2750             h->use_weight        = 0;
2751             h->use_weight_chroma = 0;
2752             return;
2753         }
2754         ref_start  = 0;
2755         ref_count0 = h->ref_count[0];
2756         ref_count1 = h->ref_count[1];
2757     } else {
2758         cur_poc    = h->cur_pic_ptr->field_poc[field];
2759         ref_start  = 16;
2760         ref_count0 = 16 + 2 * h->ref_count[0];
2761         ref_count1 = 16 + 2 * h->ref_count[1];
2762     }
2763
2764     h->use_weight               = 2;
2765     h->use_weight_chroma        = 2;
2766     h->luma_log2_weight_denom   = 5;
2767     h->chroma_log2_weight_denom = 5;
2768
2769     for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2770         int poc0 = h->ref_list[0][ref0].poc;
2771         for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2772             int w = 32;
2773             if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2774                 int poc1 = h->ref_list[1][ref1].poc;
2775                 int td   = av_clip(poc1 - poc0, -128, 127);
2776                 if (td) {
2777                     int tb = av_clip(cur_poc - poc0, -128, 127);
2778                     int tx = (16384 + (FFABS(td) >> 1)) / td;
2779                     int dist_scale_factor = (tb * tx + 32) >> 8;
2780                     if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2781                         w = 64 - dist_scale_factor;
2782                 }
2783             }
2784             if (field < 0) {
2785                 h->implicit_weight[ref0][ref1][0] =
2786                 h->implicit_weight[ref0][ref1][1] = w;
2787             } else {
2788                 h->implicit_weight[ref0][ref1][field] = w;
2789             }
2790         }
2791     }
2792 }
2793
2794 /**
2795  * instantaneous decoder refresh.
2796  */
2797 static void idr(H264Context *h)
2798 {
2799     int i;
2800     ff_h264_remove_all_refs(h);
2801     h->prev_frame_num        = 0;
2802     h->prev_frame_num_offset = 0;
2803     h->prev_poc_msb          = 1<<16;
2804     h->prev_poc_lsb          = 0;
2805     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2806         h->last_pocs[i] = INT_MIN;
2807 }
2808
2809 /* forget old pics after a seek */
2810 static void flush_change(H264Context *h)
2811 {
2812     int i, j;
2813
2814     h->outputed_poc          = h->next_outputed_poc = INT_MIN;
2815     h->prev_interlaced_frame = 1;
2816     idr(h);
2817
2818     h->prev_frame_num = -1;
2819     if (h->cur_pic_ptr) {
2820         h->cur_pic_ptr->reference = 0;
2821         for (j=i=0; h->delayed_pic[i]; i++)
2822             if (h->delayed_pic[i] != h->cur_pic_ptr)
2823                 h->delayed_pic[j++] = h->delayed_pic[i];
2824         h->delayed_pic[j] = NULL;
2825     }
2826     h->first_field = 0;
2827     memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2828     memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2829     memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2830     memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2831     ff_h264_reset_sei(h);
2832     h->recovery_frame = -1;
2833     h->frame_recovered = 0;
2834     h->list_count = 0;
2835     h->current_slice = 0;
2836     h->mmco_reset = 1;
2837 }
2838
2839 /* forget old pics after a seek */
2840 static void flush_dpb(AVCodecContext *avctx)
2841 {
2842     H264Context *h = avctx->priv_data;
2843     int i;
2844
2845     for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2846         if (h->delayed_pic[i])
2847             h->delayed_pic[i]->reference = 0;
2848         h->delayed_pic[i] = NULL;
2849     }
2850
2851     flush_change(h);
2852
2853     if (h->DPB)
2854         for (i = 0; i < MAX_PICTURE_COUNT; i++)
2855             unref_picture(h, &h->DPB[i]);
2856     h->cur_pic_ptr = NULL;
2857     unref_picture(h, &h->cur_pic);
2858
2859     h->mb_x = h->mb_y = 0;
2860
2861     h->parse_context.state             = -1;
2862     h->parse_context.frame_start_found = 0;
2863     h->parse_context.overread          = 0;
2864     h->parse_context.overread_index    = 0;
2865     h->parse_context.index             = 0;
2866     h->parse_context.last_index        = 0;
2867
2868     free_tables(h, 1);
2869     h->context_initialized = 0;
2870 }
2871
2872 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2873 {
2874     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2875     int field_poc[2];
2876
2877     h->frame_num_offset = h->prev_frame_num_offset;
2878     if (h->frame_num < h->prev_frame_num)
2879         h->frame_num_offset += max_frame_num;
2880
2881     if (h->sps.poc_type == 0) {
2882         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2883
2884         if (h->poc_lsb < h->prev_poc_lsb &&
2885             h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2886             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2887         else if (h->poc_lsb > h->prev_poc_lsb &&
2888                  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2889             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2890         else
2891             h->poc_msb = h->prev_poc_msb;
2892         field_poc[0] =
2893         field_poc[1] = h->poc_msb + h->poc_lsb;
2894         if (h->picture_structure == PICT_FRAME)
2895             field_poc[1] += h->delta_poc_bottom;
2896     } else if (h->sps.poc_type == 1) {
2897         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2898         int i;
2899
2900         if (h->sps.poc_cycle_length != 0)
2901             abs_frame_num = h->frame_num_offset + h->frame_num;
2902         else
2903             abs_frame_num = 0;
2904
2905         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2906             abs_frame_num--;
2907
2908         expected_delta_per_poc_cycle = 0;
2909         for (i = 0; i < h->sps.poc_cycle_length; i++)
2910             // FIXME integrate during sps parse
2911             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2912
2913         if (abs_frame_num > 0) {
2914             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2915             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2916
2917             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2918             for (i = 0; i <= frame_num_in_poc_cycle; i++)
2919                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2920         } else
2921             expectedpoc = 0;
2922
2923         if (h->nal_ref_idc == 0)
2924             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2925
2926         field_poc[0] = expectedpoc + h->delta_poc[0];
2927         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2928
2929         if (h->picture_structure == PICT_FRAME)
2930             field_poc[1] += h->delta_poc[1];
2931     } else {
2932         int poc = 2 * (h->frame_num_offset + h->frame_num);
2933
2934         if (!h->nal_ref_idc)
2935             poc--;
2936
2937         field_poc[0] = poc;
2938         field_poc[1] = poc;
2939     }
2940
2941     if (h->picture_structure != PICT_BOTTOM_FIELD)
2942         pic_field_poc[0] = field_poc[0];
2943     if (h->picture_structure != PICT_TOP_FIELD)
2944         pic_field_poc[1] = field_poc[1];
2945     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2946
2947     return 0;
2948 }
2949
2950 /**
2951  * initialize scan tables
2952  */
2953 static void init_scan_tables(H264Context *h)
2954 {
2955     int i;
2956     for (i = 0; i < 16; i++) {
2957 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2958         h->zigzag_scan[i] = T(zigzag_scan[i]);
2959         h->field_scan[i]  = T(field_scan[i]);
2960 #undef T
2961     }
2962     for (i = 0; i < 64; i++) {
2963 #define T(x) (x >> 3) | ((x & 7) << 3)
2964         h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
2965         h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2966         h->field_scan8x8[i]        = T(field_scan8x8[i]);
2967         h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
2968 #undef T
2969     }
2970     if (h->sps.transform_bypass) { // FIXME same ugly
2971         memcpy(h->zigzag_scan_q0          , zigzag_scan             , sizeof(h->zigzag_scan_q0         ));
2972         memcpy(h->zigzag_scan8x8_q0       , ff_zigzag_direct        , sizeof(h->zigzag_scan8x8_q0      ));
2973         memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc    , sizeof(h->zigzag_scan8x8_cavlc_q0));
2974         memcpy(h->field_scan_q0           , field_scan              , sizeof(h->field_scan_q0          ));
2975         memcpy(h->field_scan8x8_q0        , field_scan8x8           , sizeof(h->field_scan8x8_q0       ));
2976         memcpy(h->field_scan8x8_cavlc_q0  , field_scan8x8_cavlc     , sizeof(h->field_scan8x8_cavlc_q0 ));
2977     } else {
2978         memcpy(h->zigzag_scan_q0          , h->zigzag_scan          , sizeof(h->zigzag_scan_q0         ));
2979         memcpy(h->zigzag_scan8x8_q0       , h->zigzag_scan8x8       , sizeof(h->zigzag_scan8x8_q0      ));
2980         memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2981         memcpy(h->field_scan_q0           , h->field_scan           , sizeof(h->field_scan_q0          ));
2982         memcpy(h->field_scan8x8_q0        , h->field_scan8x8        , sizeof(h->field_scan8x8_q0       ));
2983         memcpy(h->field_scan8x8_cavlc_q0  , h->field_scan8x8_cavlc  , sizeof(h->field_scan8x8_cavlc_q0 ));
2984     }
2985 }
2986
2987 static int field_end(H264Context *h, int in_setup)
2988 {
2989     AVCodecContext *const avctx = h->avctx;
2990     int err = 0;
2991     h->mb_y = 0;
2992
2993     if (CONFIG_H264_VDPAU_DECODER &&
2994         h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2995         ff_vdpau_h264_set_reference_frames(h);
2996
2997     if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2998         if (!h->droppable) {
2999             err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3000             h->prev_poc_msb = h->poc_msb;
3001             h->prev_poc_lsb = h->poc_lsb;
3002         }
3003         h->prev_frame_num_offset = h->frame_num_offset;
3004         h->prev_frame_num        = h->frame_num;
3005         h->outputed_poc          = h->next_outputed_poc;
3006     }
3007
3008     if (avctx->hwaccel) {
3009         if (avctx->hwaccel->end_frame(avctx) < 0)
3010             av_log(avctx, AV_LOG_ERROR,
3011                    "hardware accelerator failed to decode picture\n");
3012     }
3013
3014     if (CONFIG_H264_VDPAU_DECODER &&
3015         h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3016         ff_vdpau_h264_picture_complete(h);
3017
3018     /*
3019      * FIXME: Error handling code does not seem to support interlaced
3020      * when slices span multiple rows
3021      * The ff_er_add_slice calls don't work right for bottom
3022      * fields; they cause massive erroneous error concealing
3023      * Error marking covers both fields (top and bottom).
3024      * This causes a mismatched s->error_count
3025      * and a bad error table. Further, the error count goes to
3026      * INT_MAX when called for bottom field, because mb_y is
3027      * past end by one (callers fault) and resync_mb_y != 0
3028      * causes problems for the first MB line, too.
3029      */
3030     if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
3031         h->er.cur_pic  = h->cur_pic_ptr;
3032         ff_er_frame_end(&h->er);
3033     }
3034     if (!in_setup && !h->droppable)
3035         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3036                                   h->picture_structure == PICT_BOTTOM_FIELD);
3037     emms_c();
3038
3039     h->current_slice = 0;
3040
3041     return err;
3042 }
3043
3044 /**
3045  * Replicate H264 "master" context to thread contexts.
3046  */
3047 static int clone_slice(H264Context *dst, H264Context *src)
3048 {
3049     memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3050     dst->cur_pic_ptr = src->cur_pic_ptr;
3051     dst->cur_pic     = src->cur_pic;
3052     dst->linesize    = src->linesize;
3053     dst->uvlinesize  = src->uvlinesize;
3054     dst->first_field = src->first_field;
3055
3056     dst->prev_poc_msb          = src->prev_poc_msb;
3057     dst->prev_poc_lsb          = src->prev_poc_lsb;
3058     dst->prev_frame_num_offset = src->prev_frame_num_offset;
3059     dst->prev_frame_num        = src->prev_frame_num;
3060     dst->short_ref_count       = src->short_ref_count;
3061
3062     memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
3063     memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
3064     memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3065
3066     memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
3067     memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
3068
3069     return 0;
3070 }
3071
3072 /**
3073  * Compute profile from profile_idc and constraint_set?_flags.
3074  *
3075  * @param sps SPS
3076  *
3077  * @return profile as defined by FF_PROFILE_H264_*
3078  */
3079 int ff_h264_get_profile(SPS *sps)
3080 {
3081     int profile = sps->profile_idc;
3082
3083     switch (sps->profile_idc) {
3084     case FF_PROFILE_H264_BASELINE:
3085         // constraint_set1_flag set to 1
3086         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3087         break;
3088     case FF_PROFILE_H264_HIGH_10:
3089     case FF_PROFILE_H264_HIGH_422:
3090     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3091         // constraint_set3_flag set to 1
3092         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3093         break;
3094     }
3095
3096     return profile;
3097 }
3098
3099 static int h264_set_parameter_from_sps(H264Context *h)
3100 {
3101     if (h->flags & CODEC_FLAG_LOW_DELAY ||
3102         (h->sps.bitstream_restriction_flag &&
3103          !h->sps.num_reorder_frames)) {
3104         if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3105             av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3106                    "Reenabling low delay requires a codec flush.\n");
3107         else
3108             h->low_delay = 1;
3109     }
3110
3111     if (h->avctx->has_b_frames < 2)
3112         h->avctx->has_b_frames = !h->low_delay;
3113
3114     if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3115         avpriv_request_sample(h->avctx,
3116                               "Different chroma and luma bit depth");
3117         return AVERROR_PATCHWELCOME;
3118     }
3119
3120     if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3121         h->cur_chroma_format_idc      != h->sps.chroma_format_idc) {
3122         if (h->avctx->codec &&
3123             h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
3124             (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
3125             av_log(h->avctx, AV_LOG_ERROR,
3126                    "VDPAU decoding does not support video colorspace.\n");
3127             return AVERROR_INVALIDDATA;
3128         }
3129         if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
3130             h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
3131             h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3132             h->cur_chroma_format_idc      = h->sps.chroma_format_idc;
3133             h->pixel_shift                = h->sps.bit_depth_luma > 8;
3134
3135             ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3136                             h->sps.chroma_format_idc);
3137             ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3138             ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3139             ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3140                               h->sps.chroma_format_idc);
3141
3142             if (CONFIG_ERROR_RESILIENCE)
3143                 ff_dsputil_init(&h->dsp, h->avctx);
3144             ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3145         } else {
3146             av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3147                    h->sps.bit_depth_luma);
3148             return AVERROR_INVALIDDATA;
3149         }
3150     }
3151     return 0;
3152 }
3153
3154 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3155 {
3156     switch (h->sps.bit_depth_luma) {
3157     case 9:
3158         if (CHROMA444(h)) {
3159             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3160                 return AV_PIX_FMT_GBRP9;
3161             } else
3162                 return AV_PIX_FMT_YUV444P9;
3163         } else if (CHROMA422(h))
3164             return AV_PIX_FMT_YUV422P9;
3165         else
3166             return AV_PIX_FMT_YUV420P9;
3167         break;
3168     case 10:
3169         if (CHROMA444(h)) {
3170             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3171                 return AV_PIX_FMT_GBRP10;
3172             } else
3173                 return AV_PIX_FMT_YUV444P10;
3174         } else if (CHROMA422(h))
3175             return AV_PIX_FMT_YUV422P10;
3176         else
3177             return AV_PIX_FMT_YUV420P10;
3178         break;
3179     case 12:
3180         if (CHROMA444(h)) {
3181             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3182                 return AV_PIX_FMT_GBRP12;
3183             } else
3184                 return AV_PIX_FMT_YUV444P12;
3185         } else if (CHROMA422(h))
3186             return AV_PIX_FMT_YUV422P12;
3187         else
3188             return AV_PIX_FMT_YUV420P12;
3189         break;
3190     case 14:
3191         if (CHROMA444(h)) {
3192             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3193                 return AV_PIX_FMT_GBRP14;
3194             } else
3195                 return AV_PIX_FMT_YUV444P14;
3196         } else if (CHROMA422(h))
3197             return AV_PIX_FMT_YUV422P14;
3198         else
3199             return AV_PIX_FMT_YUV420P14;
3200         break;
3201     case 8:
3202         if (CHROMA444(h)) {
3203             if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3204                 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3205                 return AV_PIX_FMT_GBR24P;
3206             } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3207                 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3208             }
3209             return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3210                                                                 : AV_PIX_FMT_YUV444P;
3211         } else if (CHROMA422(h)) {
3212             return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3213                                                              : AV_PIX_FMT_YUV422P;
3214         } else {
3215             int i;
3216             const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3217                                         h->avctx->codec->pix_fmts :
3218                                         h->avctx->color_range == AVCOL_RANGE_JPEG ?
3219                                         h264_hwaccel_pixfmt_list_jpeg_420 :
3220                                         h264_hwaccel_pixfmt_list_420;
3221
3222             for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3223                 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3224                     return fmt[i];
3225             return ff_thread_get_format(h->avctx, fmt);
3226         }
3227         break;
3228     default:
3229         av_log(h->avctx, AV_LOG_ERROR,
3230                "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3231         return AVERROR_INVALIDDATA;
3232     }
3233 }
3234
3235 /* export coded and cropped frame dimensions to AVCodecContext */
3236 static int init_dimensions(H264Context *h)
3237 {
3238     int width  = h->width  - (h->sps.crop_right + h->sps.crop_left);
3239     int height = h->height - (h->sps.crop_top   + h->sps.crop_bottom);
3240     av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
3241     av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
3242
3243     /* handle container cropping */
3244     if (!h->sps.crop &&
3245         FFALIGN(h->avctx->width,  16) == h->width &&
3246         FFALIGN(h->avctx->height, 16) == h->height) {
3247         width  = h->avctx->width;
3248         height = h->avctx->height;
3249     }
3250
3251     if (width <= 0 || height <= 0) {
3252         av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3253                width, height);
3254         if (h->avctx->err_recognition & AV_EF_EXPLODE)
3255             return AVERROR_INVALIDDATA;
3256
3257         av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3258         h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3259         h->sps.crop        = 0;
3260
3261         width  = h->width;
3262         height = h->height;
3263     }
3264
3265     h->avctx->coded_width  = h->width;
3266     h->avctx->coded_height = h->height;
3267     h->avctx->width        = width;
3268     h->avctx->height       = height;
3269
3270     return 0;
3271 }
3272
3273 static int h264_slice_header_init(H264Context *h, int reinit)
3274 {
3275     int nb_slices = (HAVE_THREADS &&
3276                      h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3277                     h->avctx->thread_count : 1;
3278     int i, ret;
3279
3280     h->avctx->sample_aspect_ratio = h->sps.sar;
3281     av_assert0(h->avctx->sample_aspect_ratio.den);
3282     av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3283                                      &h->chroma_x_shift, &h->chroma_y_shift);
3284
3285     if (h->sps.timing_info_present_flag) {
3286         int64_t den = h->sps.time_scale;
3287         if (h->x264_build < 44U)
3288             den *= 2;
3289         av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3290                   h->sps.num_units_in_tick, den, 1 << 30);
3291     }
3292
3293     h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3294
3295     if (reinit)
3296         free_tables(h, 0);
3297     h->first_field           = 0;
3298     h->prev_interlaced_frame = 1;
3299
3300     init_scan_tables(h);
3301     ret = ff_h264_alloc_tables(h);
3302     if (ret < 0) {
3303         av_log(h->avctx, AV_LOG_ERROR,
3304                "Could not allocate memory for h264\n");
3305         return ret;
3306     }
3307
3308     if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3309         int max_slices;
3310         if (h->mb_height)
3311             max_slices = FFMIN(MAX_THREADS, h->mb_height);
3312         else
3313             max_slices = MAX_THREADS;
3314         av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3315                " reducing to %d\n", nb_slices, max_slices);
3316         nb_slices = max_slices;
3317     }
3318     h->slice_context_count = nb_slices;
3319
3320     if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3321         ret = context_init(h);
3322         if (ret < 0) {
3323             av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3324             return ret;
3325         }
3326     } else {
3327         for (i = 1; i < h->slice_context_count; i++) {
3328             H264Context *c;
3329             c                    = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3330             if (!c)
3331                 return AVERROR(ENOMEM);
3332             c->avctx             = h->avctx;
3333             if (CONFIG_ERROR_RESILIENCE) {
3334                 c->dsp               = h->dsp;
3335             }
3336             c->vdsp              = h->vdsp;
3337             c->h264dsp           = h->h264dsp;
3338             c->h264qpel          = h->h264qpel;
3339             c->h264chroma        = h->h264chroma;
3340             c->sps               = h->sps;
3341             c->pps               = h->pps;
3342             c->pixel_shift       = h->pixel_shift;
3343             c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3344             c->width             = h->width;
3345             c->height            = h->height;
3346             c->linesize          = h->linesize;
3347             c->uvlinesize        = h->uvlinesize;
3348             c->chroma_x_shift    = h->chroma_x_shift;
3349             c->chroma_y_shift    = h->chroma_y_shift;
3350             c->qscale            = h->qscale;
3351             c->droppable         = h->droppable;
3352             c->data_partitioning = h->data_partitioning;
3353             c->low_delay         = h->low_delay;
3354             c->mb_width          = h->mb_width;
3355             c->mb_height         = h->mb_height;
3356             c->mb_stride         = h->mb_stride;
3357             c->mb_num            = h->mb_num;
3358             c->flags             = h->flags;
3359             c->workaround_bugs   = h->workaround_bugs;
3360             c->pict_type         = h->pict_type;
3361
3362             init_scan_tables(c);
3363             clone_tables(c, h, i);
3364             c->context_initialized = 1;
3365         }
3366
3367         for (i = 0; i < h->slice_context_count; i++)
3368             if ((ret = context_init(h->thread_context[i])) < 0) {
3369                 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3370                 return ret;
3371             }
3372     }
3373
3374     h->context_initialized = 1;
3375
3376     return 0;
3377 }
3378
3379 int ff_set_ref_count(H264Context *h)
3380 {
3381     int num_ref_idx_active_override_flag;
3382
3383     // set defaults, might be overridden a few lines later
3384     h->ref_count[0] = h->pps.ref_count[0];
3385     h->ref_count[1] = h->pps.ref_count[1];
3386
3387     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3388         unsigned max[2];
3389         max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3390
3391         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3392             h->direct_spatial_mv_pred = get_bits1(&h->gb);
3393         num_ref_idx_active_override_flag = get_bits1(&h->gb);
3394
3395         if (num_ref_idx_active_override_flag) {
3396             h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3397             if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3398                 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3399             } else
3400                 // full range is spec-ok in this case, even for frames
3401                 h->ref_count[1] = 1;
3402         }
3403
3404         if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3405             av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
3406             h->ref_count[0] = h->ref_count[1] = 0;
3407             return AVERROR_INVALIDDATA;
3408         }
3409
3410         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3411             h->list_count = 2;
3412         else
3413             h->list_count = 1;
3414     } else {
3415         h->list_count   = 0;
3416         h->ref_count[0] = h->ref_count[1] = 0;
3417     }
3418
3419     return 0;
3420 }
3421
3422 /**
3423  * Decode a slice header.
3424  * This will also call ff_MPV_common_init() and frame_start() as needed.
3425  *
3426  * @param h h264context
3427  * @param h0 h264 master context (differs from 'h' when doing sliced based
3428  *           parallel decoding)
3429  *
3430  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3431  */
3432 static int decode_slice_header(H264Context *h, H264Context *h0)
3433 {
3434     unsigned int first_mb_in_slice;
3435     unsigned int pps_id;
3436     int ret;
3437     unsigned int slice_type, tmp, i, j;
3438     int last_pic_structure, last_pic_droppable;
3439     int must_reinit;
3440     int needs_reinit = 0;
3441     int field_pic_flag, bottom_field_flag;
3442
3443     h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3444     h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3445
3446     first_mb_in_slice = get_ue_golomb_long(&h->gb);
3447
3448     if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3449         if (h0->current_slice && FIELD_PICTURE(h)) {
3450             field_end(h, 1);
3451         }
3452
3453         h0->current_slice = 0;
3454         if (!h0->first_field) {
3455             if (h->cur_pic_ptr && !h->droppable) {
3456                 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3457                                           h->picture_structure == PICT_BOTTOM_FIELD);
3458             }
3459             h->cur_pic_ptr = NULL;
3460         }
3461     }
3462
3463     slice_type = get_ue_golomb_31(&h->gb);
3464     if (slice_type > 9) {
3465         av_log(h->avctx, AV_LOG_ERROR,
3466                "slice type too large (%d) at %d %d\n",
3467                slice_type, h->mb_x, h->mb_y);
3468         return AVERROR_INVALIDDATA;
3469     }
3470     if (slice_type > 4) {
3471         slice_type -= 5;
3472         h->slice_type_fixed = 1;
3473     } else
3474         h->slice_type_fixed = 0;
3475
3476     slice_type = golomb_to_pict_type[slice_type];
3477     h->slice_type     = slice_type;
3478     h->slice_type_nos = slice_type & 3;
3479
3480     // to make a few old functions happy, it's wrong though
3481     h->pict_type = h->slice_type;
3482
3483     pps_id = get_ue_golomb(&h->gb);
3484     if (pps_id >= MAX_PPS_COUNT) {
3485         av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3486         return AVERROR_INVALIDDATA;
3487     }
3488     if (!h0->pps_buffers[pps_id]) {
3489         av_log(h->avctx, AV_LOG_ERROR,
3490                "non-existing PPS %u referenced\n",
3491                pps_id);
3492         return AVERROR_INVALIDDATA;
3493     }
3494     h->pps = *h0->pps_buffers[pps_id];
3495
3496     if (!h0->sps_buffers[h->pps.sps_id]) {
3497         av_log(h->avctx, AV_LOG_ERROR,
3498                "non-existing SPS %u referenced\n",
3499                h->pps.sps_id);
3500         return AVERROR_INVALIDDATA;
3501     }
3502
3503     if (h->pps.sps_id != h->current_sps_id ||
3504         h0->sps_buffers[h->pps.sps_id]->new) {
3505         h0->sps_buffers[h->pps.sps_id]->new = 0;
3506
3507         h->current_sps_id = h->pps.sps_id;
3508         h->sps            = *h0->sps_buffers[h->pps.sps_id];
3509
3510         if (h->mb_width  != h->sps.mb_width ||
3511             h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3512             h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3513             h->cur_chroma_format_idc != h->sps.chroma_format_idc
3514         )
3515             needs_reinit = 1;
3516
3517         if (h->bit_depth_luma    != h->sps.bit_depth_luma ||
3518             h->chroma_format_idc != h->sps.chroma_format_idc) {
3519             h->bit_depth_luma    = h->sps.bit_depth_luma;
3520             h->chroma_format_idc = h->sps.chroma_format_idc;
3521             needs_reinit         = 1;
3522         }
3523         if ((ret = h264_set_parameter_from_sps(h)) < 0)
3524             return ret;
3525     }
3526
3527     h->avctx->profile = ff_h264_get_profile(&h->sps);
3528     h->avctx->level   = h->sps.level_idc;
3529     h->avctx->refs    = h->sps.ref_frame_count;
3530
3531     must_reinit = (h->context_initialized &&
3532                     (   16*h->sps.mb_width != h->avctx->coded_width
3533                      || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3534                      || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3535                      || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3536                      || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
3537                      || h->mb_width  != h->sps.mb_width
3538                      || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3539                     ));
3540     if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3541         must_reinit = 1;
3542
3543     h->mb_width  = h->sps.mb_width;
3544     h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3545     h->mb_num    = h->mb_width * h->mb_height;
3546     h->mb_stride = h->mb_width + 1;
3547
3548     h->b_stride = h->mb_width * 4;
3549
3550     h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3551
3552     h->width  = 16 * h->mb_width;
3553     h->height = 16 * h->mb_height;
3554
3555     ret = init_dimensions(h);
3556     if (ret < 0)
3557         return ret;
3558
3559     if (h->sps.video_signal_type_present_flag) {
3560         h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3561                                                     : AVCOL_RANGE_MPEG;
3562         if (h->sps.colour_description_present_flag) {
3563             if (h->avctx->colorspace != h->sps.colorspace)
3564                 needs_reinit = 1;
3565             h->avctx->color_primaries = h->sps.color_primaries;
3566             h->avctx->color_trc       = h->sps.color_trc;
3567             h->avctx->colorspace      = h->sps.colorspace;
3568         }
3569     }
3570
3571     if (h->context_initialized &&
3572         (h->width  != h->avctx->coded_width   ||
3573          h->height != h->avctx->coded_height  ||
3574          must_reinit ||
3575          needs_reinit)) {
3576         if (h != h0) {
3577             av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3578                    "slice %d\n", h0->current_slice + 1);
3579             return AVERROR_INVALIDDATA;
3580         }
3581
3582         flush_change(h);
3583
3584         if ((ret = get_pixel_format(h, 1)) < 0)
3585             return ret;
3586         h->avctx->pix_fmt = ret;
3587
3588         av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3589                "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3590
3591         if ((ret = h264_slice_header_init(h, 1)) < 0) {
3592             av_log(h->avctx, AV_LOG_ERROR,
3593                    "h264_slice_header_init() failed\n");
3594             return ret;
3595         }
3596     }
3597     if (!h->context_initialized) {
3598         if (h != h0) {
3599             av_log(h->avctx, AV_LOG_ERROR,
3600                    "Cannot (re-)initialize context during parallel decoding.\n");
3601             return AVERROR_PATCHWELCOME;
3602         }
3603
3604         if ((ret = get_pixel_format(h, 1)) < 0)
3605             return ret;
3606         h->avctx->pix_fmt = ret;
3607
3608         if ((ret = h264_slice_header_init(h, 0)) < 0) {
3609             av_log(h->avctx, AV_LOG_ERROR,
3610                    "h264_slice_header_init() failed\n");
3611             return ret;
3612         }
3613     }
3614
3615     if (h == h0 && h->dequant_coeff_pps != pps_id) {
3616         h->dequant_coeff_pps = pps_id;
3617         init_dequant_tables(h);
3618     }
3619
3620     h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3621
3622     h->mb_mbaff        = 0;
3623     h->mb_aff_frame    = 0;
3624     last_pic_structure = h0->picture_structure;
3625     last_pic_droppable = h0->droppable;
3626     h->droppable       = h->nal_ref_idc == 0;
3627     if (h->sps.frame_mbs_only_flag) {
3628         h->picture_structure = PICT_FRAME;
3629     } else {
3630         if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3631             av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3632             return -1;
3633         }
3634         field_pic_flag = get_bits1(&h->gb);
3635         if (field_pic_flag) {
3636             bottom_field_flag = get_bits1(&h->gb);
3637             h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3638         } else {
3639             h->picture_structure = PICT_FRAME;
3640             h->mb_aff_frame      = h->sps.mb_aff;
3641         }
3642     }
3643     h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3644
3645     if (h0->current_slice != 0) {
3646         if (last_pic_structure != h->picture_structure ||
3647             last_pic_droppable != h->droppable) {
3648             av_log(h->avctx, AV_LOG_ERROR,
3649                    "Changing field mode (%d -> %d) between slices is not allowed\n",
3650                    last_pic_structure, h->picture_structure);
3651             h->picture_structure = last_pic_structure;
3652             h->droppable         = last_pic_droppable;
3653             return AVERROR_INVALIDDATA;
3654         } else if (!h0->cur_pic_ptr) {
3655             av_log(h->avctx, AV_LOG_ERROR,
3656                    "unset cur_pic_ptr on %d. slice\n",
3657                    h0->current_slice + 1);
3658             return AVERROR_INVALIDDATA;
3659         }
3660     } else {
3661         /* Shorten frame num gaps so we don't have to allocate reference
3662          * frames just to throw them away */
3663         if (h->frame_num != h->prev_frame_num) {
3664             int unwrap_prev_frame_num = h->prev_frame_num;
3665             int max_frame_num         = 1 << h->sps.log2_max_frame_num;
3666
3667             if (unwrap_prev_frame_num > h->frame_num)
3668                 unwrap_prev_frame_num -= max_frame_num;
3669
3670             if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3671                 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3672                 if (unwrap_prev_frame_num < 0)
3673                     unwrap_prev_frame_num += max_frame_num;
3674
3675                 h->prev_frame_num = unwrap_prev_frame_num;
3676             }
3677         }
3678
3679         /* See if we have a decoded first field looking for a pair...
3680          * Here, we're using that to see if we should mark previously
3681          * decode frames as "finished".
3682          * We have to do that before the "dummy" in-between frame allocation,
3683          * since that can modify h->cur_pic_ptr. */
3684         if (h0->first_field) {
3685             assert(h0->cur_pic_ptr);
3686             assert(h0->cur_pic_ptr->f.buf[0]);
3687             assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3688
3689             /* Mark old field/frame as completed */
3690             if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
3691                 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3692                                           last_pic_structure == PICT_BOTTOM_FIELD);
3693             }
3694
3695             /* figure out if we have a complementary field pair */
3696             if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3697                 /* Previous field is unmatched. Don't display it, but let it
3698                  * remain for reference if marked as such. */
3699                 if (last_pic_structure != PICT_FRAME) {
3700                     ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3701                                               last_pic_structure == PICT_TOP_FIELD);
3702                 }
3703             } else {
3704                 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3705                     /* This and previous field were reference, but had
3706                      * different frame_nums. Consider this field first in
3707                      * pair. Throw away previous field except for reference
3708                      * purposes. */
3709                     if (last_pic_structure != PICT_FRAME) {
3710                         ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3711                                                   last_pic_structure == PICT_TOP_FIELD);
3712                     }
3713                 } else {
3714                     /* Second field in complementary pair */
3715                     if (!((last_pic_structure   == PICT_TOP_FIELD &&
3716                            h->picture_structure == PICT_BOTTOM_FIELD) ||
3717                           (last_pic_structure   == PICT_BOTTOM_FIELD &&
3718                            h->picture_structure == PICT_TOP_FIELD))) {
3719                         av_log(h->avctx, AV_LOG_ERROR,
3720                                "Invalid field mode combination %d/%d\n",
3721                                last_pic_structure, h->picture_structure);
3722                         h->picture_structure = last_pic_structure;
3723                         h->droppable         = last_pic_droppable;
3724                         return AVERROR_INVALIDDATA;
3725                     } else if (last_pic_droppable != h->droppable) {
3726                         avpriv_request_sample(h->avctx,
3727                                               "Found reference and non-reference fields in the same frame, which");
3728                         h->picture_structure = last_pic_structure;
3729                         h->droppable         = last_pic_droppable;
3730                         return AVERROR_PATCHWELCOME;
3731                     }
3732                 }
3733             }
3734         }
3735
3736         while (h->frame_num != h->prev_frame_num && !h0->first_field &&
3737                h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3738             Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3739             av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3740                    h->frame_num, h->prev_frame_num);
3741             if (!h->sps.gaps_in_frame_num_allowed_flag)
3742                 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3743                     h->last_pocs[i] = INT_MIN;
3744             ret = h264_frame_start(h);
3745             if (ret < 0)
3746                 return ret;
3747             h->prev_frame_num++;
3748             h->prev_frame_num        %= 1 << h->sps.log2_max_frame_num;
3749             h->cur_pic_ptr->frame_num = h->prev_frame_num;
3750             ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3751             ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3752             ret = ff_generate_sliding_window_mmcos(h, 1);
3753             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3754                 return ret;
3755             ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3756             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3757                 return ret;
3758             /* Error concealment: If a ref is missing, copy the previous ref
3759              * in its place.
3760              * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3761              * many assumptions about there being no actual duplicates.
3762              * FIXME: This does not copy padding for out-of-frame motion
3763              * vectors.  Given we are concealing a lost frame, this probably
3764              * is not noticeable by comparison, but it should be fixed. */
3765             if (h->short_ref_count) {
3766                 if (prev) {
3767                     av_image_copy(h->short_ref[0]->f.data,
3768                                   h->short_ref[0]->f.linesize,
3769                                   (const uint8_t **)prev->f.data,
3770                                   prev->f.linesize,
3771                                   h->avctx->pix_fmt,
3772                                   h->mb_width  * 16,
3773                                   h->mb_height * 16);
3774                     h->short_ref[0]->poc = prev->poc + 2;
3775                 }
3776                 h->short_ref[0]->frame_num = h->prev_frame_num;
3777             }
3778         }
3779
3780         /* See if we have a decoded first field looking for a pair...
3781          * We're using that to see whether to continue decoding in that
3782          * frame, or to allocate a new one. */
3783         if (h0->first_field) {
3784             assert(h0->cur_pic_ptr);
3785             assert(h0->cur_pic_ptr->f.buf[0]);
3786             assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3787
3788             /* figure out if we have a complementary field pair */
3789             if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3790                 /* Previous field is unmatched. Don't display it, but let it
3791                  * remain for reference if marked as such. */
3792                 h0->cur_pic_ptr = NULL;
3793                 h0->first_field = FIELD_PICTURE(h);
3794             } else {
3795                 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3796                     ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3797                                               h0->picture_structure==PICT_BOTTOM_FIELD);
3798                     /* This and the previous field had different frame_nums.
3799                      * Consider this field first in pair. Throw away previous
3800                      * one except for reference purposes. */
3801                     h0->first_field = 1;
3802                     h0->cur_pic_ptr = NULL;
3803                 } else {
3804                     /* Second field in complementary pair */
3805                     h0->first_field = 0;
3806                 }
3807             }
3808         } else {
3809             /* Frame or first field in a potentially complementary pair */
3810             h0->first_field = FIELD_PICTURE(h);
3811         }
3812
3813         if (!FIELD_PICTURE(h) || h0->first_field) {
3814             if (h264_frame_start(h) < 0) {
3815                 h0->first_field = 0;
3816                 return AVERROR_INVALIDDATA;
3817             }
3818         } else {
3819             release_unused_pictures(h, 0);
3820         }
3821         /* Some macroblocks can be accessed before they're available in case
3822         * of lost slices, MBAFF or threading. */
3823         if (FIELD_PICTURE(h)) {
3824             for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3825                 memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3826         } else {
3827             memset(h->slice_table, -1,
3828                 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3829         }
3830         h0->last_slice_type = -1;
3831     }
3832     if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3833         return ret;
3834
3835     /* can't be in alloc_tables because linesize isn't known there.
3836      * FIXME: redo bipred weight to not require extra buffer? */
3837     for (i = 0; i < h->slice_context_count; i++)
3838         if (h->thread_context[i]) {
3839             ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3840             if (ret < 0)
3841                 return ret;
3842         }
3843
3844     h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3845
3846     av_assert1(h->mb_num == h->mb_width * h->mb_height);
3847     if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3848         first_mb_in_slice >= h->mb_num) {
3849         av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3850         return AVERROR_INVALIDDATA;
3851     }
3852     h->resync_mb_x = h->mb_x =  first_mb_in_slice % h->mb_width;
3853     h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3854                                FIELD_OR_MBAFF_PICTURE(h);
3855     if (h->picture_structure == PICT_BOTTOM_FIELD)
3856         h->resync_mb_y = h->mb_y = h->mb_y + 1;
3857     av_assert1(h->mb_y < h->mb_height);
3858
3859     if (h->picture_structure == PICT_FRAME) {
3860         h->curr_pic_num = h->frame_num;
3861         h->max_pic_num  = 1 << h->sps.log2_max_frame_num;
3862     } else {
3863         h->curr_pic_num = 2 * h->frame_num + 1;
3864         h->max_pic_num  = 1 << (h->sps.log2_max_frame_num + 1);
3865     }
3866
3867     if (h->nal_unit_type == NAL_IDR_SLICE)
3868         get_ue_golomb(&h->gb); /* idr_pic_id */
3869
3870     if (h->sps.poc_type == 0) {
3871         h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3872
3873         if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3874             h->delta_poc_bottom = get_se_golomb(&h->gb);
3875     }
3876
3877     if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3878         h->delta_poc[0] = get_se_golomb(&h->gb);
3879
3880         if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3881             h->delta_poc[1] = get_se_golomb(&h->gb);
3882     }
3883
3884     ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3885
3886     if (h->pps.redundant_pic_cnt_present)
3887         h->redundant_pic_count = get_ue_golomb(&h->gb);
3888
3889     ret = ff_set_ref_count(h);
3890     if (ret < 0)
3891         return ret;
3892
3893     if (slice_type != AV_PICTURE_TYPE_I &&
3894         (h0->current_slice == 0 ||
3895          slice_type != h0->last_slice_type ||
3896          memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3897
3898         ff_h264_fill_default_ref_list(h);
3899     }
3900
3901     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3902        ret = ff_h264_decode_ref_pic_list_reordering(h);
3903        if (ret < 0) {
3904            h->ref_count[1] = h->ref_count[0] = 0;
3905            return ret;
3906        }
3907     }
3908
3909     if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3910         (h->pps.weighted_bipred_idc == 1 &&
3911          h->slice_type_nos == AV_PICTURE_TYPE_B))
3912         ff_pred_weight_table(h);
3913     else if (h->pps.weighted_bipred_idc == 2 &&
3914              h->slice_type_nos == AV_PICTURE_TYPE_B) {
3915         implicit_weight_table(h, -1);
3916     } else {
3917         h->use_weight = 0;
3918         for (i = 0; i < 2; i++) {
3919             h->luma_weight_flag[i]   = 0;
3920             h->chroma_weight_flag[i] = 0;
3921         }
3922     }
3923
3924     // If frame-mt is enabled, only update mmco tables for the first slice
3925     // in a field. Subsequent slices can temporarily clobber h->mmco_index
3926     // or h->mmco, which will cause ref list mix-ups and decoding errors
3927     // further down the line. This may break decoding if the first slice is
3928     // corrupt, thus we only do this if frame-mt is enabled.
3929     if (h->nal_ref_idc) {
3930         ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3931                                              !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3932                                              h0->current_slice == 0);
3933         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3934             return AVERROR_INVALIDDATA;
3935     }
3936
3937     if (FRAME_MBAFF(h)) {
3938         ff_h264_fill_mbaff_ref_list(h);
3939
3940         if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3941             implicit_weight_table(h, 0);
3942             implicit_weight_table(h, 1);
3943         }
3944     }
3945
3946     if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3947         ff_h264_direct_dist_scale_factor(h);
3948     ff_h264_direct_ref_list_init(h);
3949
3950     if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3951         tmp = get_ue_golomb_31(&h->gb);
3952         if (tmp > 2) {
3953             av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3954             return AVERROR_INVALIDDATA;
3955         }
3956         h->cabac_init_idc = tmp;
3957     }
3958
3959     h->last_qscale_diff = 0;
3960     tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3961     if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3962         av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3963         return AVERROR_INVALIDDATA;
3964     }
3965     h->qscale       = tmp;
3966     h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3967     h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3968     // FIXME qscale / qp ... stuff
3969     if (h->slice_type == AV_PICTURE_TYPE_SP)
3970         get_bits1(&h->gb); /* sp_for_switch_flag */
3971     if (h->slice_type == AV_PICTURE_TYPE_SP ||
3972         h->slice_type == AV_PICTURE_TYPE_SI)
3973         get_se_golomb(&h->gb); /* slice_qs_delta */
3974
3975     h->deblocking_filter     = 1;
3976     h->slice_alpha_c0_offset = 52;
3977     h->slice_beta_offset     = 52;
3978     if (h->pps.deblocking_filter_parameters_present) {
3979         tmp = get_ue_golomb_31(&h->gb);
3980         if (tmp > 2) {
3981             av_log(h->avctx, AV_LOG_ERROR,
3982                    "deblocking_filter_idc %u out of range\n", tmp);
3983             return AVERROR_INVALIDDATA;
3984         }
3985         h->deblocking_filter = tmp;
3986         if (h->deblocking_filter < 2)
3987             h->deblocking_filter ^= 1;  // 1<->0
3988
3989         if (h->deblocking_filter) {
3990             h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3991             h->slice_beta_offset     += get_se_golomb(&h->gb) << 1;
3992             if (h->slice_alpha_c0_offset > 104U ||
3993                 h->slice_beta_offset     > 104U) {
3994                 av_log(h->avctx, AV_LOG_ERROR,
3995                        "deblocking filter parameters %d %d out of range\n",
3996                        h->slice_alpha_c0_offset, h->slice_beta_offset);
3997                 return AVERROR_INVALIDDATA;
3998             }
3999         }
4000     }
4001
4002     if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
4003         (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
4004          h->slice_type_nos != AV_PICTURE_TYPE_I) ||
4005         (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&
4006          h->slice_type_nos == AV_PICTURE_TYPE_B) ||
4007         (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
4008          h->nal_ref_idc == 0))
4009         h->deblocking_filter = 0;
4010
4011     if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
4012         if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
4013             /* Cheat slightly for speed:
4014              * Do not bother to deblock across slices. */
4015             h->deblocking_filter = 2;
4016         } else {
4017             h0->max_contexts = 1;
4018             if (!h0->single_decode_warning) {
4019                 av_log(h->avctx, AV_LOG_INFO,
4020                        "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
4021                 h0->single_decode_warning = 1;
4022             }
4023             if (h != h0) {
4024                 av_log(h->avctx, AV_LOG_ERROR,
4025                        "Deblocking switched inside frame.\n");
4026                 return 1;
4027             }
4028         }
4029     }
4030     h->qp_thresh = 15 + 52 -
4031                    FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
4032                    FFMAX3(0,
4033                           h->pps.chroma_qp_index_offset[0],
4034                           h->pps.chroma_qp_index_offset[1]) +
4035                    6 * (h->sps.bit_depth_luma - 8);
4036
4037     h0->last_slice_type = slice_type;
4038     memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
4039     h->slice_num        = ++h0->current_slice;
4040
4041     if (h->slice_num)
4042         h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
4043     if (   h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
4044         && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
4045         && h->slice_num >= MAX_SLICES) {
4046         //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
4047         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);
4048     }
4049
4050     for (j = 0; j < 2; j++) {
4051         int id_list[16];
4052         int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
4053         for (i = 0; i < 16; i++) {
4054             id_list[i] = 60;
4055             if (j < h->list_count && i < h->ref_count[j] &&
4056                 h->ref_list[j][i].f.buf[0]) {
4057                 int k;
4058                 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
4059                 for (k = 0; k < h->short_ref_count; k++)
4060                     if (h->short_ref[k]->f.buf[0]->buffer == buf) {
4061                         id_list[i] = k;
4062                         break;
4063                     }
4064                 for (k = 0; k < h->long_ref_count; k++)
4065                     if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
4066                         id_list[i] = h->short_ref_count + k;
4067                         break;
4068                     }
4069             }
4070         }
4071
4072         ref2frm[0] =
4073         ref2frm[1] = -1;
4074         for (i = 0; i < 16; i++)
4075             ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
4076         ref2frm[18 + 0] =
4077         ref2frm[18 + 1] = -1;
4078         for (i = 16; i < 48; i++)
4079             ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
4080                              (h->ref_list[j][i].reference & 3);
4081     }
4082
4083     if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
4084     if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
4085     h->er.ref_count = h->ref_count[0];
4086
4087     if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
4088         av_log(h->avctx, AV_LOG_DEBUG,
4089                "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",
4090                h->slice_num,
4091                (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
4092                first_mb_in_slice,
4093                av_get_picture_type_char(h->slice_type),
4094                h->slice_type_fixed ? " fix" : "",
4095                h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
4096                pps_id, h->frame_num,
4097                h->cur_pic_ptr->field_poc[0],
4098                h->cur_pic_ptr->field_poc[1],
4099                h->ref_count[0], h->ref_count[1],
4100                h->qscale,
4101                h->deblocking_filter,
4102                h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
4103                h->use_weight,
4104                h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
4105                h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
4106     }
4107
4108     return 0;
4109 }
4110
4111 int ff_h264_get_slice_type(const H264Context *h)
4112 {
4113     switch (h->slice_type) {
4114     case AV_PICTURE_TYPE_P:
4115         return 0;
4116     case AV_PICTURE_TYPE_B:
4117         return 1;
4118     case AV_PICTURE_TYPE_I:
4119         return 2;
4120     case AV_PICTURE_TYPE_SP:
4121         return 3;
4122     case AV_PICTURE_TYPE_SI:
4123         return 4;
4124     default:
4125         return AVERROR_INVALIDDATA;
4126     }
4127 }
4128
4129 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4130                                                       int mb_type, int top_xy,
4131                                                       int left_xy[LEFT_MBS],
4132                                                       int top_type,
4133                                                       int left_type[LEFT_MBS],
4134                                                       int mb_xy, int list)
4135 {
4136     int b_stride = h->b_stride;
4137     int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4138     int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4139     if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4140         if (USES_LIST(top_type, list)) {
4141             const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;
4142             const int b8_xy = 4 * top_xy + 2;
4143             int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4144             AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4145             ref_cache[0 - 1 * 8] =
4146             ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4147             ref_cache[2 - 1 * 8] =
4148             ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4149         } else {
4150             AV_ZERO128(mv_dst - 1 * 8);
4151             AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4152         }
4153
4154         if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4155             if (USES_LIST(left_type[LTOP], list)) {
4156                 const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;
4157                 const int b8_xy = 4 * left_xy[LTOP] + 1;
4158                 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4159                 AV_COPY32(mv_dst - 1 +  0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4160                 AV_COPY32(mv_dst - 1 +  8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4161                 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4162                 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4163                 ref_cache[-1 +  0] =
4164                 ref_cache[-1 +  8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4165                 ref_cache[-1 + 16] =
4166                 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4167             } else {
4168                 AV_ZERO32(mv_dst - 1 +  0);
4169                 AV_ZERO32(mv_dst - 1 +  8);
4170                 AV_ZERO32(mv_dst - 1 + 16);
4171                 AV_ZERO32(mv_dst - 1 + 24);
4172                 ref_cache[-1 +  0] =
4173                 ref_cache[-1 +  8] =
4174                 ref_cache[-1 + 16] =
4175                 ref_cache[-1 + 24] = LIST_NOT_USED;
4176             }
4177         }
4178     }
4179
4180     if (!USES_LIST(mb_type, list)) {
4181         fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4182         AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4183         AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4184         AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4185         AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4186         return;
4187     }
4188
4189     {
4190         int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4191         int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4192         uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4193         uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4194         AV_WN32A(&ref_cache[0 * 8], ref01);
4195         AV_WN32A(&ref_cache[1 * 8], ref01);
4196         AV_WN32A(&ref_cache[2 * 8], ref23);
4197         AV_WN32A(&ref_cache[3 * 8], ref23);
4198     }
4199
4200     {
4201         int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4202         AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4203         AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4204         AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4205         AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4206     }
4207 }
4208
4209 /**
4210  *
4211  * @return non zero if the loop filter can be skipped
4212  */
4213 static int fill_filter_caches(H264Context *h, int mb_type)
4214 {
4215     const int mb_xy = h->mb_xy;
4216     int top_xy, left_xy[LEFT_MBS];
4217     int top_type, left_type[LEFT_MBS];
4218     uint8_t *nnz;
4219     uint8_t *nnz_cache;
4220
4221     top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4222
4223     /* Wow, what a mess, why didn't they simplify the interlacing & intra
4224      * stuff, I can't imagine that these complex rules are worth it. */
4225
4226     left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4227     if (FRAME_MBAFF(h)) {
4228         const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4229         const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4230         if (h->mb_y & 1) {
4231             if (left_mb_field_flag != curr_mb_field_flag)
4232                 left_xy[LTOP] -= h->mb_stride;
4233         } else {
4234             if (curr_mb_field_flag)
4235                 top_xy += h->mb_stride &
4236                           (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4237             if (left_mb_field_flag != curr_mb_field_flag)
4238                 left_xy[LBOT] += h->mb_stride;
4239         }
4240     }
4241
4242     h->top_mb_xy        = top_xy;
4243     h->left_mb_xy[LTOP] = left_xy[LTOP];
4244     h->left_mb_xy[LBOT] = left_xy[LBOT];
4245     {
4246         /* For sufficiently low qp, filtering wouldn't do anything.
4247          * This is a conservative estimate: could also check beta_offset
4248          * and more accurate chroma_qp. */
4249         int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4250         int qp        = h->cur_pic.qscale_table[mb_xy];
4251         if (qp <= qp_thresh &&
4252             (left_xy[LTOP] < 0 ||
4253              ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4254             (top_xy < 0 ||
4255              ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4256             if (!FRAME_MBAFF(h))
4257                 return 1;
4258             if ((left_xy[LTOP] < 0 ||
4259                  ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4260                 (top_xy < h->mb_stride ||
4261                  ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4262                 return 1;
4263         }
4264     }
4265
4266     top_type        = h->cur_pic.mb_type[top_xy];
4267     left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4268     left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4269     if (h->deblocking_filter == 2) {
4270         if (h->slice_table[top_xy] != h->slice_num)
4271             top_type = 0;
4272         if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4273             left_type[LTOP] = left_type[LBOT] = 0;
4274     } else {
4275         if (h->slice_table[top_xy] == 0xFFFF)
4276             top_type = 0;
4277         if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4278             left_type[LTOP] = left_type[LBOT] = 0;
4279     }
4280     h->top_type        = top_type;
4281     h->left_type[LTOP] = left_type[LTOP];
4282     h->left_type[LBOT] = left_type[LBOT];
4283
4284     if (IS_INTRA(mb_type))
4285         return 0;
4286
4287     fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4288                              top_type, left_type, mb_xy, 0);
4289     if (h->list_count == 2)
4290         fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4291                                  top_type, left_type, mb_xy, 1);
4292
4293     nnz       = h->non_zero_count[mb_xy];
4294     nnz_cache = h->non_zero_count_cache;
4295     AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4296     AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4297     AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4298     AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4299     h->cbp = h->cbp_table[mb_xy];
4300
4301     if (top_type) {
4302         nnz = h->non_zero_count[top_xy];
4303         AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4304     }
4305
4306     if (left_type[LTOP]) {
4307         nnz = h->non_zero_count[left_xy[LTOP]];
4308         nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4309         nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4310         nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4311         nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4312     }
4313
4314     /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4315      * from what the loop filter needs */
4316     if (!CABAC(h) && h->pps.transform_8x8_mode) {
4317         if (IS_8x8DCT(top_type)) {
4318             nnz_cache[4 + 8 * 0] =
4319             nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4320             nnz_cache[6 + 8 * 0] =
4321             nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4322         }
4323         if (IS_8x8DCT(left_type[LTOP])) {
4324             nnz_cache[3 + 8 * 1] =
4325             nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4326         }
4327         if (IS_8x8DCT(left_type[LBOT])) {
4328             nnz_cache[3 + 8 * 3] =
4329             nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4330         }
4331
4332         if (IS_8x8DCT(mb_type)) {
4333             nnz_cache[scan8[0]] =
4334             nnz_cache[scan8[1]] =
4335             nnz_cache[scan8[2]] =
4336             nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4337
4338             nnz_cache[scan8[0 + 4]] =
4339             nnz_cache[scan8[1 + 4]] =
4340             nnz_cache[scan8[2 + 4]] =
4341             nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4342
4343             nnz_cache[scan8[0 + 8]] =
4344             nnz_cache[scan8[1 + 8]] =
4345             nnz_cache[scan8[2 + 8]] =
4346             nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4347
4348             nnz_cache[scan8[0 + 12]] =
4349             nnz_cache[scan8[1 + 12]] =
4350             nnz_cache[scan8[2 + 12]] =
4351             nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4352         }
4353     }
4354
4355     return 0;
4356 }
4357
4358 static void loop_filter(H264Context *h, int start_x, int end_x)
4359 {
4360     uint8_t *dest_y, *dest_cb, *dest_cr;
4361     int linesize, uvlinesize, mb_x, mb_y;
4362     const int end_mb_y       = h->mb_y + FRAME_MBAFF(h);
4363     const int old_slice_type = h->slice_type;
4364     const int pixel_shift    = h->pixel_shift;
4365     const int block_h        = 16 >> h->chroma_y_shift;
4366
4367     if (h->deblocking_filter) {
4368         for (mb_x = start_x; mb_x < end_x; mb_x++)
4369             for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4370                 int mb_xy, mb_type;
4371                 mb_xy         = h->mb_xy = mb_x + mb_y * h->mb_stride;
4372                 h->slice_num  = h->slice_table[mb_xy];
4373                 mb_type       = h->cur_pic.mb_type[mb_xy];
4374                 h->list_count = h->list_counts[mb_xy];
4375
4376                 if (FRAME_MBAFF(h))
4377                     h->mb_mbaff               =
4378                     h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4379
4380                 h->mb_x = mb_x;
4381                 h->mb_y = mb_y;
4382                 dest_y  = h->cur_pic.f.data[0] +
4383                           ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4384                 dest_cb = h->cur_pic.f.data[1] +
4385                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4386                           mb_y * h->uvlinesize * block_h;
4387                 dest_cr = h->cur_pic.f.data[2] +
4388                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4389                           mb_y * h->uvlinesize * block_h;
4390                 // FIXME simplify above
4391
4392                 if (MB_FIELD(h)) {
4393                     linesize   = h->mb_linesize   = h->linesize   * 2;
4394                     uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4395                     if (mb_y & 1) { // FIXME move out of this function?
4396                         dest_y  -= h->linesize   * 15;
4397                         dest_cb -= h->uvlinesize * (block_h - 1);
4398                         dest_cr -= h->uvlinesize * (block_h - 1);
4399                     }
4400                 } else {
4401                     linesize   = h->mb_linesize   = h->linesize;
4402                     uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4403                 }
4404                 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4405                                  uvlinesize, 0);
4406                 if (fill_filter_caches(h, mb_type))
4407                     continue;
4408                 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4409                 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4410
4411                 if (FRAME_MBAFF(h)) {
4412                     ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4413                                       linesize, uvlinesize);
4414                 } else {
4415                     ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4416                                            dest_cr, linesize, uvlinesize);
4417                 }
4418             }
4419     }
4420     h->slice_type   = old_slice_type;
4421     h->mb_x         = end_x;
4422     h->mb_y         = end_mb_y - FRAME_MBAFF(h);
4423     h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4424     h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4425 }
4426
4427 static void predict_field_decoding_flag(H264Context *h)
4428 {
4429     const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4430     int mb_type     = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4431                       h->cur_pic.mb_type[mb_xy - 1] :
4432                       (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4433                       h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4434     h->mb_mbaff     = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4435 }
4436
4437 /**
4438  * Draw edges and report progress for the last MB row.
4439  */
4440 static void decode_finish_row(H264Context *h)
4441 {
4442     int top            = 16 * (h->mb_y      >> FIELD_PICTURE(h));
4443     int pic_height     = 16 *  h->mb_height >> FIELD_PICTURE(h);
4444     int height         =  16      << FRAME_MBAFF(h);
4445     int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4446
4447     if (h->deblocking_filter) {
4448         if ((top + height) >= pic_height)
4449             height += deblock_border;
4450         top -= deblock_border;
4451     }
4452
4453     if (top >= pic_height || (top + height) < 0)
4454         return;
4455
4456     height = FFMIN(height, pic_height - top);
4457     if (top < 0) {
4458         height = top + height;
4459         top    = 0;
4460     }
4461
4462     ff_h264_draw_horiz_band(h, top, height);
4463
4464     if (h->droppable || h->er.error_occurred)
4465         return;
4466
4467     ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4468                               h->picture_structure == PICT_BOTTOM_FIELD);
4469 }
4470
4471 static void er_add_slice(H264Context *h, int startx, int starty,
4472                          int endx, int endy, int status)
4473 {
4474     if (CONFIG_ERROR_RESILIENCE) {
4475         ERContext *er = &h->er;
4476
4477         ff_er_add_slice(er, startx, starty, endx, endy, status);
4478     }
4479 }
4480
4481 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4482 {
4483     H264Context *h = *(void **)arg;
4484     int lf_x_start = h->mb_x;
4485
4486     h->mb_skip_run = -1;
4487
4488     av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4489
4490     h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4491                     avctx->codec_id != AV_CODEC_ID_H264 ||
4492                     (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4493
4494     if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
4495         const int start_i  = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
4496         if (start_i) {
4497             int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
4498             prev_status &= ~ VP_START;
4499             if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
4500                 h->er.error_occurred = 1;
4501         }
4502     }
4503
4504     if (h->pps.cabac) {
4505         /* realign */
4506         align_get_bits(&h->gb);
4507
4508         /* init cabac */
4509         ff_init_cabac_decoder(&h->cabac,
4510                               h->gb.buffer + get_bits_count(&h->gb) / 8,
4511                               (get_bits_left(&h->gb) + 7) / 8);
4512
4513         ff_h264_init_cabac_states(h);
4514
4515         for (;;) {
4516             // START_TIMER
4517             int ret = ff_h264_decode_mb_cabac(h);
4518             int eos;
4519             // STOP_TIMER("decode_mb_cabac")
4520
4521             if (ret >= 0)
4522                 ff_h264_hl_decode_mb(h);
4523
4524             // FIXME optimal? or let mb_decode decode 16x32 ?
4525             if (ret >= 0 && FRAME_MBAFF(h)) {
4526                 h->mb_y++;
4527
4528                 ret = ff_h264_decode_mb_cabac(h);
4529
4530                 if (ret >= 0)
4531                     ff_h264_hl_decode_mb(h);
4532                 h->mb_y--;
4533             }
4534             eos = get_cabac_terminate(&h->cabac);
4535
4536             if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4537                 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4538                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4539                              h->mb_y, ER_MB_END);
4540                 if (h->mb_x >= lf_x_start)
4541                     loop_filter(h, lf_x_start, h->mb_x + 1);
4542                 return 0;
4543             }
4544             if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4545                 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4546             if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4547                 av_log(h->avctx, AV_LOG_ERROR,
4548                        "error while decoding MB %d %d, bytestream (%td)\n",
4549                        h->mb_x, h->mb_y,
4550                        h->cabac.bytestream_end - h->cabac.bytestream);
4551                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4552                              h->mb_y, ER_MB_ERROR);
4553                 return AVERROR_INVALIDDATA;
4554             }
4555
4556             if (++h->mb_x >= h->mb_width) {
4557                 loop_filter(h, lf_x_start, h->mb_x);
4558                 h->mb_x = lf_x_start = 0;
4559                 decode_finish_row(h);
4560                 ++h->mb_y;
4561                 if (FIELD_OR_MBAFF_PICTURE(h)) {
4562                     ++h->mb_y;
4563                     if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4564                         predict_field_decoding_flag(h);
4565                 }
4566             }
4567
4568             if (eos || h->mb_y >= h->mb_height) {
4569                 tprintf(h->avctx, "slice end %d %d\n",
4570                         get_bits_count(&h->gb), h->gb.size_in_bits);
4571                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4572                              h->mb_y, ER_MB_END);
4573                 if (h->mb_x > lf_x_start)
4574                     loop_filter(h, lf_x_start, h->mb_x);
4575                 return 0;
4576             }
4577         }
4578     } else {
4579         for (;;) {
4580             int ret = ff_h264_decode_mb_cavlc(h);
4581
4582             if (ret >= 0)
4583                 ff_h264_hl_decode_mb(h);
4584
4585             // FIXME optimal? or let mb_decode decode 16x32 ?
4586             if (ret >= 0 && FRAME_MBAFF(h)) {
4587                 h->mb_y++;
4588                 ret = ff_h264_decode_mb_cavlc(h);
4589
4590                 if (ret >= 0)
4591                     ff_h264_hl_decode_mb(h);
4592                 h->mb_y--;
4593             }
4594
4595             if (ret < 0) {
4596                 av_log(h->avctx, AV_LOG_ERROR,
4597                        "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4598                 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4599                              h->mb_y, ER_MB_ERROR);
4600                 return ret;
4601             }
4602
4603             if (++h->mb_x >= h->mb_width) {
4604                 loop_filter(h, lf_x_start, h->mb_x);
4605                 h->mb_x = lf_x_start = 0;
4606                 decode_finish_row(h);
4607                 ++h->mb_y;
4608                 if (FIELD_OR_MBAFF_PICTURE(h)) {
4609                     ++h->mb_y;
4610                     if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4611                         predict_field_decoding_flag(h);
4612                 }
4613                 if (h->mb_y >= h->mb_height) {
4614                     tprintf(h->avctx, "slice end %d %d\n",
4615                             get_bits_count(&h->gb), h->gb.size_in_bits);
4616
4617                     if (   get_bits_left(&h->gb) == 0
4618                         || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4619                         er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4620                                      h->mb_x - 1, h->mb_y,
4621                                      ER_MB_END);
4622
4623                         return 0;
4624                     } else {
4625                         er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4626                                      h->mb_x, h->mb_y,
4627                                      ER_MB_END);
4628
4629                         return AVERROR_INVALIDDATA;
4630                     }
4631                 }
4632             }
4633
4634             if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4635                 tprintf(h->avctx, "slice end %d %d\n",
4636                         get_bits_count(&h->gb), h->gb.size_in_bits);
4637
4638                 if (get_bits_left(&h->gb) == 0) {
4639                     er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4640                                  h->mb_x - 1, h->mb_y,
4641                                  ER_MB_END);
4642                     if (h->mb_x > lf_x_start)
4643                         loop_filter(h, lf_x_start, h->mb_x);
4644
4645                     return 0;
4646                 } else {
4647                     er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4648                                  h->mb_y, ER_MB_ERROR);
4649
4650                     return AVERROR_INVALIDDATA;
4651                 }
4652             }
4653         }
4654     }
4655 }
4656
4657 /**
4658  * Call decode_slice() for each context.
4659  *
4660  * @param h h264 master context
4661  * @param context_count number of contexts to execute
4662  */
4663 static int execute_decode_slices(H264Context *h, int context_count)
4664 {
4665     AVCodecContext *const avctx = h->avctx;
4666     H264Context *hx;
4667     int i;
4668
4669     if (h->avctx->hwaccel ||
4670         h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4671         return 0;
4672     if (context_count == 1) {
4673         return decode_slice(avctx, &h);
4674     } else {
4675         av_assert0(context_count > 0);
4676         for (i = 1; i < context_count; i++) {
4677             hx                 = h->thread_context[i];
4678             if (CONFIG_ERROR_RESILIENCE) {
4679                 hx->er.error_count = 0;
4680             }
4681             hx->x264_build     = h->x264_build;
4682         }
4683
4684         avctx->execute(avctx, decode_slice, h->thread_context,
4685                        NULL, context_count, sizeof(void *));
4686
4687         /* pull back stuff from slices to master context */
4688         hx                   = h->thread_context[context_count - 1];
4689         h->mb_x              = hx->mb_x;
4690         h->mb_y              = hx->mb_y;
4691         h->droppable         = hx->droppable;
4692         h->picture_structure = hx->picture_structure;
4693         if (CONFIG_ERROR_RESILIENCE) {
4694             for (i = 1; i < context_count; i++)
4695                 h->er.error_count += h->thread_context[i]->er.error_count;
4696         }
4697     }
4698
4699     return 0;
4700 }
4701
4702 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
4703
4704 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4705                             int parse_extradata)
4706 {
4707     AVCodecContext *const avctx = h->avctx;
4708     H264Context *hx; ///< thread context
4709     int buf_index;
4710     int context_count;
4711     int next_avc;
4712     int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4713     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4714     int nal_index;
4715     int idr_cleared=0;
4716     int first_slice = 0;
4717     int ret = 0;
4718
4719     h->nal_unit_type= 0;
4720
4721     if(!h->slice_context_count)
4722          h->slice_context_count= 1;
4723     h->max_contexts = h->slice_context_count;
4724     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4725         h->current_slice = 0;
4726         if (!h->first_field)
4727             h->cur_pic_ptr = NULL;
4728         ff_h264_reset_sei(h);
4729     }
4730
4731     if (h->nal_length_size == 4) {
4732         if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4733             h->is_avc = 0;
4734         }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4735             h->is_avc = 1;
4736     }
4737
4738     for (; pass <= 1; pass++) {
4739         buf_index     = 0;
4740         context_count = 0;
4741         next_avc      = h->is_avc ? 0 : buf_size;
4742         nal_index     = 0;
4743         for (;;) {
4744             int consumed;
4745             int dst_length;
4746             int bit_length;
4747             const uint8_t *ptr;
4748             int i, nalsize = 0;
4749             int err;
4750
4751             if (buf_index >= next_avc) {
4752                 if (buf_index >= buf_size - h->nal_length_size)
4753                     break;
4754                 nalsize = 0;
4755                 for (i = 0; i < h->nal_length_size; i++)
4756                     nalsize = (nalsize << 8) | buf[buf_index++];
4757                 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4758                     av_log(h->avctx, AV_LOG_ERROR,
4759                            "AVC: nal size %d\n", nalsize);
4760                     break;
4761                 }
4762                 next_avc = buf_index + nalsize;
4763             } else {
4764                 // start code prefix search
4765                 for (; buf_index + 3 < next_avc; buf_index++)
4766                     // This should always succeed in the first iteration.
4767                     if (buf[buf_index]     == 0 &&
4768                         buf[buf_index + 1] == 0 &&
4769                         buf[buf_index + 2] == 1)
4770                         break;
4771
4772                 if (buf_index + 3 >= buf_size) {
4773                     buf_index = buf_size;
4774                     break;
4775                 }
4776
4777                 buf_index += 3;
4778                 if (buf_index >= next_avc)
4779                     continue;
4780             }
4781
4782             hx = h->thread_context[context_count];
4783
4784             ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4785                                      &consumed, next_avc - buf_index);
4786             if (ptr == NULL || dst_length < 0) {
4787                 ret = -1;
4788                 goto end;
4789             }
4790             i = buf_index + consumed;
4791             if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4792                 buf[i]     == 0x00 && buf[i + 1] == 0x00 &&
4793                 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4794                 h->workaround_bugs |= FF_BUG_TRUNCATED;
4795
4796             if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4797                 while (dst_length > 0 && ptr[dst_length - 1] == 0)
4798                     dst_length--;
4799             bit_length = !dst_length ? 0
4800                                      : (8 * dst_length -
4801                                         decode_rbsp_trailing(h, ptr + dst_length - 1));
4802
4803             if (h->avctx->debug & FF_DEBUG_STARTCODE)
4804                 av_log(h->avctx, AV_LOG_DEBUG,
4805                        "NAL %d/%d at %d/%d length %d pass %d\n",
4806                        hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4807
4808             if (h->is_avc && (nalsize != consumed) && nalsize)
4809                 av_log(h->avctx, AV_LOG_DEBUG,
4810                        "AVC: Consumed only %d bytes instead of %d\n",
4811                        consumed, nalsize);
4812
4813             buf_index += consumed;
4814             nal_index++;
4815
4816             if (pass == 0) {
4817                 /* packets can sometimes contain multiple PPS/SPS,
4818                  * e.g. two PAFF field pictures in one packet, or a demuxer
4819                  * which splits NALs strangely if so, when frame threading we
4820                  * can't start the next thread until we've read all of them */
4821                 switch (hx->nal_unit_type) {
4822                 case NAL_SPS:
4823                 case NAL_PPS:
4824                     nals_needed = nal_index;
4825                     break;
4826                 case NAL_DPA:
4827                 case NAL_IDR_SLICE:
4828                 case NAL_SLICE:
4829                     init_get_bits(&hx->gb, ptr, bit_length);
4830                     if (!get_ue_golomb(&hx->gb) || !first_slice)
4831                         nals_needed = nal_index;
4832                     if (!first_slice)
4833                         first_slice = hx->nal_unit_type;
4834                 }
4835                 continue;
4836             }
4837
4838             if (!first_slice)
4839                 switch (hx->nal_unit_type) {
4840                 case NAL_DPA:
4841                 case NAL_IDR_SLICE:
4842                 case NAL_SLICE:
4843                     first_slice = hx->nal_unit_type;
4844                 }
4845
4846             if (avctx->skip_frame >= AVDISCARD_NONREF &&
4847                 h->nal_ref_idc == 0 &&
4848                 h->nal_unit_type != NAL_SEI)
4849                 continue;
4850
4851 again:
4852             /* Ignore per frame NAL unit type during extradata
4853              * parsing. Decoding slices is not possible in codec init
4854              * with frame-mt */
4855             if (parse_extradata) {
4856                 switch (hx->nal_unit_type) {
4857                 case NAL_IDR_SLICE:
4858                 case NAL_SLICE:
4859                 case NAL_DPA:
4860                 case NAL_DPB:
4861                 case NAL_DPC:
4862                     av_log(h->avctx, AV_LOG_WARNING,
4863                            "Ignoring NAL %d in global header/extradata\n",
4864                            hx->nal_unit_type);
4865                     // fall through to next case
4866                 case NAL_AUXILIARY_SLICE:
4867                     hx->nal_unit_type = NAL_FF_IGNORE;
4868                 }
4869             }
4870
4871             err = 0;
4872
4873             switch (hx->nal_unit_type) {
4874             case NAL_IDR_SLICE:
4875                 if (first_slice != NAL_IDR_SLICE) {
4876                     av_log(h->avctx, AV_LOG_ERROR,
4877                            "Invalid mix of idr and non-idr slices\n");
4878                     ret = -1;
4879                     goto end;
4880                 }
4881                 if(!idr_cleared)
4882                     idr(h); // FIXME ensure we don't lose some frames if there is reordering
4883                 idr_cleared = 1;
4884             case NAL_SLICE:
4885                 init_get_bits(&hx->gb, ptr, bit_length);
4886                 hx->intra_gb_ptr      =
4887                 hx->inter_gb_ptr      = &hx->gb;
4888                 hx->data_partitioning = 0;
4889
4890                 if ((err = decode_slice_header(hx, h)))
4891                     break;
4892
4893                 if (h->sei_recovery_frame_cnt >= 0) {
4894                     if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
4895                         h->valid_recovery_point = 1;
4896
4897                     if (   h->recovery_frame < 0
4898                         || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
4899                         h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4900                                             ((1 << h->sps.log2_max_frame_num) - 1);
4901
4902                         if (!h->valid_recovery_point)
4903                             h->recovery_frame = h->frame_num;
4904                     }
4905                 }
4906
4907                 h->cur_pic_ptr->f.key_frame |=
4908                     (hx->nal_unit_type == NAL_IDR_SLICE);
4909
4910                 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4911                     h->recovery_frame == h->frame_num) {
4912                     h->recovery_frame         = -1;
4913                     h->cur_pic_ptr->recovered = 1;
4914                 }
4915                 // If we have an IDR, all frames after it in decoded order are
4916                 // "recovered".
4917                 if (hx->nal_unit_type == NAL_IDR_SLICE)
4918                     h->frame_recovered |= FRAME_RECOVERED_IDR;
4919                 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4920                 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
4921 #if 1
4922                 h->cur_pic_ptr->recovered |= h->frame_recovered;
4923 #else
4924                 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4925 #endif
4926
4927                 if (h->current_slice == 1) {
4928                     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4929                         decode_postinit(h, nal_index >= nals_needed);
4930
4931                     if (h->avctx->hwaccel &&
4932                         (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4933                         return ret;
4934                     if (CONFIG_H264_VDPAU_DECODER &&
4935                         h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4936                         ff_vdpau_h264_picture_start(h);
4937                 }
4938
4939                 if (hx->redundant_pic_count == 0 &&
4940                     (avctx->skip_frame < AVDISCARD_NONREF ||
4941                      hx->nal_ref_idc) &&
4942                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
4943                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4944                     (avctx->skip_frame < AVDISCARD_NONKEY ||
4945                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4946                     avctx->skip_frame < AVDISCARD_ALL) {
4947                     if (avctx->hwaccel) {
4948                         ret = avctx->hwaccel->decode_slice(avctx,
4949                                                            &buf[buf_index - consumed],
4950                                                            consumed);
4951                         if (ret < 0)
4952                             return ret;
4953                     } else if (CONFIG_H264_VDPAU_DECODER &&
4954                                h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4955                         ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4956                                                 start_code,
4957                                                 sizeof(start_code));
4958                         ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4959                                                 &buf[buf_index - consumed],
4960                                                 consumed);
4961                     } else
4962                         context_count++;
4963                 }
4964                 break;
4965             case NAL_DPA:
4966                 init_get_bits(&hx->gb, ptr, bit_length);
4967                 hx->intra_gb_ptr =
4968                 hx->inter_gb_ptr = NULL;
4969
4970                 if ((err = decode_slice_header(hx, h)) < 0)
4971                     break;
4972
4973                 hx->data_partitioning = 1;
4974                 break;
4975             case NAL_DPB:
4976                 init_get_bits(&hx->intra_gb, ptr, bit_length);
4977                 hx->intra_gb_ptr = &hx->intra_gb;
4978                 break;
4979             case NAL_DPC:
4980                 init_get_bits(&hx->inter_gb, ptr, bit_length);
4981                 hx->inter_gb_ptr = &hx->inter_gb;
4982
4983                 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
4984                 break;
4985
4986                 if (hx->redundant_pic_count == 0 &&
4987                     hx->intra_gb_ptr &&
4988                     hx->data_partitioning &&
4989                     h->cur_pic_ptr && h->context_initialized &&
4990                     (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4991                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
4992                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4993                     (avctx->skip_frame < AVDISCARD_NONKEY ||
4994                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4995                     avctx->skip_frame < AVDISCARD_ALL)
4996                     context_count++;
4997                 break;
4998             case NAL_SEI:
4999                 init_get_bits(&h->gb, ptr, bit_length);
5000                 ff_h264_decode_sei(h);
5001                 break;
5002             case NAL_SPS:
5003                 init_get_bits(&h->gb, ptr, bit_length);
5004                 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
5005                     av_log(h->avctx, AV_LOG_DEBUG,
5006                            "SPS decoding failure, trying again with the complete NAL\n");
5007                     if (h->is_avc)
5008                         av_assert0(next_avc - buf_index + consumed == nalsize);
5009                     if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
5010                         break;
5011                     init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
5012                                   8*(next_avc - buf_index + consumed - 1));
5013                     ff_h264_decode_seq_parameter_set(h);
5014                 }
5015
5016                 break;
5017             case NAL_PPS:
5018                 init_get_bits(&h->gb, ptr, bit_length);
5019                 ff_h264_decode_picture_parameter_set(h, bit_length);
5020                 break;
5021             case NAL_AUD:
5022             case NAL_END_SEQUENCE:
5023             case NAL_END_STREAM:
5024             case NAL_FILLER_DATA:
5025             case NAL_SPS_EXT:
5026             case NAL_AUXILIARY_SLICE:
5027                 break;
5028             case NAL_FF_IGNORE:
5029                 break;
5030             default:
5031                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
5032                        hx->nal_unit_type, bit_length);
5033             }
5034
5035             if (context_count == h->max_contexts) {
5036                 execute_decode_slices(h, context_count);
5037                 context_count = 0;
5038             }
5039
5040             if (err < 0)
5041                 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
5042             else if (err == 1) {
5043                 /* Slice could not be decoded in parallel mode, copy down
5044                  * NAL unit stuff to context 0 and restart. Note that
5045                  * rbsp_buffer is not transferred, but since we no longer
5046                  * run in parallel mode this should not be an issue. */
5047                 h->nal_unit_type = hx->nal_unit_type;
5048                 h->nal_ref_idc   = hx->nal_ref_idc;
5049                 hx               = h;
5050                 goto again;
5051             }
5052         }
5053     }
5054     if (context_count)
5055         execute_decode_slices(h, context_count);
5056
5057 end:
5058     /* clean up */
5059     if (h->cur_pic_ptr && !h->droppable) {
5060         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
5061                                   h->picture_structure == PICT_BOTTOM_FIELD);
5062     }
5063
5064     return (ret < 0) ? ret : buf_index;
5065 }
5066
5067 /**
5068  * Return the number of bytes consumed for building the current frame.
5069  */
5070 static int get_consumed_bytes(int pos, int buf_size)
5071 {
5072     if (pos == 0)
5073         pos = 1;          // avoid infinite loops (i doubt that is needed but ...)
5074     if (pos + 10 > buf_size)
5075         pos = buf_size;                   // oops ;)
5076
5077     return pos;
5078 }
5079
5080 static int output_frame(H264Context *h, AVFrame *dst, Picture *srcp)
5081 {
5082     AVFrame *src = &srcp->f;
5083     int i;
5084     int ret = av_frame_ref(dst, src);
5085     if (ret < 0)
5086         return ret;
5087
5088     av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
5089
5090     if (!srcp->crop)
5091         return 0;
5092
5093     for (i = 0; i < 3; i++) {
5094         int hshift = (i > 0) ? h->chroma_x_shift : 0;
5095         int vshift = (i > 0) ? h->chroma_y_shift : 0;
5096         int off    = ((srcp->crop_left >> hshift) << h->pixel_shift) +
5097                       (srcp->crop_top  >> vshift) * dst->linesize[i];
5098         dst->data[i] += off;
5099     }
5100     return 0;
5101 }
5102
5103 static int h264_decode_frame(AVCodecContext *avctx, void *data,
5104                              int *got_frame, AVPacket *avpkt)
5105 {
5106     const uint8_t *buf = avpkt->data;
5107     int buf_size       = avpkt->size;
5108     H264Context *h     = avctx->priv_data;
5109     AVFrame *pict      = data;
5110     int buf_index      = 0;
5111     Picture *out;
5112     int i, out_idx;
5113     int ret;
5114
5115     h->flags = avctx->flags;
5116
5117     /* end of stream, output what is still in the buffers */
5118     if (buf_size == 0) {
5119  out:
5120
5121         h->cur_pic_ptr = NULL;
5122         h->first_field = 0;
5123
5124         // FIXME factorize this with the output code below
5125         out     = h->delayed_pic[0];
5126         out_idx = 0;
5127         for (i = 1;
5128              h->delayed_pic[i] &&
5129              !h->delayed_pic[i]->f.key_frame &&
5130              !h->delayed_pic[i]->mmco_reset;
5131              i++)
5132             if (h->delayed_pic[i]->poc < out->poc) {
5133                 out     = h->delayed_pic[i];
5134                 out_idx = i;
5135             }
5136
5137         for (i = out_idx; h->delayed_pic[i]; i++)
5138             h->delayed_pic[i] = h->delayed_pic[i + 1];
5139
5140         if (out) {
5141             out->reference &= ~DELAYED_PIC_REF;
5142             ret = output_frame(h, pict, out);
5143             if (ret < 0)
5144                 return ret;
5145             *got_frame = 1;
5146         }
5147
5148         return buf_index;
5149     }
5150     if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
5151         int cnt= buf[5]&0x1f;
5152         const uint8_t *p= buf+6;
5153         while(cnt--){
5154             int nalsize= AV_RB16(p) + 2;
5155             if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
5156                 goto not_extra;
5157             p += nalsize;
5158         }
5159         cnt = *(p++);
5160         if(!cnt)
5161             goto not_extra;
5162         while(cnt--){
5163             int nalsize= AV_RB16(p) + 2;
5164             if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
5165                 goto not_extra;
5166             p += nalsize;
5167         }
5168
5169         return ff_h264_decode_extradata(h, buf, buf_size);
5170     }
5171 not_extra:
5172
5173     buf_index = decode_nal_units(h, buf, buf_size, 0);
5174     if (buf_index < 0)
5175         return AVERROR_INVALIDDATA;
5176
5177     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
5178         av_assert0(buf_index <= buf_size);
5179         goto out;
5180     }
5181
5182     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
5183         if (avctx->skip_frame >= AVDISCARD_NONREF ||
5184             buf_size >= 4 && !memcmp("Q264", buf, 4))
5185             return buf_size;
5186         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
5187         return AVERROR_INVALIDDATA;
5188     }
5189
5190     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
5191         (h->mb_y >= h->mb_height && h->mb_height)) {
5192         if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
5193             decode_postinit(h, 1);
5194
5195         field_end(h, 0);
5196
5197         /* Wait for second field. */
5198         *got_frame = 0;
5199         if (h->next_output_pic && (
5200                                    h->next_output_pic->recovered)) {
5201             if (!h->next_output_pic->recovered)
5202                 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
5203
5204             ret = output_frame(h, pict, h->next_output_pic);
5205             if (ret < 0)
5206                 return ret;
5207             *got_frame = 1;
5208             if (CONFIG_MPEGVIDEO) {
5209                 ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
5210                                     &h->low_delay,
5211                                     h->mb_width, h->mb_height, h->mb_stride, 1);
5212             }
5213         }
5214     }
5215
5216     assert(pict->buf[0] || !*got_frame);
5217
5218     return get_consumed_bytes(buf_index, buf_size);
5219 }
5220
5221 av_cold void ff_h264_free_context(H264Context *h)
5222 {
5223     int i;
5224
5225     free_tables(h, 1); // FIXME cleanup init stuff perhaps
5226
5227     for (i = 0; i < MAX_SPS_COUNT; i++)
5228         av_freep(h->sps_buffers + i);
5229
5230     for (i = 0; i < MAX_PPS_COUNT; i++)
5231         av_freep(h->pps_buffers + i);
5232 }
5233
5234 static av_cold int h264_decode_end(AVCodecContext *avctx)
5235 {
5236     H264Context *h = avctx->priv_data;
5237
5238     ff_h264_remove_all_refs(h);
5239     ff_h264_free_context(h);
5240
5241     unref_picture(h, &h->cur_pic);
5242
5243     return 0;
5244 }
5245
5246 static const AVProfile profiles[] = {
5247     { FF_PROFILE_H264_BASELINE,             "Baseline"              },
5248     { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
5249     { FF_PROFILE_H264_MAIN,                 "Main"                  },
5250     { FF_PROFILE_H264_EXTENDED,             "Extended"              },
5251     { FF_PROFILE_H264_HIGH,                 "High"                  },
5252     { FF_PROFILE_H264_HIGH_10,              "High 10"               },
5253     { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
5254     { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
5255     { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
5256     { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
5257     { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
5258     { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
5259     { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
5260     { FF_PROFILE_UNKNOWN },
5261 };
5262
5263 static const AVOption h264_options[] = {
5264     {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
5265     {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
5266     {NULL}
5267 };
5268
5269 static const AVClass h264_class = {
5270     .class_name = "H264 Decoder",
5271     .item_name  = av_default_item_name,
5272     .option     = h264_options,
5273     .version    = LIBAVUTIL_VERSION_INT,
5274 };
5275
5276 static const AVClass h264_vdpau_class = {
5277     .class_name = "H264 VDPAU Decoder",
5278     .item_name  = av_default_item_name,
5279     .option     = h264_options,
5280     .version    = LIBAVUTIL_VERSION_INT,
5281 };
5282
5283 AVCodec ff_h264_decoder = {
5284     .name                  = "h264",
5285     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5286     .type                  = AVMEDIA_TYPE_VIDEO,
5287     .id                    = AV_CODEC_ID_H264,
5288     .priv_data_size        = sizeof(H264Context),
5289     .init                  = ff_h264_decode_init,
5290     .close                 = h264_decode_end,
5291     .decode                = h264_decode_frame,
5292     .capabilities          = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5293                              CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5294                              CODEC_CAP_FRAME_THREADS,
5295     .flush                 = flush_dpb,
5296     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5297     .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5298     .profiles              = NULL_IF_CONFIG_SMALL(profiles),
5299     .priv_class            = &h264_class,
5300 };
5301
5302 #if CONFIG_H264_VDPAU_DECODER
5303 AVCodec ff_h264_vdpau_decoder = {
5304     .name           = "h264_vdpau",
5305     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
5306     .type           = AVMEDIA_TYPE_VIDEO,
5307     .id             = AV_CODEC_ID_H264,
5308     .priv_data_size = sizeof(H264Context),
5309     .init           = ff_h264_decode_init,
5310     .close          = h264_decode_end,
5311     .decode         = h264_decode_frame,
5312     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5313     .flush          = flush_dpb,
5314     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
5315                                                      AV_PIX_FMT_NONE},
5316     .profiles       = NULL_IF_CONFIG_SMALL(profiles),
5317     .priv_class     = &h264_vdpau_class,
5318 };
5319 #endif