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