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