Merge commit '716d413c13981da15323c7a3821860536eefdbbb'
[ffmpeg.git] / 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     AV_PIX_FMT_DXVA2_VLD,
71     AV_PIX_FMT_VAAPI_VLD,
72     AV_PIX_FMT_VDA_VLD,
73     AV_PIX_FMT_YUVJ420P,
74     AV_PIX_FMT_NONE
75 };
76
77 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
78 {
79     H264Context *h = avctx->priv_data;
80     return h ? h->sps.num_reorder_frames : 0;
81 }
82
83 /**
84  * Check if the top & left blocks are available if needed and
85  * change the dc mode so it only uses the available blocks.
86  */
87 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
88 {
89     MpegEncContext *const s     = &h->s;
90     static const int8_t top[12] = {
91         -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
92     };
93     static const int8_t left[12] = {
94         0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
95     };
96     int i;
97
98     if (!(h->top_samples_available & 0x8000)) {
99         for (i = 0; i < 4; i++) {
100             int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
101             if (status < 0) {
102                 av_log(h->s.avctx, AV_LOG_ERROR,
103                        "top block unavailable for requested intra4x4 mode %d at %d %d\n",
104                        status, s->mb_x, s->mb_y);
105                 return -1;
106             } else if (status) {
107                 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
108             }
109         }
110     }
111
112     if ((h->left_samples_available & 0x8888) != 0x8888) {
113         static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
114         for (i = 0; i < 4; i++)
115             if (!(h->left_samples_available & mask[i])) {
116                 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
117                 if (status < 0) {
118                     av_log(h->s.avctx, AV_LOG_ERROR,
119                            "left block unavailable for requested intra4x4 mode %d at %d %d\n",
120                            status, s->mb_x, s->mb_y);
121                     return -1;
122                 } else if (status) {
123                     h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
124                 }
125             }
126     }
127
128     return 0;
129 } // FIXME cleanup like ff_h264_check_intra_pred_mode
130
131 /**
132  * Check if the top & left blocks are available if needed and
133  * change the dc mode so it only uses the available blocks.
134  */
135 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
136 {
137     MpegEncContext *const s     = &h->s;
138     static const int8_t top[7]  = { LEFT_DC_PRED8x8, 1, -1, -1 };
139     static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
140
141     if (mode > 6U) {
142         av_log(h->s.avctx, AV_LOG_ERROR,
143                "out of range intra chroma pred mode at %d %d\n",
144                s->mb_x, s->mb_y);
145         return -1;
146     }
147
148     if (!(h->top_samples_available & 0x8000)) {
149         mode = top[mode];
150         if (mode < 0) {
151             av_log(h->s.avctx, AV_LOG_ERROR,
152                    "top block unavailable for requested intra mode at %d %d\n",
153                    s->mb_x, s->mb_y);
154             return -1;
155         }
156     }
157
158     if ((h->left_samples_available & 0x8080) != 0x8080) {
159         mode = left[mode];
160         if (is_chroma && (h->left_samples_available & 0x8080)) {
161             // mad cow disease mode, aka MBAFF + constrained_intra_pred
162             mode = ALZHEIMER_DC_L0T_PRED8x8 +
163                    (!(h->left_samples_available & 0x8000)) +
164                    2 * (mode == DC_128_PRED8x8);
165         }
166         if (mode < 0) {
167             av_log(h->s.avctx, AV_LOG_ERROR,
168                    "left block unavailable for requested intra mode at %d %d\n",
169                    s->mb_x, s->mb_y);
170             return -1;
171         }
172     }
173
174     return mode;
175 }
176
177 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
178                                   int *dst_length, int *consumed, int length)
179 {
180     int i, si, di;
181     uint8_t *dst;
182     int bufidx;
183
184     // src[0]&0x80; // forbidden bit
185     h->nal_ref_idc   = src[0] >> 5;
186     h->nal_unit_type = src[0] & 0x1F;
187
188     src++;
189     length--;
190
191 #define STARTCODE_TEST                                                  \
192         if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {     \
193             if (src[i + 2] != 3) {                                      \
194                 /* startcode, so we must be past the end */             \
195                 length = i;                                             \
196             }                                                           \
197             break;                                                      \
198         }
199 #if HAVE_FAST_UNALIGNED
200 #define FIND_FIRST_ZERO                                                 \
201         if (i > 0 && !src[i])                                           \
202             i--;                                                        \
203         while (src[i])                                                  \
204             i++
205 #if HAVE_FAST_64BIT
206     for (i = 0; i + 1 < length; i += 9) {
207         if (!((~AV_RN64A(src + i) &
208                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
209               0x8000800080008080ULL))
210             continue;
211         FIND_FIRST_ZERO;
212         STARTCODE_TEST;
213         i -= 7;
214     }
215 #else
216     for (i = 0; i + 1 < length; i += 5) {
217         if (!((~AV_RN32A(src + i) &
218                (AV_RN32A(src + i) - 0x01000101U)) &
219               0x80008080U))
220             continue;
221         FIND_FIRST_ZERO;
222         STARTCODE_TEST;
223         i -= 3;
224     }
225 #endif
226 #else
227     for (i = 0; i + 1 < length; i += 2) {
228         if (src[i])
229             continue;
230         if (i > 0 && src[i - 1] == 0)
231             i--;
232         STARTCODE_TEST;
233     }
234 #endif
235
236     // use second escape buffer for inter data
237     bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
238
239     si = h->rbsp_buffer_size[bufidx];
240     av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
241     dst = h->rbsp_buffer[bufidx];
242
243     if (dst == NULL)
244         return NULL;
245
246     if(i>=length-1){ //no escaped 0
247         *dst_length= length;
248         *consumed= length+1; //+1 for the header
249         if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
250             return src;
251         }else{
252             memcpy(dst, src, length);
253             return dst;
254         }
255     }
256
257     memcpy(dst, src, i);
258     si = di = i;
259     while (si + 2 < length) {
260         // remove escapes (very rare 1:2^22)
261         if (src[si + 2] > 3) {
262             dst[di++] = src[si++];
263             dst[di++] = src[si++];
264         } else if (src[si] == 0 && src[si + 1] == 0) {
265             if (src[si + 2] == 3) { // escape
266                 dst[di++]  = 0;
267                 dst[di++]  = 0;
268                 si        += 3;
269                 continue;
270             } else // next start code
271                 goto nsc;
272         }
273
274         dst[di++] = src[si++];
275     }
276     while (si < length)
277         dst[di++] = src[si++];
278 nsc:
279
280     memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
281
282     *dst_length = di;
283     *consumed   = si + 1; // +1 for the header
284     /* FIXME store exact number of bits in the getbitcontext
285      * (it is needed for decoding) */
286     return dst;
287 }
288
289 /**
290  * Identify the exact end of the bitstream
291  * @return the length of the trailing, or 0 if damaged
292  */
293 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
294 {
295     int v = *src;
296     int r;
297
298     tprintf(h->s.avctx, "rbsp trailing %X\n", v);
299
300     for (r = 1; r < 9; r++) {
301         if (v & 1)
302             return r;
303         v >>= 1;
304     }
305     return 0;
306 }
307
308 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
309                                          int height, int y_offset, int list)
310 {
311     int raw_my        = h->mv_cache[list][scan8[n]][1];
312     int filter_height = (raw_my & 3) ? 2 : 0;
313     int full_my       = (raw_my >> 2) + y_offset;
314     int top           = full_my - filter_height;
315     int bottom        = full_my + filter_height + height;
316
317     return FFMAX(abs(top), bottom);
318 }
319
320 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
321                                      int height, int y_offset, int list0,
322                                      int list1, int *nrefs)
323 {
324     MpegEncContext *const s = &h->s;
325     int my;
326
327     y_offset += 16 * (s->mb_y >> MB_FIELD);
328
329     if (list0) {
330         int ref_n    = h->ref_cache[0][scan8[n]];
331         Picture *ref = &h->ref_list[0][ref_n];
332
333         // Error resilience puts the current picture in the ref list.
334         // Don't try to wait on these as it will cause a deadlock.
335         // Fields can wait on each other, though.
336         if (ref->f.thread_opaque   != s->current_picture.f.thread_opaque ||
337             (ref->f.reference & 3) != s->picture_structure) {
338             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
339             if (refs[0][ref_n] < 0)
340                 nrefs[0] += 1;
341             refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
342         }
343     }
344
345     if (list1) {
346         int ref_n    = h->ref_cache[1][scan8[n]];
347         Picture *ref = &h->ref_list[1][ref_n];
348
349         if (ref->f.thread_opaque   != s->current_picture.f.thread_opaque ||
350             (ref->f.reference & 3) != s->picture_structure) {
351             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
352             if (refs[1][ref_n] < 0)
353                 nrefs[1] += 1;
354             refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
355         }
356     }
357 }
358
359 /**
360  * Wait until all reference frames are available for MC operations.
361  *
362  * @param h the H264 context
363  */
364 static void await_references(H264Context *h)
365 {
366     MpegEncContext *const s = &h->s;
367     const int mb_xy   = h->mb_xy;
368     const int mb_type = s->current_picture.f.mb_type[mb_xy];
369     int refs[2][48];
370     int nrefs[2] = { 0 };
371     int ref, list;
372
373     memset(refs, -1, sizeof(refs));
374
375     if (IS_16X16(mb_type)) {
376         get_lowest_part_y(h, refs, 0, 16, 0,
377                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
378     } else if (IS_16X8(mb_type)) {
379         get_lowest_part_y(h, refs, 0, 8, 0,
380                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
381         get_lowest_part_y(h, refs, 8, 8, 8,
382                           IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
383     } else if (IS_8X16(mb_type)) {
384         get_lowest_part_y(h, refs, 0, 16, 0,
385                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
386         get_lowest_part_y(h, refs, 4, 16, 0,
387                           IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
388     } else {
389         int i;
390
391         av_assert2(IS_8X8(mb_type));
392
393         for (i = 0; i < 4; i++) {
394             const int sub_mb_type = h->sub_mb_type[i];
395             const int n           = 4 * i;
396             int y_offset          = (i & 2) << 2;
397
398             if (IS_SUB_8X8(sub_mb_type)) {
399                 get_lowest_part_y(h, refs, n, 8, y_offset,
400                                   IS_DIR(sub_mb_type, 0, 0),
401                                   IS_DIR(sub_mb_type, 0, 1),
402                                   nrefs);
403             } else if (IS_SUB_8X4(sub_mb_type)) {
404                 get_lowest_part_y(h, refs, n, 4, y_offset,
405                                   IS_DIR(sub_mb_type, 0, 0),
406                                   IS_DIR(sub_mb_type, 0, 1),
407                                   nrefs);
408                 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
409                                   IS_DIR(sub_mb_type, 0, 0),
410                                   IS_DIR(sub_mb_type, 0, 1),
411                                   nrefs);
412             } else if (IS_SUB_4X8(sub_mb_type)) {
413                 get_lowest_part_y(h, refs, n, 8, y_offset,
414                                   IS_DIR(sub_mb_type, 0, 0),
415                                   IS_DIR(sub_mb_type, 0, 1),
416                                   nrefs);
417                 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
418                                   IS_DIR(sub_mb_type, 0, 0),
419                                   IS_DIR(sub_mb_type, 0, 1),
420                                   nrefs);
421             } else {
422                 int j;
423                 av_assert2(IS_SUB_4X4(sub_mb_type));
424                 for (j = 0; j < 4; j++) {
425                     int sub_y_offset = y_offset + 2 * (j & 2);
426                     get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
427                                       IS_DIR(sub_mb_type, 0, 0),
428                                       IS_DIR(sub_mb_type, 0, 1),
429                                       nrefs);
430                 }
431             }
432         }
433     }
434
435     for (list = h->list_count - 1; list >= 0; list--)
436         for (ref = 0; ref < 48 && nrefs[list]; ref++) {
437             int row = refs[list][ref];
438             if (row >= 0) {
439                 Picture *ref_pic      = &h->ref_list[list][ref];
440                 int ref_field         = ref_pic->f.reference - 1;
441                 int ref_field_picture = ref_pic->field_picture;
442                 int pic_height        = 16 * s->mb_height >> ref_field_picture;
443
444                 row <<= MB_MBAFF;
445                 nrefs[list]--;
446
447                 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
448                     ff_thread_await_progress(&ref_pic->f,
449                                              FFMIN((row >> 1) - !(row & 1),
450                                                    pic_height - 1),
451                                              1);
452                     ff_thread_await_progress(&ref_pic->f,
453                                              FFMIN((row >> 1), pic_height - 1),
454                                              0);
455                 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
456                     ff_thread_await_progress(&ref_pic->f,
457                                              FFMIN(row * 2 + ref_field,
458                                                    pic_height - 1),
459                                              0);
460                 } else if (FIELD_PICTURE) {
461                     ff_thread_await_progress(&ref_pic->f,
462                                              FFMIN(row, pic_height - 1),
463                                              ref_field);
464                 } else {
465                     ff_thread_await_progress(&ref_pic->f,
466                                              FFMIN(row, pic_height - 1),
467                                              0);
468                 }
469             }
470         }
471 }
472
473 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
474                                          int n, int square, int height,
475                                          int delta, int list,
476                                          uint8_t *dest_y, uint8_t *dest_cb,
477                                          uint8_t *dest_cr,
478                                          int src_x_offset, int src_y_offset,
479                                          qpel_mc_func *qpix_op,
480                                          h264_chroma_mc_func chroma_op,
481                                          int pixel_shift, int chroma_idc)
482 {
483     MpegEncContext *const s = &h->s;
484     const int mx      = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
485     int my            = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
486     const int luma_xy = (mx & 3) + ((my & 3) << 2);
487     int offset        = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
488     uint8_t *src_y    = pic->f.data[0] + offset;
489     uint8_t *src_cb, *src_cr;
490     int extra_width  = h->emu_edge_width;
491     int extra_height = h->emu_edge_height;
492     int emu = 0;
493     const int full_mx    = mx >> 2;
494     const int full_my    = my >> 2;
495     const int pic_width  = 16 * s->mb_width;
496     const int pic_height = 16 * s->mb_height >> MB_FIELD;
497     int ysh;
498
499     if (mx & 7)
500         extra_width -= 3;
501     if (my & 7)
502         extra_height -= 3;
503
504     if (full_mx                <          0 - extra_width  ||
505         full_my                <          0 - extra_height ||
506         full_mx + 16 /*FIXME*/ > pic_width  + extra_width  ||
507         full_my + 16 /*FIXME*/ > pic_height + extra_height) {
508         s->dsp.emulated_edge_mc(s->edge_emu_buffer,
509                                 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
510                                 h->mb_linesize,
511                                 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
512                                 full_my - 2, pic_width, pic_height);
513         src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
514         emu   = 1;
515     }
516
517     qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
518     if (!square)
519         qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
520
521     if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
522         return;
523
524     if (chroma_idc == 3 /* yuv444 */) {
525         src_cb = pic->f.data[1] + offset;
526         if (emu) {
527             s->dsp.emulated_edge_mc(s->edge_emu_buffer,
528                                     src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
529                                     h->mb_linesize,
530                                     16 + 5, 16 + 5 /*FIXME*/,
531                                     full_mx - 2, full_my - 2,
532                                     pic_width, pic_height);
533             src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
534         }
535         qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
536         if (!square)
537             qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
538
539         src_cr = pic->f.data[2] + offset;
540         if (emu) {
541             s->dsp.emulated_edge_mc(s->edge_emu_buffer,
542                                     src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
543                                     h->mb_linesize,
544                                     16 + 5, 16 + 5 /*FIXME*/,
545                                     full_mx - 2, full_my - 2,
546                                     pic_width, pic_height);
547             src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
548         }
549         qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
550         if (!square)
551             qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
552         return;
553     }
554
555     ysh = 3 - (chroma_idc == 2 /* yuv422 */);
556     if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
557         // chroma offset when predicting from a field of opposite parity
558         my  += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
559         emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
560     }
561
562     src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
563              (my >> ysh) * h->mb_uvlinesize;
564     src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
565              (my >> ysh) * h->mb_uvlinesize;
566
567     if (emu) {
568         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
569                                 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
570                                 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
571         src_cb = s->edge_emu_buffer;
572     }
573     chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
574               height >> (chroma_idc == 1 /* yuv420 */),
575               mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
576
577     if (emu) {
578         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, 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_cr = s->edge_emu_buffer;
582     }
583     chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
584               mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
585 }
586
587 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
588                                          int height, int delta,
589                                          uint8_t *dest_y, uint8_t *dest_cb,
590                                          uint8_t *dest_cr,
591                                          int x_offset, int y_offset,
592                                          qpel_mc_func *qpix_put,
593                                          h264_chroma_mc_func chroma_put,
594                                          qpel_mc_func *qpix_avg,
595                                          h264_chroma_mc_func chroma_avg,
596                                          int list0, int list1,
597                                          int pixel_shift, int chroma_idc)
598 {
599     MpegEncContext *const s       = &h->s;
600     qpel_mc_func *qpix_op         = qpix_put;
601     h264_chroma_mc_func chroma_op = chroma_put;
602
603     dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
604     if (chroma_idc == 3 /* yuv444 */) {
605         dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
606         dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
607     } else if (chroma_idc == 2 /* yuv422 */) {
608         dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
609         dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
610     } else { /* yuv420 */
611         dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
612         dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
613     }
614     x_offset += 8 * s->mb_x;
615     y_offset += 8 * (s->mb_y >> MB_FIELD);
616
617     if (list0) {
618         Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
619         mc_dir_part(h, ref, n, square, height, delta, 0,
620                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
621                     qpix_op, chroma_op, pixel_shift, chroma_idc);
622
623         qpix_op   = qpix_avg;
624         chroma_op = chroma_avg;
625     }
626
627     if (list1) {
628         Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
629         mc_dir_part(h, ref, n, square, height, delta, 1,
630                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
631                     qpix_op, chroma_op, pixel_shift, chroma_idc);
632     }
633 }
634
635 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
636                                               int height, int delta,
637                                               uint8_t *dest_y, uint8_t *dest_cb,
638                                               uint8_t *dest_cr,
639                                               int x_offset, int y_offset,
640                                               qpel_mc_func *qpix_put,
641                                               h264_chroma_mc_func chroma_put,
642                                               h264_weight_func luma_weight_op,
643                                               h264_weight_func chroma_weight_op,
644                                               h264_biweight_func luma_weight_avg,
645                                               h264_biweight_func chroma_weight_avg,
646                                               int list0, int list1,
647                                               int pixel_shift, int chroma_idc)
648 {
649     MpegEncContext *const s = &h->s;
650     int chroma_height;
651
652     dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
653     if (chroma_idc == 3 /* yuv444 */) {
654         chroma_height     = height;
655         chroma_weight_avg = luma_weight_avg;
656         chroma_weight_op  = luma_weight_op;
657         dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
658         dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
659     } else if (chroma_idc == 2 /* yuv422 */) {
660         chroma_height = height;
661         dest_cb      += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
662         dest_cr      += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
663     } else { /* yuv420 */
664         chroma_height = height >> 1;
665         dest_cb      += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
666         dest_cr      += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
667     }
668     x_offset += 8 * s->mb_x;
669     y_offset += 8 * (s->mb_y >> MB_FIELD);
670
671     if (list0 && list1) {
672         /* don't optimize for luma-only case, since B-frames usually
673          * use implicit weights => chroma too. */
674         uint8_t *tmp_cb = s->obmc_scratchpad;
675         uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
676         uint8_t *tmp_y  = s->obmc_scratchpad + 16 * h->mb_uvlinesize;
677         int refn0       = h->ref_cache[0][scan8[n]];
678         int refn1       = h->ref_cache[1][scan8[n]];
679
680         mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
681                     dest_y, dest_cb, dest_cr,
682                     x_offset, y_offset, qpix_put, chroma_put,
683                     pixel_shift, chroma_idc);
684         mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
685                     tmp_y, tmp_cb, tmp_cr,
686                     x_offset, y_offset, qpix_put, chroma_put,
687                     pixel_shift, chroma_idc);
688
689         if (h->use_weight == 2) {
690             int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
691             int weight1 = 64 - weight0;
692             luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
693                             height, 5, weight0, weight1, 0);
694             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
695                               chroma_height, 5, weight0, weight1, 0);
696             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
697                               chroma_height, 5, weight0, weight1, 0);
698         } else {
699             luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
700                             h->luma_log2_weight_denom,
701                             h->luma_weight[refn0][0][0],
702                             h->luma_weight[refn1][1][0],
703                             h->luma_weight[refn0][0][1] +
704                             h->luma_weight[refn1][1][1]);
705             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
706                               h->chroma_log2_weight_denom,
707                               h->chroma_weight[refn0][0][0][0],
708                               h->chroma_weight[refn1][1][0][0],
709                               h->chroma_weight[refn0][0][0][1] +
710                               h->chroma_weight[refn1][1][0][1]);
711             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
712                               h->chroma_log2_weight_denom,
713                               h->chroma_weight[refn0][0][1][0],
714                               h->chroma_weight[refn1][1][1][0],
715                               h->chroma_weight[refn0][0][1][1] +
716                               h->chroma_weight[refn1][1][1][1]);
717         }
718     } else {
719         int list     = list1 ? 1 : 0;
720         int refn     = h->ref_cache[list][scan8[n]];
721         Picture *ref = &h->ref_list[list][refn];
722         mc_dir_part(h, ref, n, square, height, delta, list,
723                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
724                     qpix_put, chroma_put, pixel_shift, chroma_idc);
725
726         luma_weight_op(dest_y, h->mb_linesize, height,
727                        h->luma_log2_weight_denom,
728                        h->luma_weight[refn][list][0],
729                        h->luma_weight[refn][list][1]);
730         if (h->use_weight_chroma) {
731             chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
732                              h->chroma_log2_weight_denom,
733                              h->chroma_weight[refn][list][0][0],
734                              h->chroma_weight[refn][list][0][1]);
735             chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
736                              h->chroma_log2_weight_denom,
737                              h->chroma_weight[refn][list][1][0],
738                              h->chroma_weight[refn][list][1][1]);
739         }
740     }
741 }
742
743 static av_always_inline void prefetch_motion(H264Context *h, int list,
744                                              int pixel_shift, int chroma_idc)
745 {
746     /* fetch pixels for estimated mv 4 macroblocks ahead
747      * optimized for 64byte cache lines */
748     MpegEncContext *const s = &h->s;
749     const int refn = h->ref_cache[list][scan8[0]];
750     if (refn >= 0) {
751         const int mx  = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
752         const int my  = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
753         uint8_t **src = h->ref_list[list][refn].f.data;
754         int off       = (mx << pixel_shift) +
755                         (my + (s->mb_x & 3) * 4) * h->mb_linesize +
756                         (64 << pixel_shift);
757         s->dsp.prefetch(src[0] + off, s->linesize, 4);
758         if (chroma_idc == 3 /* yuv444 */) {
759             s->dsp.prefetch(src[1] + off, s->linesize, 4);
760             s->dsp.prefetch(src[2] + off, s->linesize, 4);
761         } else {
762             off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
763             s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
764         }
765     }
766 }
767
768 static void free_tables(H264Context *h, int free_rbsp)
769 {
770     int i;
771     H264Context *hx;
772
773     av_freep(&h->intra4x4_pred_mode);
774     av_freep(&h->chroma_pred_mode_table);
775     av_freep(&h->cbp_table);
776     av_freep(&h->mvd_table[0]);
777     av_freep(&h->mvd_table[1]);
778     av_freep(&h->direct_table);
779     av_freep(&h->non_zero_count);
780     av_freep(&h->slice_table_base);
781     h->slice_table = NULL;
782     av_freep(&h->list_counts);
783
784     av_freep(&h->mb2b_xy);
785     av_freep(&h->mb2br_xy);
786
787     for (i = 0; i < MAX_THREADS; i++) {
788         hx = h->thread_context[i];
789         if (!hx)
790             continue;
791         av_freep(&hx->top_borders[1]);
792         av_freep(&hx->top_borders[0]);
793         av_freep(&hx->s.obmc_scratchpad);
794         if (free_rbsp) {
795             av_freep(&hx->rbsp_buffer[1]);
796             av_freep(&hx->rbsp_buffer[0]);
797             hx->rbsp_buffer_size[0] = 0;
798             hx->rbsp_buffer_size[1] = 0;
799         }
800         if (i)
801             av_freep(&h->thread_context[i]);
802     }
803 }
804
805 static void init_dequant8_coeff_table(H264Context *h)
806 {
807     int i, j, q, x;
808     const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
809
810     for (i = 0; i < 6; i++) {
811         h->dequant8_coeff[i] = h->dequant8_buffer[i];
812         for (j = 0; j < i; j++)
813             if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
814                         64 * sizeof(uint8_t))) {
815                 h->dequant8_coeff[i] = h->dequant8_buffer[j];
816                 break;
817             }
818         if (j < i)
819             continue;
820
821         for (q = 0; q < max_qp + 1; q++) {
822             int shift = div6[q];
823             int idx   = rem6[q];
824             for (x = 0; x < 64; x++)
825                 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
826                     ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
827                      h->pps.scaling_matrix8[i][x]) << shift;
828         }
829     }
830 }
831
832 static void init_dequant4_coeff_table(H264Context *h)
833 {
834     int i, j, q, x;
835     const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
836     for (i = 0; i < 6; i++) {
837         h->dequant4_coeff[i] = h->dequant4_buffer[i];
838         for (j = 0; j < i; j++)
839             if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
840                         16 * sizeof(uint8_t))) {
841                 h->dequant4_coeff[i] = h->dequant4_buffer[j];
842                 break;
843             }
844         if (j < i)
845             continue;
846
847         for (q = 0; q < max_qp + 1; q++) {
848             int shift = div6[q] + 2;
849             int idx   = rem6[q];
850             for (x = 0; x < 16; x++)
851                 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
852                     ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
853                      h->pps.scaling_matrix4[i][x]) << shift;
854         }
855     }
856 }
857
858 static void init_dequant_tables(H264Context *h)
859 {
860     int i, x;
861     init_dequant4_coeff_table(h);
862     if (h->pps.transform_8x8_mode)
863         init_dequant8_coeff_table(h);
864     if (h->sps.transform_bypass) {
865         for (i = 0; i < 6; i++)
866             for (x = 0; x < 16; x++)
867                 h->dequant4_coeff[i][0][x] = 1 << 6;
868         if (h->pps.transform_8x8_mode)
869             for (i = 0; i < 6; i++)
870                 for (x = 0; x < 64; x++)
871                     h->dequant8_coeff[i][0][x] = 1 << 6;
872     }
873 }
874
875 int ff_h264_alloc_tables(H264Context *h)
876 {
877     MpegEncContext *const s = &h->s;
878     const int big_mb_num    = s->mb_stride * (s->mb_height + 1);
879     const int row_mb_num    = 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
880     int x, y;
881
882     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
883                       row_mb_num * 8 * sizeof(uint8_t), fail)
884     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
885                       big_mb_num * 48 * sizeof(uint8_t), fail)
886     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
887                       (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
888     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
889                       big_mb_num * sizeof(uint16_t), fail)
890     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
891                       big_mb_num * sizeof(uint8_t), fail)
892     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
893                       16 * row_mb_num * sizeof(uint8_t), fail);
894     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
895                       16 * row_mb_num * sizeof(uint8_t), fail);
896     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
897                       4 * big_mb_num * sizeof(uint8_t), fail);
898     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
899                       big_mb_num * sizeof(uint8_t), fail)
900
901     memset(h->slice_table_base, -1,
902            (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
903     h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
904
905     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
906                       big_mb_num * sizeof(uint32_t), fail);
907     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
908                       big_mb_num * sizeof(uint32_t), fail);
909     for (y = 0; y < s->mb_height; y++)
910         for (x = 0; x < s->mb_width; x++) {
911             const int mb_xy = x + y * s->mb_stride;
912             const int b_xy  = 4 * x + 4 * y * h->b_stride;
913
914             h->mb2b_xy[mb_xy]  = b_xy;
915             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
916         }
917
918     s->obmc_scratchpad = NULL;
919
920     if (!h->dequant4_coeff[0])
921         init_dequant_tables(h);
922
923     return 0;
924
925 fail:
926     free_tables(h, 1);
927     return -1;
928 }
929
930 /**
931  * Mimic alloc_tables(), but for every context thread.
932  */
933 static void clone_tables(H264Context *dst, H264Context *src, int i)
934 {
935     MpegEncContext *const s     = &src->s;
936     dst->intra4x4_pred_mode     = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
937     dst->non_zero_count         = src->non_zero_count;
938     dst->slice_table            = src->slice_table;
939     dst->cbp_table              = src->cbp_table;
940     dst->mb2b_xy                = src->mb2b_xy;
941     dst->mb2br_xy               = src->mb2br_xy;
942     dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
943     dst->mvd_table[0]           = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
944     dst->mvd_table[1]           = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
945     dst->direct_table           = src->direct_table;
946     dst->list_counts            = src->list_counts;
947     dst->s.obmc_scratchpad      = NULL;
948     ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
949                       src->sps.chroma_format_idc);
950 }
951
952 /**
953  * Init context
954  * Allocate buffers which are not shared amongst multiple threads.
955  */
956 static int context_init(H264Context *h)
957 {
958     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
959                       h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
960     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
961                       h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
962
963     h->ref_cache[0][scan8[5]  + 1] =
964     h->ref_cache[0][scan8[7]  + 1] =
965     h->ref_cache[0][scan8[13] + 1] =
966     h->ref_cache[1][scan8[5]  + 1] =
967     h->ref_cache[1][scan8[7]  + 1] =
968     h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
969
970     return 0;
971
972 fail:
973     return -1; // free_tables will clean up for us
974 }
975
976 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
977
978 static av_cold void common_init(H264Context *h)
979 {
980     MpegEncContext *const s = &h->s;
981
982     s->width    = s->avctx->width;
983     s->height   = s->avctx->height;
984     s->codec_id = s->avctx->codec->id;
985
986     s->avctx->bits_per_raw_sample = 8;
987     h->cur_chroma_format_idc = 1;
988
989     ff_h264dsp_init(&h->h264dsp,
990                     s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
991     ff_h264_pred_init(&h->hpc, s->codec_id,
992                       s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
993
994     h->dequant_coeff_pps = -1;
995     s->unrestricted_mv   = 1;
996
997     s->dsp.dct_bits = 16;
998     /* needed so that IDCT permutation is known early */
999     ff_dsputil_init(&s->dsp, s->avctx);
1000
1001     memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1002     memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1003 }
1004
1005 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1006 {
1007     AVCodecContext *avctx = h->s.avctx;
1008
1009     if (!buf || size <= 0)
1010         return -1;
1011
1012     if (buf[0] == 1) {
1013         int i, cnt, nalsize;
1014         const unsigned char *p = buf;
1015
1016         h->is_avc = 1;
1017
1018         if (size < 7) {
1019             av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1020             return -1;
1021         }
1022         /* sps and pps in the avcC always have length coded with 2 bytes,
1023          * so put a fake nal_length_size = 2 while parsing them */
1024         h->nal_length_size = 2;
1025         // Decode sps from avcC
1026         cnt = *(p + 5) & 0x1f; // Number of sps
1027         p  += 6;
1028         for (i = 0; i < cnt; i++) {
1029             nalsize = AV_RB16(p) + 2;
1030             if(nalsize > size - (p-buf))
1031                 return -1;
1032             if (decode_nal_units(h, p, nalsize) < 0) {
1033                 av_log(avctx, AV_LOG_ERROR,
1034                        "Decoding sps %d from avcC failed\n", i);
1035                 return -1;
1036             }
1037             p += nalsize;
1038         }
1039         // Decode pps from avcC
1040         cnt = *(p++); // Number of pps
1041         for (i = 0; i < cnt; i++) {
1042             nalsize = AV_RB16(p) + 2;
1043             if(nalsize > size - (p-buf))
1044                 return -1;
1045             if (decode_nal_units(h, p, nalsize) < 0) {
1046                 av_log(avctx, AV_LOG_ERROR,
1047                        "Decoding pps %d from avcC failed\n", i);
1048                 return -1;
1049             }
1050             p += nalsize;
1051         }
1052         // Now store right nal length size, that will be used to parse all other nals
1053         h->nal_length_size = (buf[4] & 0x03) + 1;
1054     } else {
1055         h->is_avc = 0;
1056         if (decode_nal_units(h, buf, size) < 0)
1057             return -1;
1058     }
1059     return size;
1060 }
1061
1062 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1063 {
1064     H264Context *h = avctx->priv_data;
1065     MpegEncContext *const s = &h->s;
1066     int i;
1067
1068     ff_MPV_decode_defaults(s);
1069
1070     s->avctx = avctx;
1071     common_init(h);
1072
1073     s->out_format      = FMT_H264;
1074     s->workaround_bugs = avctx->workaround_bugs;
1075
1076     /* set defaults */
1077     // s->decode_mb = ff_h263_decode_mb;
1078     s->quarter_sample = 1;
1079     if (!avctx->has_b_frames)
1080         s->low_delay = 1;
1081
1082     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1083
1084     ff_h264_decode_init_vlc();
1085
1086     h->pixel_shift = 0;
1087     h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1088
1089     h->thread_context[0] = h;
1090     h->outputed_poc      = h->next_outputed_poc = INT_MIN;
1091     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1092         h->last_pocs[i] = INT_MIN;
1093     h->prev_poc_msb = 1 << 16;
1094     h->prev_frame_num = -1;
1095     h->x264_build   = -1;
1096     ff_h264_reset_sei(h);
1097     if (avctx->codec_id == AV_CODEC_ID_H264) {
1098         if (avctx->ticks_per_frame == 1)
1099             s->avctx->time_base.den *= 2;
1100         avctx->ticks_per_frame = 2;
1101     }
1102
1103     if (avctx->extradata_size > 0 && avctx->extradata &&
1104         ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
1105         ff_h264_free_context(h);
1106         return -1;
1107     }
1108
1109     if (h->sps.bitstream_restriction_flag &&
1110         s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1111         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1112         s->low_delay           = 0;
1113     }
1114
1115     ff_init_cabac_states();
1116
1117     return 0;
1118 }
1119
1120 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1121
1122 static void copy_picture_range(Picture **to, Picture **from, int count,
1123                                MpegEncContext *new_base,
1124                                MpegEncContext *old_base)
1125 {
1126     int i;
1127
1128     for (i = 0; i < count; i++) {
1129         assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1130                 IN_RANGE(from[i], old_base->picture,
1131                          sizeof(Picture) * old_base->picture_count) ||
1132                 !from[i]));
1133         to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1134     }
1135 }
1136
1137 static void copy_parameter_set(void **to, void **from, int count, int size)
1138 {
1139     int i;
1140
1141     for (i = 0; i < count; i++) {
1142         if (to[i] && !from[i])
1143             av_freep(&to[i]);
1144         else if (from[i] && !to[i])
1145             to[i] = av_malloc(size);
1146
1147         if (from[i])
1148             memcpy(to[i], from[i], size);
1149     }
1150 }
1151
1152 static int decode_init_thread_copy(AVCodecContext *avctx)
1153 {
1154     H264Context *h = avctx->priv_data;
1155
1156     if (!avctx->internal->is_copy)
1157         return 0;
1158     memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1159     memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1160
1161     return 0;
1162 }
1163
1164 #define copy_fields(to, from, start_field, end_field)                   \
1165     memcpy(&to->start_field, &from->start_field,                        \
1166            (char *)&to->end_field - (char *)&to->start_field)
1167
1168 static int decode_update_thread_context(AVCodecContext *dst,
1169                                         const AVCodecContext *src)
1170 {
1171     H264Context *h = dst->priv_data, *h1 = src->priv_data;
1172     MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1173     int inited = s->context_initialized, err;
1174     int i;
1175
1176     if (dst == src)
1177         return 0;
1178
1179     err = ff_mpeg_update_thread_context(dst, src);
1180     if (err)
1181         return err;
1182
1183     // FIXME handle width/height changing
1184     if (!inited) {
1185         for (i = 0; i < MAX_SPS_COUNT; i++)
1186             av_freep(h->sps_buffers + i);
1187
1188         for (i = 0; i < MAX_PPS_COUNT; i++)
1189             av_freep(h->pps_buffers + i);
1190
1191         // copy all fields after MpegEnc
1192         memcpy(&h->s + 1, &h1->s + 1,
1193                sizeof(H264Context) - sizeof(MpegEncContext));
1194         memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1195         memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1196
1197         if (s1->context_initialized) {
1198         if (ff_h264_alloc_tables(h) < 0) {
1199             av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1200             return AVERROR(ENOMEM);
1201         }
1202         context_init(h);
1203
1204         /* frame_start may not be called for the next thread (if it's decoding
1205          * a bottom field) so this has to be allocated here */
1206         h->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1207         }
1208
1209         for (i = 0; i < 2; i++) {
1210             h->rbsp_buffer[i]      = NULL;
1211             h->rbsp_buffer_size[i] = 0;
1212         }
1213
1214         h->thread_context[0] = h;
1215
1216         s->dsp.clear_blocks(h->mb);
1217         s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1218     }
1219
1220     // extradata/NAL handling
1221     h->is_avc = h1->is_avc;
1222
1223     // SPS/PPS
1224     copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1225                        MAX_SPS_COUNT, sizeof(SPS));
1226     h->sps = h1->sps;
1227     copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1228                        MAX_PPS_COUNT, sizeof(PPS));
1229     h->pps = h1->pps;
1230
1231     // Dequantization matrices
1232     // FIXME these are big - can they be only copied when PPS changes?
1233     copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1234
1235     for (i = 0; i < 6; i++)
1236         h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1237                                (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1238
1239     for (i = 0; i < 6; i++)
1240         h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1241                                (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1242
1243     h->dequant_coeff_pps = h1->dequant_coeff_pps;
1244
1245     // POC timing
1246     copy_fields(h, h1, poc_lsb, redundant_pic_count);
1247
1248     // reference lists
1249     copy_fields(h, h1, ref_count, list_count);
1250     copy_fields(h, h1, ref_list, intra_gb);
1251     copy_fields(h, h1, short_ref, cabac_init_idc);
1252
1253     copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1254     copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1255     copy_picture_range(h->delayed_pic, h1->delayed_pic,
1256                        MAX_DELAYED_PIC_COUNT + 2, s, s1);
1257
1258     h->last_slice_type = h1->last_slice_type;
1259     h->sync            = h1->sync;
1260
1261     if (!s->current_picture_ptr)
1262         return 0;
1263
1264     if (!s->dropable) {
1265         err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1266         h->prev_poc_msb = h->poc_msb;
1267         h->prev_poc_lsb = h->poc_lsb;
1268     }
1269     h->prev_frame_num_offset = h->frame_num_offset;
1270     h->prev_frame_num        = h->frame_num;
1271     h->outputed_poc          = h->next_outputed_poc;
1272
1273     return err;
1274 }
1275
1276 int ff_h264_frame_start(H264Context *h)
1277 {
1278     MpegEncContext *const s = &h->s;
1279     int i;
1280     const int pixel_shift = h->pixel_shift;
1281
1282     if (ff_MPV_frame_start(s, s->avctx) < 0)
1283         return -1;
1284     ff_er_frame_start(s);
1285     /*
1286      * ff_MPV_frame_start uses pict_type to derive key_frame.
1287      * This is incorrect for H.264; IDR markings must be used.
1288      * Zero here; IDR markings per slice in frame or fields are ORed in later.
1289      * See decode_nal_units().
1290      */
1291     s->current_picture_ptr->f.key_frame = 0;
1292     s->current_picture_ptr->sync        = 0;
1293     s->current_picture_ptr->mmco_reset  = 0;
1294
1295     assert(s->linesize && s->uvlinesize);
1296
1297     for (i = 0; i < 16; i++) {
1298         h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1299         h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1300     }
1301     for (i = 0; i < 16; i++) {
1302         h->block_offset[16 + i]      =
1303         h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1304         h->block_offset[48 + 16 + i] =
1305         h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1306     }
1307
1308     /* can't be in alloc_tables because linesize isn't known there.
1309      * FIXME: redo bipred weight to not require extra buffer? */
1310     for (i = 0; i < s->slice_context_count; i++)
1311         if (h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1312             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1313
1314     /* Some macroblocks can be accessed before they're available in case
1315      * of lost slices, MBAFF or threading. */
1316     memset(h->slice_table, -1,
1317            (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1318
1319     // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1320     //             s->current_picture.f.reference /* || h->contains_intra */ || 1;
1321
1322     /* We mark the current picture as non-reference after allocating it, so
1323      * that if we break out due to an error it can be released automatically
1324      * in the next ff_MPV_frame_start().
1325      * SVQ3 as well as most other codecs have only last/next/current and thus
1326      * get released even with set reference, besides SVQ3 and others do not
1327      * mark frames as reference later "naturally". */
1328     if (s->codec_id != AV_CODEC_ID_SVQ3)
1329         s->current_picture_ptr->f.reference = 0;
1330
1331     s->current_picture_ptr->field_poc[0]     =
1332         s->current_picture_ptr->field_poc[1] = INT_MAX;
1333
1334     h->next_output_pic = NULL;
1335
1336     assert(s->current_picture_ptr->long_ref == 0);
1337
1338     return 0;
1339 }
1340
1341 /**
1342  * Run setup operations that must be run after slice header decoding.
1343  * This includes finding the next displayed frame.
1344  *
1345  * @param h h264 master context
1346  * @param setup_finished enough NALs have been read that we can call
1347  * ff_thread_finish_setup()
1348  */
1349 static void decode_postinit(H264Context *h, int setup_finished)
1350 {
1351     MpegEncContext *const s = &h->s;
1352     Picture *out = s->current_picture_ptr;
1353     Picture *cur = s->current_picture_ptr;
1354     int i, pics, out_of_order, out_idx;
1355
1356     s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1357     s->current_picture_ptr->f.pict_type   = s->pict_type;
1358
1359     if (h->next_output_pic)
1360         return;
1361
1362     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1363         /* FIXME: if we have two PAFF fields in one packet, we can't start
1364          * the next thread here. If we have one field per packet, we can.
1365          * The check in decode_nal_units() is not good enough to find this
1366          * yet, so we assume the worst for now. */
1367         // if (setup_finished)
1368         //    ff_thread_finish_setup(s->avctx);
1369         return;
1370     }
1371
1372     cur->f.interlaced_frame = 0;
1373     cur->f.repeat_pict      = 0;
1374
1375     /* Signal interlacing information externally. */
1376     /* Prioritize picture timing SEI information over used
1377      * decoding process if it exists. */
1378
1379     if (h->sps.pic_struct_present_flag) {
1380         switch (h->sei_pic_struct) {
1381         case SEI_PIC_STRUCT_FRAME:
1382             break;
1383         case SEI_PIC_STRUCT_TOP_FIELD:
1384         case SEI_PIC_STRUCT_BOTTOM_FIELD:
1385             cur->f.interlaced_frame = 1;
1386             break;
1387         case SEI_PIC_STRUCT_TOP_BOTTOM:
1388         case SEI_PIC_STRUCT_BOTTOM_TOP:
1389             if (FIELD_OR_MBAFF_PICTURE)
1390                 cur->f.interlaced_frame = 1;
1391             else
1392                 // try to flag soft telecine progressive
1393                 cur->f.interlaced_frame = h->prev_interlaced_frame;
1394             break;
1395         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1396         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1397             /* Signal the possibility of telecined film externally
1398              * (pic_struct 5,6). From these hints, let the applications
1399              * decide if they apply deinterlacing. */
1400             cur->f.repeat_pict = 1;
1401             break;
1402         case SEI_PIC_STRUCT_FRAME_DOUBLING:
1403             // Force progressive here, doubling interlaced frame is a bad idea.
1404             cur->f.repeat_pict = 2;
1405             break;
1406         case SEI_PIC_STRUCT_FRAME_TRIPLING:
1407             cur->f.repeat_pict = 4;
1408             break;
1409         }
1410
1411         if ((h->sei_ct_type & 3) &&
1412             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1413             cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1414     } else {
1415         /* Derive interlacing flag from used decoding process. */
1416         cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1417     }
1418     h->prev_interlaced_frame = cur->f.interlaced_frame;
1419
1420     if (cur->field_poc[0] != cur->field_poc[1]) {
1421         /* Derive top_field_first from field pocs. */
1422         cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1423     } else {
1424         if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1425             /* Use picture timing SEI information. Even if it is a
1426              * information of a past frame, better than nothing. */
1427             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1428                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1429                 cur->f.top_field_first = 1;
1430             else
1431                 cur->f.top_field_first = 0;
1432         } else {
1433             /* Most likely progressive */
1434             cur->f.top_field_first = 0;
1435         }
1436     }
1437
1438     cur->mmco_reset = h->mmco_reset;
1439     h->mmco_reset = 0;
1440     // FIXME do something with unavailable reference frames
1441
1442     /* Sort B-frames into display order */
1443
1444     if (h->sps.bitstream_restriction_flag &&
1445         s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1446         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1447         s->low_delay           = 0;
1448     }
1449
1450     if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1451         !h->sps.bitstream_restriction_flag) {
1452         s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1453         s->low_delay           = 0;
1454     }
1455
1456     for (i = 0; 1; i++) {
1457         if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1458             if(i)
1459                 h->last_pocs[i-1] = cur->poc;
1460             break;
1461         } else if(i) {
1462             h->last_pocs[i-1]= h->last_pocs[i];
1463         }
1464     }
1465     out_of_order = MAX_DELAYED_PIC_COUNT - i;
1466     if(   cur->f.pict_type == AV_PICTURE_TYPE_B
1467        || (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))
1468         out_of_order = FFMAX(out_of_order, 1);
1469     if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1470         av_log(s->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
1471         s->avctx->has_b_frames = out_of_order;
1472         s->low_delay = 0;
1473     }
1474
1475     pics = 0;
1476     while (h->delayed_pic[pics])
1477         pics++;
1478
1479     av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1480
1481     h->delayed_pic[pics++] = cur;
1482     if (cur->f.reference == 0)
1483         cur->f.reference = DELAYED_PIC_REF;
1484
1485     out = h->delayed_pic[0];
1486     out_idx = 0;
1487     for (i = 1; h->delayed_pic[i] &&
1488                 !h->delayed_pic[i]->f.key_frame &&
1489                 !h->delayed_pic[i]->mmco_reset;
1490          i++)
1491         if (h->delayed_pic[i]->poc < out->poc) {
1492             out     = h->delayed_pic[i];
1493             out_idx = i;
1494         }
1495     if (s->avctx->has_b_frames == 0 &&
1496         (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1497         h->next_outputed_poc = INT_MIN;
1498     out_of_order = out->poc < h->next_outputed_poc;
1499
1500     if (out_of_order || pics > s->avctx->has_b_frames) {
1501         out->f.reference &= ~DELAYED_PIC_REF;
1502         // for frame threading, the owner must be the second field's thread or
1503         // else the first thread can release the picture and reuse it unsafely
1504         out->owner2       = s;
1505         for (i = out_idx; h->delayed_pic[i]; i++)
1506             h->delayed_pic[i] = h->delayed_pic[i + 1];
1507     }
1508     if (!out_of_order && pics > s->avctx->has_b_frames) {
1509         h->next_output_pic = out;
1510         if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1511             h->next_outputed_poc = INT_MIN;
1512         } else
1513             h->next_outputed_poc = out->poc;
1514     } else {
1515         av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1516     }
1517
1518     if (h->next_output_pic && h->next_output_pic->sync) {
1519         h->sync |= 2;
1520     }
1521
1522     if (setup_finished)
1523         ff_thread_finish_setup(s->avctx);
1524 }
1525
1526 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1527                                               uint8_t *src_cb, uint8_t *src_cr,
1528                                               int linesize, int uvlinesize,
1529                                               int simple)
1530 {
1531     MpegEncContext *const s = &h->s;
1532     uint8_t *top_border;
1533     int top_idx = 1;
1534     const int pixel_shift = h->pixel_shift;
1535     int chroma444 = CHROMA444;
1536     int chroma422 = CHROMA422;
1537
1538     src_y  -= linesize;
1539     src_cb -= uvlinesize;
1540     src_cr -= uvlinesize;
1541
1542     if (!simple && FRAME_MBAFF) {
1543         if (s->mb_y & 1) {
1544             if (!MB_MBAFF) {
1545                 top_border = h->top_borders[0][s->mb_x];
1546                 AV_COPY128(top_border, src_y + 15 * linesize);
1547                 if (pixel_shift)
1548                     AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1549                 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1550                     if (chroma444) {
1551                         if (pixel_shift) {
1552                             AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1553                             AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1554                             AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1555                             AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1556                         } else {
1557                             AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1558                             AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1559                         }
1560                     } else if (chroma422) {
1561                         if (pixel_shift) {
1562                             AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1563                             AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1564                         } else {
1565                             AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1566                             AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1567                         }
1568                     } else {
1569                         if (pixel_shift) {
1570                             AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1571                             AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1572                         } else {
1573                             AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1574                             AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1575                         }
1576                     }
1577                 }
1578             }
1579         } else if (MB_MBAFF) {
1580             top_idx = 0;
1581         } else
1582             return;
1583     }
1584
1585     top_border = h->top_borders[top_idx][s->mb_x];
1586     /* There are two lines saved, the line above the top macroblock
1587      * of a pair, and the line above the bottom macroblock. */
1588     AV_COPY128(top_border, src_y + 16 * linesize);
1589     if (pixel_shift)
1590         AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1591
1592     if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1593         if (chroma444) {
1594             if (pixel_shift) {
1595                 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1596                 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1597                 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1598                 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1599             } else {
1600                 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1601                 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1602             }
1603         } else if (chroma422) {
1604             if (pixel_shift) {
1605                 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1606                 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1607             } else {
1608                 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1609                 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1610             }
1611         } else {
1612             if (pixel_shift) {
1613                 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1614                 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1615             } else {
1616                 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1617                 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1618             }
1619         }
1620     }
1621 }
1622
1623 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1624                                             uint8_t *src_cb, uint8_t *src_cr,
1625                                             int linesize, int uvlinesize,
1626                                             int xchg, int chroma444,
1627                                             int simple, int pixel_shift)
1628 {
1629     MpegEncContext *const s = &h->s;
1630     int deblock_topleft;
1631     int deblock_top;
1632     int top_idx = 1;
1633     uint8_t *top_border_m1;
1634     uint8_t *top_border;
1635
1636     if (!simple && FRAME_MBAFF) {
1637         if (s->mb_y & 1) {
1638             if (!MB_MBAFF)
1639                 return;
1640         } else {
1641             top_idx = MB_MBAFF ? 0 : 1;
1642         }
1643     }
1644
1645     if (h->deblocking_filter == 2) {
1646         deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1647         deblock_top     = h->top_type;
1648     } else {
1649         deblock_topleft = (s->mb_x > 0);
1650         deblock_top     = (s->mb_y > !!MB_FIELD);
1651     }
1652
1653     src_y  -= linesize   + 1 + pixel_shift;
1654     src_cb -= uvlinesize + 1 + pixel_shift;
1655     src_cr -= uvlinesize + 1 + pixel_shift;
1656
1657     top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1658     top_border    = h->top_borders[top_idx][s->mb_x];
1659
1660 #define XCHG(a, b, xchg)                        \
1661     if (pixel_shift) {                          \
1662         if (xchg) {                             \
1663             AV_SWAP64(b + 0, a + 0);            \
1664             AV_SWAP64(b + 8, a + 8);            \
1665         } else {                                \
1666             AV_COPY128(b, a);                   \
1667         }                                       \
1668     } else if (xchg)                            \
1669         AV_SWAP64(b, a);                        \
1670     else                                        \
1671         AV_COPY64(b, a);
1672
1673     if (deblock_top) {
1674         if (deblock_topleft) {
1675             XCHG(top_border_m1 + (8 << pixel_shift),
1676                  src_y - (7 << pixel_shift), 1);
1677         }
1678         XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1679         XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1680         if (s->mb_x + 1 < s->mb_width) {
1681             XCHG(h->top_borders[top_idx][s->mb_x + 1],
1682                  src_y + (17 << pixel_shift), 1);
1683         }
1684     }
1685     if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1686         if (chroma444) {
1687             if (deblock_topleft) {
1688                 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1689                 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1690             }
1691             XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1692             XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1693             XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1694             XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1695             if (s->mb_x + 1 < s->mb_width) {
1696                 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1697                 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1698             }
1699         } else {
1700             if (deblock_top) {
1701                 if (deblock_topleft) {
1702                     XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1703                     XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1704                 }
1705                 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1706                 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1707             }
1708         }
1709     }
1710 }
1711
1712 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
1713                                         int index)
1714 {
1715     if (high_bit_depth) {
1716         return AV_RN32A(((int32_t *)mb) + index);
1717     } else
1718         return AV_RN16A(mb + index);
1719 }
1720
1721 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
1722                                          int index, int value)
1723 {
1724     if (high_bit_depth) {
1725         AV_WN32A(((int32_t *)mb) + index, value);
1726     } else
1727         AV_WN16A(mb + index, value);
1728 }
1729
1730 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1731                                                        int mb_type, int is_h264,
1732                                                        int simple,
1733                                                        int transform_bypass,
1734                                                        int pixel_shift,
1735                                                        int *block_offset,
1736                                                        int linesize,
1737                                                        uint8_t *dest_y, int p)
1738 {
1739     MpegEncContext *const s = &h->s;
1740     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1741     void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1742     int i;
1743     int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1744     block_offset += 16 * p;
1745     if (IS_INTRA4x4(mb_type)) {
1746         if (simple || !s->encoding) {
1747             if (IS_8x8DCT(mb_type)) {
1748                 if (transform_bypass) {
1749                     idct_dc_add  =
1750                     idct_add     = s->dsp.add_pixels8;
1751                 } else {
1752                     idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1753                     idct_add    = h->h264dsp.h264_idct8_add;
1754                 }
1755                 for (i = 0; i < 16; i += 4) {
1756                     uint8_t *const ptr = dest_y + block_offset[i];
1757                     const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
1758                     if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1759                         h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1760                     } else {
1761                         const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1762                         h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1763                                              (h->topright_samples_available << i) & 0x4000, linesize);
1764                         if (nnz) {
1765                             if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1766                                 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1767                             else
1768                                 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1769                         }
1770                     }
1771                 }
1772             } else {
1773                 if (transform_bypass) {
1774                     idct_dc_add  =
1775                         idct_add = s->dsp.add_pixels4;
1776                 } else {
1777                     idct_dc_add = h->h264dsp.h264_idct_dc_add;
1778                     idct_add    = h->h264dsp.h264_idct_add;
1779                 }
1780                 for (i = 0; i < 16; i++) {
1781                     uint8_t *const ptr = dest_y + block_offset[i];
1782                     const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
1783
1784                     if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1785                         h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1786                     } else {
1787                         uint8_t *topright;
1788                         int nnz, tr;
1789                         uint64_t tr_high;
1790                         if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1791                             const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1792                             av_assert2(s->mb_y || linesize <= block_offset[i]);
1793                             if (!topright_avail) {
1794                                 if (pixel_shift) {
1795                                     tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1796                                     topright = (uint8_t *)&tr_high;
1797                                 } else {
1798                                     tr       = ptr[3 - linesize] * 0x01010101u;
1799                                     topright = (uint8_t *)&tr;
1800                                 }
1801                             } else
1802                                 topright = ptr + (4 << pixel_shift) - linesize;
1803                         } else
1804                             topright = NULL;
1805
1806                         h->hpc.pred4x4[dir](ptr, topright, linesize);
1807                         nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1808                         if (nnz) {
1809                             if (is_h264) {
1810                                 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1811                                     idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1812                                 else
1813                                     idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1814                             } else if (CONFIG_SVQ3_DECODER)
1815                                 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1816                         }
1817                     }
1818                 }
1819             }
1820         }
1821     } else {
1822         h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1823         if (is_h264) {
1824             if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1825                 if (!transform_bypass)
1826                     h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1827                                                          h->mb_luma_dc[p],
1828                                                          h->dequant4_coeff[p][qscale][0]);
1829                 else {
1830                     static const uint8_t dc_mapping[16] = {
1831                          0 * 16,  1 * 16,  4 * 16,  5 * 16,
1832                          2 * 16,  3 * 16,  6 * 16,  7 * 16,
1833                          8 * 16,  9 * 16, 12 * 16, 13 * 16,
1834                         10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1835                     for (i = 0; i < 16; i++)
1836                         dctcoef_set(h->mb + (p * 256 << pixel_shift),
1837                                     pixel_shift, dc_mapping[i],
1838                                     dctcoef_get(h->mb_luma_dc[p],
1839                                                 pixel_shift, i));
1840                 }
1841             }
1842         } else if (CONFIG_SVQ3_DECODER)
1843             ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
1844                                            h->mb_luma_dc[p], qscale);
1845     }
1846 }
1847
1848 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
1849                                                     int is_h264, int simple,
1850                                                     int transform_bypass,
1851                                                     int pixel_shift,
1852                                                     int *block_offset,
1853                                                     int linesize,
1854                                                     uint8_t *dest_y, int p)
1855 {
1856     MpegEncContext *const s = &h->s;
1857     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1858     int i;
1859     block_offset += 16 * p;
1860     if (!IS_INTRA4x4(mb_type)) {
1861         if (is_h264) {
1862             if (IS_INTRA16x16(mb_type)) {
1863                 if (transform_bypass) {
1864                     if (h->sps.profile_idc == 244 &&
1865                         (h->intra16x16_pred_mode == VERT_PRED8x8 ||
1866                          h->intra16x16_pred_mode == HOR_PRED8x8)) {
1867                         h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
1868                                                                       h->mb + (p * 256 << pixel_shift),
1869                                                                       linesize);
1870                     } else {
1871                         for (i = 0; i < 16; i++)
1872                             if (h->non_zero_count_cache[scan8[i + p * 16]] ||
1873                                 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1874                                 s->dsp.add_pixels4(dest_y + block_offset[i],
1875                                                    h->mb + (i * 16 + p * 256 << pixel_shift),
1876                                                    linesize);
1877                     }
1878                 } else {
1879                     h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
1880                                                     h->mb + (p * 256 << pixel_shift),
1881                                                     linesize,
1882                                                     h->non_zero_count_cache + p * 5 * 8);
1883                 }
1884             } else if (h->cbp & 15) {
1885                 if (transform_bypass) {
1886                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1887                     idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
1888                                                   : s->dsp.add_pixels4;
1889                     for (i = 0; i < 16; i += di)
1890                         if (h->non_zero_count_cache[scan8[i + p * 16]])
1891                             idct_add(dest_y + block_offset[i],
1892                                      h->mb + (i * 16 + p * 256 << pixel_shift),
1893                                      linesize);
1894                 } else {
1895                     if (IS_8x8DCT(mb_type))
1896                         h->h264dsp.h264_idct8_add4(dest_y, block_offset,
1897                                                    h->mb + (p * 256 << pixel_shift),
1898                                                    linesize,
1899                                                    h->non_zero_count_cache + p * 5 * 8);
1900                     else
1901                         h->h264dsp.h264_idct_add16(dest_y, block_offset,
1902                                                    h->mb + (p * 256 << pixel_shift),
1903                                                    linesize,
1904                                                    h->non_zero_count_cache + p * 5 * 8);
1905                 }
1906             }
1907         } else if (CONFIG_SVQ3_DECODER) {
1908             for (i = 0; i < 16; i++)
1909                 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
1910                     // FIXME benchmark weird rule, & below
1911                     uint8_t *const ptr = dest_y + block_offset[i];
1912                     ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
1913                                        s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1914                 }
1915         }
1916     }
1917 }
1918
1919 #define BITS   8
1920 #define SIMPLE 1
1921 #include "h264_mb_template.c"
1922
1923 #undef  BITS
1924 #define BITS   16
1925 #include "h264_mb_template.c"
1926
1927 #undef  SIMPLE
1928 #define SIMPLE 0
1929 #include "h264_mb_template.c"
1930
1931 void ff_h264_hl_decode_mb(H264Context *h)
1932 {
1933     MpegEncContext *const s = &h->s;
1934     const int mb_xy   = h->mb_xy;
1935     const int mb_type = s->current_picture.f.mb_type[mb_xy];
1936     int is_complex    = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1937
1938     if (CHROMA444) {
1939         if (is_complex || h->pixel_shift)
1940             hl_decode_mb_444_complex(h);
1941         else
1942             hl_decode_mb_444_simple_8(h);
1943     } else if (is_complex) {
1944         hl_decode_mb_complex(h);
1945     } else if (h->pixel_shift) {
1946         hl_decode_mb_simple_16(h);
1947     } else
1948         hl_decode_mb_simple_8(h);
1949 }
1950
1951 static int pred_weight_table(H264Context *h)
1952 {
1953     MpegEncContext *const s = &h->s;
1954     int list, i;
1955     int luma_def, chroma_def;
1956
1957     h->use_weight             = 0;
1958     h->use_weight_chroma      = 0;
1959     h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
1960     if (h->sps.chroma_format_idc)
1961         h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
1962     luma_def   = 1 << h->luma_log2_weight_denom;
1963     chroma_def = 1 << h->chroma_log2_weight_denom;
1964
1965     for (list = 0; list < 2; list++) {
1966         h->luma_weight_flag[list]   = 0;
1967         h->chroma_weight_flag[list] = 0;
1968         for (i = 0; i < h->ref_count[list]; i++) {
1969             int luma_weight_flag, chroma_weight_flag;
1970
1971             luma_weight_flag = get_bits1(&s->gb);
1972             if (luma_weight_flag) {
1973                 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
1974                 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
1975                 if (h->luma_weight[i][list][0] != luma_def ||
1976                     h->luma_weight[i][list][1] != 0) {
1977                     h->use_weight             = 1;
1978                     h->luma_weight_flag[list] = 1;
1979                 }
1980             } else {
1981                 h->luma_weight[i][list][0] = luma_def;
1982                 h->luma_weight[i][list][1] = 0;
1983             }
1984
1985             if (h->sps.chroma_format_idc) {
1986                 chroma_weight_flag = get_bits1(&s->gb);
1987                 if (chroma_weight_flag) {
1988                     int j;
1989                     for (j = 0; j < 2; j++) {
1990                         h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
1991                         h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
1992                         if (h->chroma_weight[i][list][j][0] != chroma_def ||
1993                             h->chroma_weight[i][list][j][1] != 0) {
1994                             h->use_weight_chroma = 1;
1995                             h->chroma_weight_flag[list] = 1;
1996                         }
1997                     }
1998                 } else {
1999                     int j;
2000                     for (j = 0; j < 2; j++) {
2001                         h->chroma_weight[i][list][j][0] = chroma_def;
2002                         h->chroma_weight[i][list][j][1] = 0;
2003                     }
2004                 }
2005             }
2006         }
2007         if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2008             break;
2009     }
2010     h->use_weight = h->use_weight || h->use_weight_chroma;
2011     return 0;
2012 }
2013
2014 /**
2015  * Initialize implicit_weight table.
2016  * @param field  0/1 initialize the weight for interlaced MBAFF
2017  *                -1 initializes the rest
2018  */
2019 static void implicit_weight_table(H264Context *h, int field)
2020 {
2021     MpegEncContext *const s = &h->s;
2022     int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2023
2024     for (i = 0; i < 2; i++) {
2025         h->luma_weight_flag[i]   = 0;
2026         h->chroma_weight_flag[i] = 0;
2027     }
2028
2029     if (field < 0) {
2030         if (s->picture_structure == PICT_FRAME) {
2031             cur_poc = s->current_picture_ptr->poc;
2032         } else {
2033             cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2034         }
2035         if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2036             h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2037             h->use_weight = 0;
2038             h->use_weight_chroma = 0;
2039             return;
2040         }
2041         ref_start  = 0;
2042         ref_count0 = h->ref_count[0];
2043         ref_count1 = h->ref_count[1];
2044     } else {
2045         cur_poc    = s->current_picture_ptr->field_poc[field];
2046         ref_start  = 16;
2047         ref_count0 = 16 + 2 * h->ref_count[0];
2048         ref_count1 = 16 + 2 * h->ref_count[1];
2049     }
2050
2051     h->use_weight               = 2;
2052     h->use_weight_chroma        = 2;
2053     h->luma_log2_weight_denom   = 5;
2054     h->chroma_log2_weight_denom = 5;
2055
2056     for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2057         int poc0 = h->ref_list[0][ref0].poc;
2058         for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2059             int w = 32;
2060             if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2061                 int poc1 = h->ref_list[1][ref1].poc;
2062                 int td   = av_clip(poc1 - poc0, -128, 127);
2063                 if (td) {
2064                     int tb = av_clip(cur_poc - poc0, -128, 127);
2065                     int tx = (16384 + (FFABS(td) >> 1)) / td;
2066                     int dist_scale_factor = (tb * tx + 32) >> 8;
2067                     if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2068                         w = 64 - dist_scale_factor;
2069                 }
2070             }
2071             if (field < 0) {
2072                 h->implicit_weight[ref0][ref1][0] =
2073                 h->implicit_weight[ref0][ref1][1] = w;
2074             } else {
2075                 h->implicit_weight[ref0][ref1][field] = w;
2076             }
2077         }
2078     }
2079 }
2080
2081 /**
2082  * instantaneous decoder refresh.
2083  */
2084 static void idr(H264Context *h)
2085 {
2086     int i;
2087     ff_h264_remove_all_refs(h);
2088     h->prev_frame_num        = 0;
2089     h->prev_frame_num_offset = 0;
2090     h->prev_poc_msb          = 1<<16;
2091     h->prev_poc_lsb          = 0;
2092     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2093         h->last_pocs[i] = INT_MIN;
2094 }
2095
2096 /* forget old pics after a seek */
2097 static void flush_dpb(AVCodecContext *avctx)
2098 {
2099     H264Context *h = avctx->priv_data;
2100     int i;
2101     for (i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
2102         if (h->delayed_pic[i])
2103             h->delayed_pic[i]->f.reference = 0;
2104         h->delayed_pic[i] = NULL;
2105     }
2106     h->outputed_poc = h->next_outputed_poc = INT_MIN;
2107     h->prev_interlaced_frame = 1;
2108     idr(h);
2109     h->prev_frame_num = -1;
2110     if (h->s.current_picture_ptr)
2111         h->s.current_picture_ptr->f.reference = 0;
2112     h->s.first_field = 0;
2113     ff_h264_reset_sei(h);
2114     ff_mpeg_flush(avctx);
2115     h->recovery_frame= -1;
2116     h->sync= 0;
2117 }
2118
2119 static int init_poc(H264Context *h)
2120 {
2121     MpegEncContext *const s = &h->s;
2122     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2123     int field_poc[2];
2124     Picture *cur = s->current_picture_ptr;
2125
2126     h->frame_num_offset = h->prev_frame_num_offset;
2127     if (h->frame_num < h->prev_frame_num)
2128         h->frame_num_offset += max_frame_num;
2129
2130     if (h->sps.poc_type == 0) {
2131         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2132
2133         if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2134             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2135         else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2136             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2137         else
2138             h->poc_msb = h->prev_poc_msb;
2139         field_poc[0] =
2140         field_poc[1] = h->poc_msb + h->poc_lsb;
2141         if (s->picture_structure == PICT_FRAME)
2142             field_poc[1] += h->delta_poc_bottom;
2143     } else if (h->sps.poc_type == 1) {
2144         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2145         int i;
2146
2147         if (h->sps.poc_cycle_length != 0)
2148             abs_frame_num = h->frame_num_offset + h->frame_num;
2149         else
2150             abs_frame_num = 0;
2151
2152         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2153             abs_frame_num--;
2154
2155         expected_delta_per_poc_cycle = 0;
2156         for (i = 0; i < h->sps.poc_cycle_length; i++)
2157             // FIXME integrate during sps parse
2158             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2159
2160         if (abs_frame_num > 0) {
2161             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2162             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2163
2164             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2165             for (i = 0; i <= frame_num_in_poc_cycle; i++)
2166                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2167         } else
2168             expectedpoc = 0;
2169
2170         if (h->nal_ref_idc == 0)
2171             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2172
2173         field_poc[0] = expectedpoc + h->delta_poc[0];
2174         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2175
2176         if (s->picture_structure == PICT_FRAME)
2177             field_poc[1] += h->delta_poc[1];
2178     } else {
2179         int poc = 2 * (h->frame_num_offset + h->frame_num);
2180
2181         if (!h->nal_ref_idc)
2182             poc--;
2183
2184         field_poc[0] = poc;
2185         field_poc[1] = poc;
2186     }
2187
2188     if (s->picture_structure != PICT_BOTTOM_FIELD)
2189         s->current_picture_ptr->field_poc[0] = field_poc[0];
2190     if (s->picture_structure != PICT_TOP_FIELD)
2191         s->current_picture_ptr->field_poc[1] = field_poc[1];
2192     cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2193
2194     return 0;
2195 }
2196
2197 /**
2198  * initialize scan tables
2199  */
2200 static void init_scan_tables(H264Context *h)
2201 {
2202     int i;
2203     for (i = 0; i < 16; i++) {
2204 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2205         h->zigzag_scan[i] = T(zigzag_scan[i]);
2206         h->field_scan[i]  = T(field_scan[i]);
2207 #undef T
2208     }
2209     for (i = 0; i < 64; i++) {
2210 #define T(x) (x >> 3) | ((x & 7) << 3)
2211         h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
2212         h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2213         h->field_scan8x8[i]        = T(field_scan8x8[i]);
2214         h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
2215 #undef T
2216     }
2217     if (h->sps.transform_bypass) { // FIXME same ugly
2218         memcpy(h->zigzag_scan_q0          , zigzag_scan             , sizeof(h->zigzag_scan_q0         ));
2219         memcpy(h->zigzag_scan8x8_q0       , ff_zigzag_direct        , sizeof(h->zigzag_scan8x8_q0      ));
2220         memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc    , sizeof(h->zigzag_scan8x8_cavlc_q0));
2221         memcpy(h->field_scan_q0           , field_scan              , sizeof(h->field_scan_q0          ));
2222         memcpy(h->field_scan8x8_q0        , field_scan8x8           , sizeof(h->field_scan8x8_q0       ));
2223         memcpy(h->field_scan8x8_cavlc_q0  , field_scan8x8_cavlc     , sizeof(h->field_scan8x8_cavlc_q0 ));
2224     } else {
2225         memcpy(h->zigzag_scan_q0          , h->zigzag_scan          , sizeof(h->zigzag_scan_q0         ));
2226         memcpy(h->zigzag_scan8x8_q0       , h->zigzag_scan8x8       , sizeof(h->zigzag_scan8x8_q0      ));
2227         memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2228         memcpy(h->field_scan_q0           , h->field_scan           , sizeof(h->field_scan_q0          ));
2229         memcpy(h->field_scan8x8_q0        , h->field_scan8x8        , sizeof(h->field_scan8x8_q0       ));
2230         memcpy(h->field_scan8x8_cavlc_q0  , h->field_scan8x8_cavlc  , sizeof(h->field_scan8x8_cavlc_q0 ));
2231     }
2232 }
2233
2234 static int field_end(H264Context *h, int in_setup)
2235 {
2236     MpegEncContext *const s     = &h->s;
2237     AVCodecContext *const avctx = s->avctx;
2238     int err = 0;
2239     s->mb_y = 0;
2240
2241     if (!in_setup && !s->dropable)
2242         ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2243                                   s->picture_structure == PICT_BOTTOM_FIELD);
2244
2245     if (CONFIG_H264_VDPAU_DECODER &&
2246         s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2247         ff_vdpau_h264_set_reference_frames(s);
2248
2249     if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2250         if (!s->dropable) {
2251             err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2252             h->prev_poc_msb = h->poc_msb;
2253             h->prev_poc_lsb = h->poc_lsb;
2254         }
2255         h->prev_frame_num_offset = h->frame_num_offset;
2256         h->prev_frame_num        = h->frame_num;
2257         h->outputed_poc          = h->next_outputed_poc;
2258     }
2259
2260     if (avctx->hwaccel) {
2261         if (avctx->hwaccel->end_frame(avctx) < 0)
2262             av_log(avctx, AV_LOG_ERROR,
2263                    "hardware accelerator failed to decode picture\n");
2264     }
2265
2266     if (CONFIG_H264_VDPAU_DECODER &&
2267         s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2268         ff_vdpau_h264_picture_complete(s);
2269
2270     /*
2271      * FIXME: Error handling code does not seem to support interlaced
2272      * when slices span multiple rows
2273      * The ff_er_add_slice calls don't work right for bottom
2274      * fields; they cause massive erroneous error concealing
2275      * Error marking covers both fields (top and bottom).
2276      * This causes a mismatched s->error_count
2277      * and a bad error table. Further, the error count goes to
2278      * INT_MAX when called for bottom field, because mb_y is
2279      * past end by one (callers fault) and resync_mb_y != 0
2280      * causes problems for the first MB line, too.
2281      */
2282     if (!FIELD_PICTURE)
2283         ff_er_frame_end(s);
2284
2285     ff_MPV_frame_end(s);
2286
2287     h->current_slice = 0;
2288
2289     return err;
2290 }
2291
2292 /**
2293  * Replicate H264 "master" context to thread contexts.
2294  */
2295 static void clone_slice(H264Context *dst, H264Context *src)
2296 {
2297     memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2298     dst->s.current_picture_ptr = src->s.current_picture_ptr;
2299     dst->s.current_picture     = src->s.current_picture;
2300     dst->s.linesize            = src->s.linesize;
2301     dst->s.uvlinesize          = src->s.uvlinesize;
2302     dst->s.first_field         = src->s.first_field;
2303
2304     dst->prev_poc_msb          = src->prev_poc_msb;
2305     dst->prev_poc_lsb          = src->prev_poc_lsb;
2306     dst->prev_frame_num_offset = src->prev_frame_num_offset;
2307     dst->prev_frame_num        = src->prev_frame_num;
2308     dst->short_ref_count       = src->short_ref_count;
2309
2310     memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2311     memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2312     memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2313     memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2314
2315     memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2316     memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2317 }
2318
2319 /**
2320  * Compute profile from profile_idc and constraint_set?_flags.
2321  *
2322  * @param sps SPS
2323  *
2324  * @return profile as defined by FF_PROFILE_H264_*
2325  */
2326 int ff_h264_get_profile(SPS *sps)
2327 {
2328     int profile = sps->profile_idc;
2329
2330     switch (sps->profile_idc) {
2331     case FF_PROFILE_H264_BASELINE:
2332         // constraint_set1_flag set to 1
2333         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2334         break;
2335     case FF_PROFILE_H264_HIGH_10:
2336     case FF_PROFILE_H264_HIGH_422:
2337     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2338         // constraint_set3_flag set to 1
2339         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2340         break;
2341     }
2342
2343     return profile;
2344 }
2345
2346 /**
2347  * Decode a slice header.
2348  * This will also call ff_MPV_common_init() and frame_start() as needed.
2349  *
2350  * @param h h264context
2351  * @param h0 h264 master context (differs from 'h' when doing sliced based
2352  *           parallel decoding)
2353  *
2354  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2355  */
2356 static int decode_slice_header(H264Context *h, H264Context *h0)
2357 {
2358     MpegEncContext *const s  = &h->s;
2359     MpegEncContext *const s0 = &h0->s;
2360     unsigned int first_mb_in_slice;
2361     unsigned int pps_id;
2362     int num_ref_idx_active_override_flag;
2363     unsigned int slice_type, tmp, i, j;
2364     int default_ref_list_done = 0;
2365     int last_pic_structure, last_pic_dropable;
2366     int must_reinit;
2367
2368     /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2369     if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
2370         !h->nal_ref_idc && !h->pixel_shift) {
2371         s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
2372         s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
2373     } else {
2374         s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
2375         s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
2376     }
2377
2378     first_mb_in_slice = get_ue_golomb_long(&s->gb);
2379
2380     if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2381         if (h0->current_slice && FIELD_PICTURE) {
2382             field_end(h, 1);
2383         }
2384
2385         h0->current_slice = 0;
2386         if (!s0->first_field) {
2387             if (s->current_picture_ptr && !s->dropable &&
2388                 s->current_picture_ptr->owner2 == s) {
2389                 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2390                                           s->picture_structure == PICT_BOTTOM_FIELD);
2391             }
2392             s->current_picture_ptr = NULL;
2393         }
2394     }
2395
2396     slice_type = get_ue_golomb_31(&s->gb);
2397     if (slice_type > 9) {
2398         av_log(h->s.avctx, AV_LOG_ERROR,
2399                "slice type too large (%d) at %d %d\n",
2400                h->slice_type, s->mb_x, s->mb_y);
2401         return -1;
2402     }
2403     if (slice_type > 4) {
2404         slice_type -= 5;
2405         h->slice_type_fixed = 1;
2406     } else
2407         h->slice_type_fixed = 0;
2408
2409     slice_type = golomb_to_pict_type[slice_type];
2410     if (slice_type == AV_PICTURE_TYPE_I ||
2411         (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2412         default_ref_list_done = 1;
2413     }
2414     h->slice_type     = slice_type;
2415     h->slice_type_nos = slice_type & 3;
2416
2417     // to make a few old functions happy, it's wrong though
2418     s->pict_type = h->slice_type;
2419
2420     pps_id = get_ue_golomb(&s->gb);
2421     if (pps_id >= MAX_PPS_COUNT) {
2422         av_log(h->s.avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
2423         return -1;
2424     }
2425     if (!h0->pps_buffers[pps_id]) {
2426         av_log(h->s.avctx, AV_LOG_ERROR,
2427                "non-existing PPS %u referenced\n",
2428                pps_id);
2429         return -1;
2430     }
2431     h->pps = *h0->pps_buffers[pps_id];
2432
2433     if (!h0->sps_buffers[h->pps.sps_id]) {
2434         av_log(h->s.avctx, AV_LOG_ERROR,
2435                "non-existing SPS %u referenced\n",
2436                h->pps.sps_id);
2437         return -1;
2438     }
2439     h->sps = *h0->sps_buffers[h->pps.sps_id];
2440
2441     s->avctx->profile = ff_h264_get_profile(&h->sps);
2442     s->avctx->level   = h->sps.level_idc;
2443     s->avctx->refs    = h->sps.ref_frame_count;
2444
2445     must_reinit = (s->context_initialized &&
2446                     (   16*h->sps.mb_width != s->avctx->coded_width
2447                      || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != s->avctx->coded_height
2448                      || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
2449                      || h->cur_chroma_format_idc != h->sps.chroma_format_idc
2450                      || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio)));
2451
2452     if(must_reinit && (h != h0 || (s->avctx->active_thread_type & FF_THREAD_FRAME))) {
2453         av_log_missing_feature(s->avctx,
2454                                 "Width/height/bit depth/chroma idc changing with threads is", 0);
2455         return AVERROR_PATCHWELCOME;   // width / height changed during parallelized decoding
2456     }
2457
2458     s->mb_width  = h->sps.mb_width;
2459     s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2460
2461     h->b_stride = s->mb_width * 4;
2462
2463     s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2464
2465     s->width  = 16 * s->mb_width;
2466     s->height = 16 * s->mb_height;
2467
2468     if(must_reinit) {
2469         free_tables(h, 0);
2470         flush_dpb(s->avctx);
2471         ff_MPV_common_end(s);
2472         h->list_count = 0;
2473         h->current_slice = 0;
2474     }
2475     if (!s->context_initialized) {
2476         if (h != h0) {
2477             av_log(h->s.avctx, AV_LOG_ERROR,
2478                    "Cannot (re-)initialize context during parallel decoding.\n");
2479             return -1;
2480         }
2481         if(   FFALIGN(s->avctx->width , 16                                 ) == s->width
2482            && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height
2483            && !h->sps.crop_right && !h->sps.crop_bottom
2484            && (s->avctx->width != s->width || s->avctx->height && s->height)
2485         ) {
2486             av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
2487             s->avctx->coded_width  = s->width;
2488             s->avctx->coded_height = s->height;
2489         } else{
2490             avcodec_set_dimensions(s->avctx, s->width, s->height);
2491             s->avctx->width  -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2492             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);
2493         }
2494         s->avctx->sample_aspect_ratio = h->sps.sar;
2495         av_assert0(s->avctx->sample_aspect_ratio.den);
2496
2497         if (s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU
2498             && (h->sps.bit_depth_luma != 8 ||
2499                 h->sps.chroma_format_idc > 1)) {
2500             av_log(s->avctx, AV_LOG_ERROR,
2501                    "VDPAU decoding does not support video "
2502                    "colorspace\n");
2503             return -1;
2504         }
2505
2506         if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2507             h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2508             if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 && h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
2509                 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2510                 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2511                 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2512                 h->pixel_shift = h->sps.bit_depth_luma > 8;
2513
2514                 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2515                 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2516                 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2517                 ff_dsputil_init(&s->dsp, s->avctx);
2518             } else {
2519                 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
2520                        h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2521                 return -1;
2522             }
2523         }
2524
2525         if (h->sps.video_signal_type_present_flag) {
2526             s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
2527                                                       : AVCOL_RANGE_MPEG;
2528             if (h->sps.colour_description_present_flag) {
2529                 s->avctx->color_primaries = h->sps.color_primaries;
2530                 s->avctx->color_trc       = h->sps.color_trc;
2531                 s->avctx->colorspace      = h->sps.colorspace;
2532             }
2533         }
2534
2535         if (h->sps.timing_info_present_flag) {
2536             int64_t den = h->sps.time_scale;
2537             if (h->x264_build < 44U)
2538                 den *= 2;
2539             av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2540                       h->sps.num_units_in_tick, den, 1 << 30);
2541         }
2542
2543         switch (h->sps.bit_depth_luma) {
2544         case 9:
2545             if (CHROMA444) {
2546                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2547                     s->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
2548                 } else
2549                     s->avctx->pix_fmt = AV_PIX_FMT_YUV444P9;
2550             } else if (CHROMA422)
2551                 s->avctx->pix_fmt = AV_PIX_FMT_YUV422P9;
2552             else
2553                 s->avctx->pix_fmt = AV_PIX_FMT_YUV420P9;
2554             break;
2555         case 10:
2556             if (CHROMA444) {
2557                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2558                     s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
2559                 } else
2560                     s->avctx->pix_fmt = AV_PIX_FMT_YUV444P10;
2561             } else if (CHROMA422)
2562                 s->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
2563             else
2564                 s->avctx->pix_fmt = AV_PIX_FMT_YUV420P10;
2565             break;
2566         case 12:
2567             if (CHROMA444) {
2568                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2569                     s->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
2570                 } else
2571                     s->avctx->pix_fmt = AV_PIX_FMT_YUV444P12;
2572             } else if (CHROMA422)
2573                 s->avctx->pix_fmt = AV_PIX_FMT_YUV422P12;
2574             else
2575                 s->avctx->pix_fmt = AV_PIX_FMT_YUV420P12;
2576             break;
2577         case 14:
2578             if (CHROMA444) {
2579                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2580                     s->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
2581                 } else
2582                     s->avctx->pix_fmt = AV_PIX_FMT_YUV444P14;
2583             } else if (CHROMA422)
2584                 s->avctx->pix_fmt = AV_PIX_FMT_YUV422P14;
2585             else
2586                 s->avctx->pix_fmt = AV_PIX_FMT_YUV420P14;
2587             break;
2588         case 8:
2589             if (CHROMA444) {
2590                     s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2591                                                                                   : AV_PIX_FMT_YUV444P;
2592                     if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2593                         s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
2594                         av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2595                     } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
2596                         av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2597                     }
2598             } else if (CHROMA422) {
2599                 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2600                                                                               : AV_PIX_FMT_YUV422P;
2601             } else {
2602                 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2603                                                          s->avctx->codec->pix_fmts ?
2604                                                          s->avctx->codec->pix_fmts :
2605                                                          s->avctx->color_range == AVCOL_RANGE_JPEG ?
2606                                                          hwaccel_pixfmt_list_h264_jpeg_420 :
2607                                                          ff_hwaccel_pixfmt_list_420);
2608             }
2609             break;
2610         default:
2611             av_log(s->avctx, AV_LOG_ERROR,
2612                    "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2613             return AVERROR_INVALIDDATA;
2614         }
2615
2616         s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
2617                                             s->avctx->pix_fmt);
2618
2619         if (ff_MPV_common_init(s) < 0) {
2620             av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
2621             return -1;
2622         }
2623         s->first_field = 0;
2624         h->prev_interlaced_frame = 1;
2625
2626         init_scan_tables(h);
2627         if (ff_h264_alloc_tables(h) < 0) {
2628             av_log(h->s.avctx, AV_LOG_ERROR,
2629                    "Could not allocate memory for h264\n");
2630             return AVERROR(ENOMEM);
2631         }
2632
2633         if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
2634             if (context_init(h) < 0) {
2635                 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2636                 return -1;
2637             }
2638         } else {
2639             for (i = 1; i < s->slice_context_count; i++) {
2640                 H264Context *c;
2641                 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2642                 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2643                 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2644                 c->h264dsp     = h->h264dsp;
2645                 c->sps         = h->sps;
2646                 c->pps         = h->pps;
2647                 c->pixel_shift = h->pixel_shift;
2648                 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
2649                 init_scan_tables(c);
2650                 clone_tables(c, h, i);
2651             }
2652
2653             for (i = 0; i < s->slice_context_count; i++)
2654                 if (context_init(h->thread_context[i]) < 0) {
2655                     av_log(h->s.avctx, AV_LOG_ERROR,
2656                            "context_init() failed.\n");
2657                     return -1;
2658                 }
2659         }
2660     }
2661
2662     if (h == h0 && h->dequant_coeff_pps != pps_id) {
2663         h->dequant_coeff_pps = pps_id;
2664         init_dequant_tables(h);
2665     }
2666
2667     h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
2668
2669     h->mb_mbaff        = 0;
2670     h->mb_aff_frame    = 0;
2671     last_pic_structure = s0->picture_structure;
2672     last_pic_dropable  = s->dropable;
2673     s->dropable        = h->nal_ref_idc == 0;
2674     if (h->sps.frame_mbs_only_flag) {
2675         s->picture_structure = PICT_FRAME;
2676     } else {
2677         if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
2678             av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
2679             return -1;
2680         }
2681         if (get_bits1(&s->gb)) { // field_pic_flag
2682             s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
2683         } else {
2684             s->picture_structure = PICT_FRAME;
2685             h->mb_aff_frame      = h->sps.mb_aff;
2686         }
2687     }
2688     h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
2689
2690     if (h0->current_slice != 0) {
2691         if (last_pic_structure != s->picture_structure ||
2692             last_pic_dropable  != s->dropable) {
2693             av_log(h->s.avctx, AV_LOG_ERROR,
2694                    "Changing field mode (%d -> %d) between slices is not allowed\n",
2695                    last_pic_structure, s->picture_structure);
2696             s->picture_structure = last_pic_structure;
2697             s->dropable          = last_pic_dropable;
2698             return AVERROR_INVALIDDATA;
2699         }
2700     } else {
2701         /* Shorten frame num gaps so we don't have to allocate reference
2702          * frames just to throw them away */
2703         if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
2704             int unwrap_prev_frame_num = h->prev_frame_num;
2705             int max_frame_num         = 1 << h->sps.log2_max_frame_num;
2706
2707             if (unwrap_prev_frame_num > h->frame_num)
2708                 unwrap_prev_frame_num -= max_frame_num;
2709
2710             if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2711                 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2712                 if (unwrap_prev_frame_num < 0)
2713                     unwrap_prev_frame_num += max_frame_num;
2714
2715                 h->prev_frame_num = unwrap_prev_frame_num;
2716             }
2717         }
2718
2719         /* See if we have a decoded first field looking for a pair...
2720          * Here, we're using that to see if we should mark previously
2721          * decode frames as "finished".
2722          * We have to do that before the "dummy" in-between frame allocation,
2723          * since that can modify s->current_picture_ptr. */
2724         if (s0->first_field) {
2725             assert(s0->current_picture_ptr);
2726             assert(s0->current_picture_ptr->f.data[0]);
2727             assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2728
2729             /* Mark old field/frame as completed */
2730             if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
2731                 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2732                                           last_pic_structure == PICT_BOTTOM_FIELD);
2733             }
2734
2735             /* figure out if we have a complementary field pair */
2736             if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2737                 /* Previous field is unmatched. Don't display it, but let it
2738                  * remain for reference if marked as such. */
2739                 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
2740                     ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2741                                               last_pic_structure == PICT_TOP_FIELD);
2742                 }
2743             } else {
2744                 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2745                     /* This and previous field were reference, but had
2746                      * different frame_nums. Consider this field first in
2747                      * pair. Throw away previous field except for reference
2748                      * purposes. */
2749                     if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
2750                         ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2751                                                   last_pic_structure == PICT_TOP_FIELD);
2752                     }
2753                 } else {
2754                     /* Second field in complementary pair */
2755                     if (!((last_pic_structure   == PICT_TOP_FIELD &&
2756                            s->picture_structure == PICT_BOTTOM_FIELD) ||
2757                           (last_pic_structure   == PICT_BOTTOM_FIELD &&
2758                            s->picture_structure == PICT_TOP_FIELD))) {
2759                         av_log(s->avctx, AV_LOG_ERROR,
2760                                "Invalid field mode combination %d/%d\n",
2761                                last_pic_structure, s->picture_structure);
2762                         s->picture_structure = last_pic_structure;
2763                         s->dropable          = last_pic_dropable;
2764                         return AVERROR_INVALIDDATA;
2765                     } else if (last_pic_dropable != s->dropable) {
2766                         av_log(s->avctx, AV_LOG_ERROR,
2767                                "Cannot combine reference and non-reference fields in the same frame\n");
2768                         av_log_ask_for_sample(s->avctx, NULL);
2769                         s->picture_structure = last_pic_structure;
2770                         s->dropable          = last_pic_dropable;
2771                         return AVERROR_INVALIDDATA;
2772                     }
2773
2774                     /* Take ownership of this buffer. Note that if another thread owned
2775                      * the first field of this buffer, we're not operating on that pointer,
2776                      * so the original thread is still responsible for reporting progress
2777                      * on that first field (or if that was us, we just did that above).
2778                      * By taking ownership, we assign responsibility to ourselves to
2779                      * report progress on the second field. */
2780                     s0->current_picture_ptr->owner2 = s0;
2781                 }
2782             }
2783         }
2784
2785         while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
2786                h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
2787             Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2788             av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
2789                    h->frame_num, h->prev_frame_num);
2790             if (ff_h264_frame_start(h) < 0)
2791                 return -1;
2792             h->prev_frame_num++;
2793             h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
2794             s->current_picture_ptr->frame_num = h->prev_frame_num;
2795             ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
2796             ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
2797             ff_generate_sliding_window_mmcos(h);
2798             if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2799                 (s->avctx->err_recognition & AV_EF_EXPLODE))
2800                 return AVERROR_INVALIDDATA;
2801             /* Error concealment: if a ref is missing, copy the previous ref in its place.
2802              * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2803              * about there being no actual duplicates.
2804              * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2805              * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2806              * be fixed. */
2807             if (h->short_ref_count) {
2808                 if (prev) {
2809                     av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2810                                   (const uint8_t **)prev->f.data, prev->f.linesize,
2811                                   s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
2812                     h->short_ref[0]->poc = prev->poc + 2;
2813                 }
2814                 h->short_ref[0]->frame_num = h->prev_frame_num;
2815             }
2816         }
2817
2818         /* See if we have a decoded first field looking for a pair...
2819          * We're using that to see whether to continue decoding in that
2820          * frame, or to allocate a new one. */
2821         if (s0->first_field) {
2822             assert(s0->current_picture_ptr);
2823             assert(s0->current_picture_ptr->f.data[0]);
2824             assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2825
2826             /* figure out if we have a complementary field pair */
2827             if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2828                 /* Previous field is unmatched. Don't display it, but let it
2829                  * remain for reference if marked as such. */
2830                 s0->current_picture_ptr = NULL;
2831                 s0->first_field         = FIELD_PICTURE;
2832             } else {
2833                 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2834                     ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
2835                                               s0->picture_structure==PICT_BOTTOM_FIELD);
2836                     /* This and the previous field had different frame_nums.
2837                      * Consider this field first in pair. Throw away previous
2838                      * one except for reference purposes. */
2839                     s0->first_field         = 1;
2840                     s0->current_picture_ptr = NULL;
2841                 } else {
2842                     /* Second field in complementary pair */
2843                     s0->first_field = 0;
2844                 }
2845             }
2846         } else {
2847             /* Frame or first field in a potentially complementary pair */
2848             s0->first_field = FIELD_PICTURE;
2849         }
2850
2851         if (!FIELD_PICTURE || s0->first_field) {
2852             if (ff_h264_frame_start(h) < 0) {
2853                 s0->first_field = 0;
2854                 return -1;
2855             }
2856         } else {
2857             ff_release_unused_pictures(s, 0);
2858         }
2859     }
2860     if (h != h0)
2861         clone_slice(h, h0);
2862
2863     s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
2864
2865     av_assert1(s->mb_num == s->mb_width * s->mb_height);
2866     if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2867         first_mb_in_slice >= s->mb_num) {
2868         av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2869         return -1;
2870     }
2871     s->resync_mb_x = s->mb_x =  first_mb_in_slice % s->mb_width;
2872     s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2873     if (s->picture_structure == PICT_BOTTOM_FIELD)
2874         s->resync_mb_y = s->mb_y = s->mb_y + 1;
2875     av_assert1(s->mb_y < s->mb_height);
2876
2877     if (s->picture_structure == PICT_FRAME) {
2878         h->curr_pic_num = h->frame_num;
2879         h->max_pic_num  = 1 << h->sps.log2_max_frame_num;
2880     } else {
2881         h->curr_pic_num = 2 * h->frame_num + 1;
2882         h->max_pic_num  = 1 << (h->sps.log2_max_frame_num + 1);
2883     }
2884
2885     if (h->nal_unit_type == NAL_IDR_SLICE)
2886         get_ue_golomb(&s->gb); /* idr_pic_id */
2887
2888     if (h->sps.poc_type == 0) {
2889         h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2890
2891         if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2892             h->delta_poc_bottom = get_se_golomb(&s->gb);
2893     }
2894
2895     if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
2896         h->delta_poc[0] = get_se_golomb(&s->gb);
2897
2898         if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2899             h->delta_poc[1] = get_se_golomb(&s->gb);
2900     }
2901
2902     init_poc(h);
2903
2904     if (h->pps.redundant_pic_cnt_present)
2905         h->redundant_pic_count = get_ue_golomb(&s->gb);
2906
2907     // set defaults, might be overridden a few lines later
2908     h->ref_count[0] = h->pps.ref_count[0];
2909     h->ref_count[1] = h->pps.ref_count[1];
2910
2911     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2912         unsigned max[2];
2913         max[0] = max[1] = s->picture_structure == PICT_FRAME ? 15 : 31;
2914
2915         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2916             h->direct_spatial_mv_pred = get_bits1(&s->gb);
2917         num_ref_idx_active_override_flag = get_bits1(&s->gb);
2918
2919         if (num_ref_idx_active_override_flag) {
2920             h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
2921             if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2922                 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
2923             else
2924                 // full range is spec-ok in this case, even for frames
2925                 max[1] = 31;
2926         }
2927
2928         if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
2929             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]);
2930             h->ref_count[0] = h->ref_count[1] = 1;
2931             return AVERROR_INVALIDDATA;
2932         }
2933
2934         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2935             h->list_count = 2;
2936         else
2937             h->list_count = 1;
2938     } else
2939         h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
2940
2941     if (!default_ref_list_done)
2942         ff_h264_fill_default_ref_list(h);
2943
2944     if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
2945         ff_h264_decode_ref_pic_list_reordering(h) < 0) {
2946         h->ref_count[1] = h->ref_count[0] = 0;
2947         return -1;
2948     }
2949
2950     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2951         s->last_picture_ptr = &h->ref_list[0][0];
2952         ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2953     }
2954     if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
2955         s->next_picture_ptr = &h->ref_list[1][0];
2956         ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2957     }
2958
2959     if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
2960         (h->pps.weighted_bipred_idc == 1 &&
2961          h->slice_type_nos == AV_PICTURE_TYPE_B))
2962         pred_weight_table(h);
2963     else if (h->pps.weighted_bipred_idc == 2 &&
2964              h->slice_type_nos == AV_PICTURE_TYPE_B) {
2965         implicit_weight_table(h, -1);
2966     } else {
2967         h->use_weight = 0;
2968         for (i = 0; i < 2; i++) {
2969             h->luma_weight_flag[i]   = 0;
2970             h->chroma_weight_flag[i] = 0;
2971         }
2972     }
2973
2974     if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
2975         (s->avctx->err_recognition & AV_EF_EXPLODE))
2976         return AVERROR_INVALIDDATA;
2977
2978     if (FRAME_MBAFF) {
2979         ff_h264_fill_mbaff_ref_list(h);
2980
2981         if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
2982             implicit_weight_table(h, 0);
2983             implicit_weight_table(h, 1);
2984         }
2985     }
2986
2987     if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
2988         ff_h264_direct_dist_scale_factor(h);
2989     ff_h264_direct_ref_list_init(h);
2990
2991     if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
2992         tmp = get_ue_golomb_31(&s->gb);
2993         if (tmp > 2) {
2994             av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2995             return -1;
2996         }
2997         h->cabac_init_idc = tmp;
2998     }
2999
3000     h->last_qscale_diff = 0;
3001     tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3002     if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3003         av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3004         return -1;
3005     }
3006     s->qscale       = tmp;
3007     h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3008     h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3009     // FIXME qscale / qp ... stuff
3010     if (h->slice_type == AV_PICTURE_TYPE_SP)
3011         get_bits1(&s->gb); /* sp_for_switch_flag */
3012     if (h->slice_type == AV_PICTURE_TYPE_SP ||
3013         h->slice_type == AV_PICTURE_TYPE_SI)
3014         get_se_golomb(&s->gb); /* slice_qs_delta */
3015
3016     h->deblocking_filter     = 1;
3017     h->slice_alpha_c0_offset = 52;
3018     h->slice_beta_offset     = 52;
3019     if (h->pps.deblocking_filter_parameters_present) {
3020         tmp = get_ue_golomb_31(&s->gb);
3021         if (tmp > 2) {
3022             av_log(s->avctx, AV_LOG_ERROR,
3023                    "deblocking_filter_idc %u out of range\n", tmp);
3024             return -1;
3025         }
3026         h->deblocking_filter = tmp;
3027         if (h->deblocking_filter < 2)
3028             h->deblocking_filter ^= 1;  // 1<->0
3029
3030         if (h->deblocking_filter) {
3031             h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3032             h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
3033             if (h->slice_alpha_c0_offset > 104U ||
3034                 h->slice_beta_offset     > 104U) {
3035                 av_log(s->avctx, AV_LOG_ERROR,
3036                        "deblocking filter parameters %d %d out of range\n",
3037                        h->slice_alpha_c0_offset, h->slice_beta_offset);
3038                 return -1;
3039             }
3040         }
3041     }
3042
3043     if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3044         (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3045          h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3046         (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&
3047          h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3048         (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3049          h->nal_ref_idc == 0))
3050         h->deblocking_filter = 0;
3051
3052     if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3053         if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3054             /* Cheat slightly for speed:
3055              * Do not bother to deblock across slices. */
3056             h->deblocking_filter = 2;
3057         } else {
3058             h0->max_contexts = 1;
3059             if (!h0->single_decode_warning) {
3060                 av_log(s->avctx, AV_LOG_INFO,
3061                        "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3062                 h0->single_decode_warning = 1;
3063             }
3064             if (h != h0) {
3065                 av_log(h->s.avctx, AV_LOG_ERROR,
3066                        "Deblocking switched inside frame.\n");
3067                 return 1;
3068             }
3069         }
3070     }
3071     h->qp_thresh = 15 + 52 -
3072                    FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3073                    FFMAX3(0,
3074                           h->pps.chroma_qp_index_offset[0],
3075                           h->pps.chroma_qp_index_offset[1]) +
3076                    6 * (h->sps.bit_depth_luma - 8);
3077
3078     h0->last_slice_type = slice_type;
3079     h->slice_num = ++h0->current_slice;
3080
3081     if (h->slice_num)
3082         h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
3083     if (   h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
3084         && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
3085         && h->slice_num >= MAX_SLICES) {
3086         //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3087         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);
3088     }
3089
3090     for (j = 0; j < 2; j++) {
3091         int id_list[16];
3092         int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3093         for (i = 0; i < 16; i++) {
3094             id_list[i] = 60;
3095             if (h->ref_list[j][i].f.data[0]) {
3096                 int k;
3097                 uint8_t *base = h->ref_list[j][i].f.base[0];
3098                 for (k = 0; k < h->short_ref_count; k++)
3099                     if (h->short_ref[k]->f.base[0] == base) {
3100                         id_list[i] = k;
3101                         break;
3102                     }
3103                 for (k = 0; k < h->long_ref_count; k++)
3104                     if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3105                         id_list[i] = h->short_ref_count + k;
3106                         break;
3107                     }
3108             }
3109         }
3110
3111         ref2frm[0]     =
3112             ref2frm[1] = -1;
3113         for (i = 0; i < 16; i++)
3114             ref2frm[i + 2] = 4 * id_list[i] +
3115                              (h->ref_list[j][i].f.reference & 3);
3116         ref2frm[18 + 0]     =
3117             ref2frm[18 + 1] = -1;
3118         for (i = 16; i < 48; i++)
3119             ref2frm[i + 4] =