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