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