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