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