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