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