OSDN Git Service

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