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