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