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