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