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