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