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