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