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