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