]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
h264: K&R formatting cosmetics
[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,
2751                                   (16 * s->mb_height >> FIELD_PICTURE) - 1,
2752                                   s->picture_structure == PICT_BOTTOM_FIELD);
2753
2754     if (CONFIG_H264_VDPAU_DECODER &&
2755         s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2756         ff_vdpau_h264_set_reference_frames(s);
2757
2758     if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2759         if (!s->dropable) {
2760             err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2761             h->prev_poc_msb = h->poc_msb;
2762             h->prev_poc_lsb = h->poc_lsb;
2763         }
2764         h->prev_frame_num_offset = h->frame_num_offset;
2765         h->prev_frame_num        = h->frame_num;
2766         h->outputed_poc          = h->next_outputed_poc;
2767     }
2768
2769     if (avctx->hwaccel) {
2770         if (avctx->hwaccel->end_frame(avctx) < 0)
2771             av_log(avctx, AV_LOG_ERROR,
2772                    "hardware accelerator failed to decode picture\n");
2773     }
2774
2775     if (CONFIG_H264_VDPAU_DECODER &&
2776         s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2777         ff_vdpau_h264_picture_complete(s);
2778
2779     /*
2780      * FIXME: Error handling code does not seem to support interlaced
2781      * when slices span multiple rows
2782      * The ff_er_add_slice calls don't work right for bottom
2783      * fields; they cause massive erroneous error concealing
2784      * Error marking covers both fields (top and bottom).
2785      * This causes a mismatched s->error_count
2786      * and a bad error table. Further, the error count goes to
2787      * INT_MAX when called for bottom field, because mb_y is
2788      * past end by one (callers fault) and resync_mb_y != 0
2789      * causes problems for the first MB line, too.
2790      */
2791     if (!FIELD_PICTURE)
2792         ff_er_frame_end(s);
2793
2794     ff_MPV_frame_end(s);
2795
2796     h->current_slice = 0;
2797
2798     return err;
2799 }
2800
2801 /**
2802  * Replicate H264 "master" context to thread contexts.
2803  */
2804 static void clone_slice(H264Context *dst, H264Context *src)
2805 {
2806     memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2807     dst->s.current_picture_ptr = src->s.current_picture_ptr;
2808     dst->s.current_picture     = src->s.current_picture;
2809     dst->s.linesize            = src->s.linesize;
2810     dst->s.uvlinesize          = src->s.uvlinesize;
2811     dst->s.first_field         = src->s.first_field;
2812
2813     dst->prev_poc_msb          = src->prev_poc_msb;
2814     dst->prev_poc_lsb          = src->prev_poc_lsb;
2815     dst->prev_frame_num_offset = src->prev_frame_num_offset;
2816     dst->prev_frame_num        = src->prev_frame_num;
2817     dst->short_ref_count       = src->short_ref_count;
2818
2819     memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2820     memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2821     memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2822     memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2823
2824     memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2825     memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2826 }
2827
2828 /**
2829  * Compute profile from profile_idc and constraint_set?_flags.
2830  *
2831  * @param sps SPS
2832  *
2833  * @return profile as defined by FF_PROFILE_H264_*
2834  */
2835 int ff_h264_get_profile(SPS *sps)
2836 {
2837     int profile = sps->profile_idc;
2838
2839     switch (sps->profile_idc) {
2840     case FF_PROFILE_H264_BASELINE:
2841         // constraint_set1_flag set to 1
2842         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2843         break;
2844     case FF_PROFILE_H264_HIGH_10:
2845     case FF_PROFILE_H264_HIGH_422:
2846     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2847         // constraint_set3_flag set to 1
2848         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2849         break;
2850     }
2851
2852     return profile;
2853 }
2854
2855 /**
2856  * Decode a slice header.
2857  * This will also call ff_MPV_common_init() and frame_start() as needed.
2858  *
2859  * @param h h264context
2860  * @param h0 h264 master context (differs from 'h' when doing sliced based
2861  *           parallel decoding)
2862  *
2863  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2864  */
2865 static int decode_slice_header(H264Context *h, H264Context *h0)
2866 {
2867     MpegEncContext *const s  = &h->s;
2868     MpegEncContext *const s0 = &h0->s;
2869     unsigned int first_mb_in_slice;
2870     unsigned int pps_id;
2871     int num_ref_idx_active_override_flag;
2872     unsigned int slice_type, tmp, i, j;
2873     int default_ref_list_done = 0;
2874     int last_pic_structure;
2875
2876     s->dropable = h->nal_ref_idc == 0;
2877
2878     /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2879     if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
2880         !h->nal_ref_idc && !h->pixel_shift) {
2881         s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
2882         s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
2883     } else {
2884         s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
2885         s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
2886     }
2887
2888     first_mb_in_slice = get_ue_golomb(&s->gb);
2889
2890     if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2891         if (h0->current_slice && FIELD_PICTURE) {
2892             field_end(h, 1);
2893         }
2894
2895         h0->current_slice = 0;
2896         if (!s0->first_field)
2897             s->current_picture_ptr = NULL;
2898     }
2899
2900     slice_type = get_ue_golomb_31(&s->gb);
2901     if (slice_type > 9) {
2902         av_log(h->s.avctx, AV_LOG_ERROR,
2903                "slice type too large (%d) at %d %d\n",
2904                h->slice_type, s->mb_x, s->mb_y);
2905         return -1;
2906     }
2907     if (slice_type > 4) {
2908         slice_type -= 5;
2909         h->slice_type_fixed = 1;
2910     } else
2911         h->slice_type_fixed = 0;
2912
2913     slice_type = golomb_to_pict_type[slice_type];
2914     if (slice_type == AV_PICTURE_TYPE_I ||
2915         (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2916         default_ref_list_done = 1;
2917     }
2918     h->slice_type     = slice_type;
2919     h->slice_type_nos = slice_type & 3;
2920
2921     // to make a few old functions happy, it's wrong though
2922     s->pict_type = h->slice_type;
2923
2924     pps_id = get_ue_golomb(&s->gb);
2925     if (pps_id >= MAX_PPS_COUNT) {
2926         av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2927         return -1;
2928     }
2929     if (!h0->pps_buffers[pps_id]) {
2930         av_log(h->s.avctx, AV_LOG_ERROR,
2931                "non-existing PPS %u referenced\n",
2932                pps_id);
2933         return -1;
2934     }
2935     h->pps = *h0->pps_buffers[pps_id];
2936
2937     if (!h0->sps_buffers[h->pps.sps_id]) {
2938         av_log(h->s.avctx, AV_LOG_ERROR,
2939                "non-existing SPS %u referenced\n",
2940                h->pps.sps_id);
2941         return -1;
2942     }
2943     h->sps = *h0->sps_buffers[h->pps.sps_id];
2944
2945     s->avctx->profile = ff_h264_get_profile(&h->sps);
2946     s->avctx->level   = h->sps.level_idc;
2947     s->avctx->refs    = h->sps.ref_frame_count;
2948
2949     s->mb_width  = h->sps.mb_width;
2950     s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2951
2952     h->b_stride = s->mb_width * 4;
2953
2954     s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2955
2956     s->width = 16 * s->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
2957     if (h->sps.frame_mbs_only_flag)
2958         s->height = 16 * s->mb_height - (1 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2959     else
2960         s->height = 16 * s->mb_height - (2 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2961
2962     if (s->context_initialized &&
2963         (s->width != s->avctx->width || s->height != s->avctx->height ||
2964          av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2965         if (h != h0) {
2966             av_log_missing_feature(s->avctx,
2967                                    "Width/height changing with threads is", 0);
2968             return -1;   // width / height changed during parallelized decoding
2969         }
2970         free_tables(h, 0);
2971         flush_dpb(s->avctx);
2972         ff_MPV_common_end(s);
2973     }
2974     if (!s->context_initialized) {
2975         if (h != h0) {
2976             av_log(h->s.avctx, AV_LOG_ERROR,
2977                    "Cannot (re-)initialize context during parallel decoding.\n");
2978             return -1;
2979         }
2980
2981         avcodec_set_dimensions(s->avctx, s->width, s->height);
2982         s->avctx->sample_aspect_ratio = h->sps.sar;
2983         av_assert0(s->avctx->sample_aspect_ratio.den);
2984
2985         if (h->sps.video_signal_type_present_flag) {
2986             s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
2987                                                       : AVCOL_RANGE_MPEG;
2988             if (h->sps.colour_description_present_flag) {
2989                 s->avctx->color_primaries = h->sps.color_primaries;
2990                 s->avctx->color_trc       = h->sps.color_trc;
2991                 s->avctx->colorspace      = h->sps.colorspace;
2992             }
2993         }
2994
2995         if (h->sps.timing_info_present_flag) {
2996             int64_t den = h->sps.time_scale;
2997             if (h->x264_build < 44U)
2998                 den *= 2;
2999             av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
3000                       h->sps.num_units_in_tick, den, 1 << 30);
3001         }
3002
3003         switch (h->sps.bit_depth_luma) {
3004         case 9:
3005             if (CHROMA444) {
3006                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3007                     s->avctx->pix_fmt = PIX_FMT_GBRP9;
3008                 } else
3009                     s->avctx->pix_fmt = PIX_FMT_YUV444P9;
3010             } else if (CHROMA422)
3011                 s->avctx->pix_fmt = PIX_FMT_YUV422P9;
3012             else
3013                 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
3014             break;
3015         case 10:
3016             if (CHROMA444) {
3017                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3018                     s->avctx->pix_fmt = PIX_FMT_GBRP10;
3019                 } else
3020                     s->avctx->pix_fmt = PIX_FMT_YUV444P10;
3021             } else if (CHROMA422)
3022                 s->avctx->pix_fmt = PIX_FMT_YUV422P10;
3023             else
3024                 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
3025             break;
3026         case 8:
3027             if (CHROMA444) {
3028                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3029                     s->avctx->pix_fmt = PIX_FMT_GBRP;
3030                 } else
3031                     s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P
3032                                                                                   : PIX_FMT_YUV444P;
3033             } else if (CHROMA422) {
3034                 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P
3035                                                                               : PIX_FMT_YUV422P;
3036             } else {
3037                 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
3038                                                          s->avctx->codec->pix_fmts ?
3039                                                          s->avctx->codec->pix_fmts :
3040                                                          s->avctx->color_range == AVCOL_RANGE_JPEG ?
3041                                                          hwaccel_pixfmt_list_h264_jpeg_420 :
3042                                                          ff_hwaccel_pixfmt_list_420);
3043             }
3044             break;
3045         default:
3046             av_log(s->avctx, AV_LOG_ERROR,
3047                    "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3048             return AVERROR_INVALIDDATA;
3049         }
3050
3051         s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
3052                                             s->avctx->pix_fmt);
3053
3054         if (ff_MPV_common_init(s) < 0) {
3055             av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
3056             return -1;
3057         }
3058         s->first_field = 0;
3059         h->prev_interlaced_frame = 1;
3060
3061         init_scan_tables(h);
3062         if (ff_h264_alloc_tables(h) < 0) {
3063             av_log(h->s.avctx, AV_LOG_ERROR,
3064                    "Could not allocate memory for h264\n");
3065             return AVERROR(ENOMEM);
3066         }
3067
3068         if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
3069             if (context_init(h) < 0) {
3070                 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
3071                 return -1;
3072             }
3073         } else {
3074             for (i = 1; i < s->slice_context_count; i++) {
3075                 H264Context *c;
3076                 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
3077                 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
3078                 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
3079                 c->h264dsp     = h->h264dsp;
3080                 c->sps         = h->sps;
3081                 c->pps         = h->pps;
3082                 c->pixel_shift = h->pixel_shift;
3083                 init_scan_tables(c);
3084                 clone_tables(c, h, i);
3085             }
3086
3087             for (i = 0; i < s->slice_context_count; i++)
3088                 if (context_init(h->thread_context[i]) < 0) {
3089                     av_log(h->s.avctx, AV_LOG_ERROR,
3090                            "context_init() failed.\n");
3091                     return -1;
3092                 }
3093         }
3094     }
3095
3096     if (h == h0 && h->dequant_coeff_pps != pps_id) {
3097         h->dequant_coeff_pps = pps_id;
3098         init_dequant_tables(h);
3099     }
3100
3101     h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
3102
3103     h->mb_mbaff        = 0;
3104     h->mb_aff_frame    = 0;
3105     last_pic_structure = s0->picture_structure;
3106     if (h->sps.frame_mbs_only_flag) {
3107         s->picture_structure = PICT_FRAME;
3108     } else {
3109         if (get_bits1(&s->gb)) { // field_pic_flag
3110             s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
3111         } else {
3112             s->picture_structure = PICT_FRAME;
3113             h->mb_aff_frame      = h->sps.mb_aff;
3114         }
3115     }
3116     h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
3117
3118     if (h0->current_slice == 0) {
3119         /* Shorten frame num gaps so we don't have to allocate reference
3120          * frames just to throw them away */
3121         if (h->frame_num != h->prev_frame_num) {
3122             int unwrap_prev_frame_num = h->prev_frame_num;
3123             int max_frame_num         = 1 << h->sps.log2_max_frame_num;
3124
3125             if (unwrap_prev_frame_num > h->frame_num)
3126                 unwrap_prev_frame_num -= max_frame_num;
3127
3128             if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3129                 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3130                 if (unwrap_prev_frame_num < 0)
3131                     unwrap_prev_frame_num += max_frame_num;
3132
3133                 h->prev_frame_num = unwrap_prev_frame_num;
3134             }
3135         }
3136
3137         while (h->frame_num != h->prev_frame_num &&
3138                h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3139             Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3140             av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3141                    h->frame_num, h->prev_frame_num);
3142             if (ff_h264_frame_start(h) < 0)
3143                 return -1;
3144             h->prev_frame_num++;
3145             h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3146             s->current_picture_ptr->frame_num = h->prev_frame_num;
3147             ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
3148             ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
3149             ff_generate_sliding_window_mmcos(h);
3150             if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3151                 (s->avctx->err_recognition & AV_EF_EXPLODE))
3152                 return AVERROR_INVALIDDATA;
3153             /* Error concealment: if a ref is missing, copy the previous ref in its place.
3154              * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3155              * about there being no actual duplicates.
3156              * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
3157              * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3158              * be fixed. */
3159             if (h->short_ref_count) {
3160                 if (prev) {
3161                     av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3162                                   (const uint8_t **)prev->f.data, prev->f.linesize,
3163                                   s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
3164                     h->short_ref[0]->poc = prev->poc + 2;
3165                 }
3166                 h->short_ref[0]->frame_num = h->prev_frame_num;
3167             }
3168         }
3169
3170         /* See if we have a decoded first field looking for a pair... */
3171         if (s0->first_field) {
3172             assert(s0->current_picture_ptr);
3173             assert(s0->current_picture_ptr->f.data[0]);
3174             assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
3175
3176             /* figure out if we have a complementary field pair */
3177             if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3178                 /* Previous field is unmatched. Don't display it, but let it
3179                  * remain for reference if marked as such. */
3180                 s0->current_picture_ptr = NULL;
3181                 s0->first_field         = FIELD_PICTURE;
3182             } else {
3183                 if (h->nal_ref_idc &&
3184                     s0->current_picture_ptr->f.reference &&
3185                     s0->current_picture_ptr->frame_num != h->frame_num) {
3186                     /* This and the previous field were reference, but had
3187                      * different frame_nums. Consider this field first in pair.
3188                      * Throw away previous one except for reference purposes. */
3189                     s0->first_field         = 1;
3190                     s0->current_picture_ptr = NULL;
3191                 } else {
3192                     /* Second field in complementary pair */
3193                     s0->first_field = 0;
3194                 }
3195             }
3196         } else {
3197             /* Frame or first field in a potentially complementary pair */
3198             assert(!s0->current_picture_ptr);
3199             s0->first_field = FIELD_PICTURE;
3200         }
3201
3202         if (!FIELD_PICTURE || s0->first_field) {
3203             if (ff_h264_frame_start(h) < 0) {
3204                 s0->first_field = 0;
3205                 return -1;
3206             }
3207         } else {
3208             ff_release_unused_pictures(s, 0);
3209         }
3210     }
3211     if (h != h0)
3212         clone_slice(h, h0);
3213
3214     s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3215
3216     assert(s->mb_num == s->mb_width * s->mb_height);
3217     if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
3218         first_mb_in_slice >= s->mb_num) {
3219         av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3220         return -1;
3221     }
3222     s->resync_mb_x = s->mb_x =  first_mb_in_slice % s->mb_width;
3223     s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3224     if (s->picture_structure == PICT_BOTTOM_FIELD)
3225         s->resync_mb_y = s->mb_y = s->mb_y + 1;
3226     assert(s->mb_y < s->mb_height);
3227
3228     if (s->picture_structure == PICT_FRAME) {
3229         h->curr_pic_num = h->frame_num;
3230         h->max_pic_num  = 1 << h->sps.log2_max_frame_num;
3231     } else {
3232         h->curr_pic_num = 2 * h->frame_num + 1;
3233         h->max_pic_num  = 1 << (h->sps.log2_max_frame_num + 1);
3234     }
3235
3236     if (h->nal_unit_type == NAL_IDR_SLICE)
3237         get_ue_golomb(&s->gb); /* idr_pic_id */
3238
3239     if (h->sps.poc_type == 0) {
3240         h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3241
3242         if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3243             h->delta_poc_bottom = get_se_golomb(&s->gb);
3244     }
3245
3246     if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3247         h->delta_poc[0] = get_se_golomb(&s->gb);
3248
3249         if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3250             h->delta_poc[1] = get_se_golomb(&s->gb);
3251     }
3252
3253     init_poc(h);
3254
3255     if (h->pps.redundant_pic_cnt_present)
3256         h->redundant_pic_count = get_ue_golomb(&s->gb);
3257
3258     // set defaults, might be overridden a few lines later
3259     h->ref_count[0] = h->pps.ref_count[0];
3260     h->ref_count[1] = h->pps.ref_count[1];
3261
3262     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3263         int max_refs = s->picture_structure == PICT_FRAME ? 16 : 32;
3264
3265         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3266             h->direct_spatial_mv_pred = get_bits1(&s->gb);
3267         num_ref_idx_active_override_flag = get_bits1(&s->gb);
3268
3269         if (num_ref_idx_active_override_flag) {
3270             h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
3271             if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3272                 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
3273         }
3274
3275         if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
3276             av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3277             h->ref_count[0] = h->ref_count[1] = 1;
3278             return AVERROR_INVALIDDATA;
3279         }
3280
3281         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3282             h->list_count = 2;
3283         else
3284             h->list_count = 1;
3285     } else
3286         h->list_count = 0;
3287
3288     if (!default_ref_list_done)
3289         ff_h264_fill_default_ref_list(h);
3290
3291     if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
3292         ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3293         h->ref_count[1] = h->ref_count[0] = 0;
3294         return -1;
3295     }
3296
3297     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3298         s->last_picture_ptr = &h->ref_list[0][0];
3299         ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3300     }
3301     if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3302         s->next_picture_ptr = &h->ref_list[1][0];
3303         ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3304     }
3305
3306     if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3307         (h->pps.weighted_bipred_idc == 1 &&
3308          h->slice_type_nos == AV_PICTURE_TYPE_B))
3309         pred_weight_table(h);
3310     else if (h->pps.weighted_bipred_idc == 2 &&
3311              h->slice_type_nos == AV_PICTURE_TYPE_B) {
3312         implicit_weight_table(h, -1);
3313     } else {
3314         h->use_weight = 0;
3315         for (i = 0; i < 2; i++) {
3316             h->luma_weight_flag[i]   = 0;
3317             h->chroma_weight_flag[i] = 0;
3318         }
3319     }
3320
3321     if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
3322         (s->avctx->err_recognition & AV_EF_EXPLODE))
3323         return AVERROR_INVALIDDATA;
3324
3325     if (FRAME_MBAFF) {
3326         ff_h264_fill_mbaff_ref_list(h);
3327
3328         if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3329             implicit_weight_table(h, 0);
3330             implicit_weight_table(h, 1);
3331         }
3332     }
3333
3334     if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3335         ff_h264_direct_dist_scale_factor(h);
3336     ff_h264_direct_ref_list_init(h);
3337
3338     if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3339         tmp = get_ue_golomb_31(&s->gb);
3340         if (tmp > 2) {
3341             av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3342             return -1;
3343         }
3344         h->cabac_init_idc = tmp;
3345     }
3346
3347     h->last_qscale_diff = 0;
3348     tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3349     if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3350         av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3351         return -1;
3352     }
3353     s->qscale       = tmp;
3354     h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3355     h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3356     // FIXME qscale / qp ... stuff
3357     if (h->slice_type == AV_PICTURE_TYPE_SP)
3358         get_bits1(&s->gb); /* sp_for_switch_flag */
3359     if (h->slice_type == AV_PICTURE_TYPE_SP ||
3360         h->slice_type == AV_PICTURE_TYPE_SI)
3361         get_se_golomb(&s->gb); /* slice_qs_delta */
3362
3363     h->deblocking_filter     = 1;
3364     h->slice_alpha_c0_offset = 52;
3365     h->slice_beta_offset     = 52;
3366     if (h->pps.deblocking_filter_parameters_present) {
3367         tmp = get_ue_golomb_31(&s->gb);
3368         if (tmp > 2) {
3369             av_log(s->avctx, AV_LOG_ERROR,
3370                    "deblocking_filter_idc %u out of range\n", tmp);
3371             return -1;
3372         }
3373         h->deblocking_filter = tmp;
3374         if (h->deblocking_filter < 2)
3375             h->deblocking_filter ^= 1;  // 1<->0
3376
3377         if (h->deblocking_filter) {
3378             h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3379             h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
3380             if (h->slice_alpha_c0_offset > 104U ||
3381                 h->slice_beta_offset     > 104U) {
3382                 av_log(s->avctx, AV_LOG_ERROR,
3383                        "deblocking filter parameters %d %d out of range\n",
3384                        h->slice_alpha_c0_offset, h->slice_beta_offset);
3385                 return -1;
3386             }
3387         }
3388     }
3389
3390     if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3391         (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3392          h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3393         (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&
3394          h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3395         (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3396          h->nal_ref_idc == 0))
3397         h->deblocking_filter = 0;
3398
3399     if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3400         if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3401             /* Cheat slightly for speed:
3402              * Do not bother to deblock across slices. */
3403             h->deblocking_filter = 2;
3404         } else {
3405             h0->max_contexts = 1;
3406             if (!h0->single_decode_warning) {
3407                 av_log(s->avctx, AV_LOG_INFO,
3408                        "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3409                 h0->single_decode_warning = 1;
3410             }
3411             if (h != h0) {
3412                 av_log(h->s.avctx, AV_LOG_ERROR,
3413                        "Deblocking switched inside frame.\n");
3414                 return 1;
3415             }
3416         }
3417     }
3418     h->qp_thresh = 15 + 52 -
3419                    FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3420                    FFMAX3(0,
3421                           h->pps.chroma_qp_index_offset[0],
3422                           h->pps.chroma_qp_index_offset[1]) +
3423                    6 * (h->sps.bit_depth_luma - 8);
3424
3425     h0->last_slice_type = slice_type;
3426     h->slice_num = ++h0->current_slice;
3427     if (h->slice_num >= MAX_SLICES) {
3428         av_log(s->avctx, AV_LOG_ERROR,
3429                "Too many slices, increase MAX_SLICES and recompile\n");
3430     }
3431
3432     for (j = 0; j < 2; j++) {
3433         int id_list[16];
3434         int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3435         for (i = 0; i < 16; i++) {
3436             id_list[i] = 60;
3437             if (h->ref_list[j][i].f.data[0]) {
3438                 int k;
3439                 uint8_t *base = h->ref_list[j][i].f.base[0];
3440                 for (k = 0; k < h->short_ref_count; k++)
3441                     if (h->short_ref[k]->f.base[0] == base) {
3442                         id_list[i] = k;
3443                         break;
3444                     }
3445                 for (k = 0; k < h->long_ref_count; k++)
3446                     if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3447                         id_list[i] = h->short_ref_count + k;
3448                         break;
3449                     }
3450             }
3451         }
3452
3453         ref2frm[0]     =
3454             ref2frm[1] = -1;
3455         for (i = 0; i < 16; i++)
3456             ref2frm[i + 2] = 4 * id_list[i] +
3457                              (h->ref_list[j][i].f.reference & 3);
3458         ref2frm[18 + 0]     =
3459             ref2frm[18 + 1] = -1;
3460         for (i = 16; i < 48; i++)
3461             ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3462                              (h->ref_list[j][i].f.reference & 3);
3463     }
3464
3465     // FIXME: fix draw_edges + PAFF + frame threads
3466     h->emu_edge_width  = (s->flags & CODEC_FLAG_EMU_EDGE ||
3467                           (!h->sps.frame_mbs_only_flag &&
3468                            s->avctx->active_thread_type))
3469                          ? 0 : 16;
3470     h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3471
3472     if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3473         av_log(h->s.avctx, AV_LOG_DEBUG,
3474                "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",
3475                h->slice_num,
3476                (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3477                first_mb_in_slice,
3478                av_get_picture_type_char(h->slice_type),
3479                h->slice_type_fixed ? " fix" : "",
3480                h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3481                pps_id, h->frame_num,
3482                s->current_picture_ptr->field_poc[0],
3483                s->current_picture_ptr->field_poc[1],
3484                h->ref_count[0], h->ref_count[1],
3485                s->qscale,
3486                h->deblocking_filter,
3487                h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3488                h->use_weight,
3489                h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3490                h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3491     }
3492
3493     return 0;
3494 }
3495
3496 int ff_h264_get_slice_type(const H264Context *h)
3497 {
3498     switch (h->slice_type) {
3499     case AV_PICTURE_TYPE_P:
3500         return 0;
3501     case AV_PICTURE_TYPE_B:
3502         return 1;
3503     case AV_PICTURE_TYPE_I:
3504         return 2;
3505     case AV_PICTURE_TYPE_SP:
3506         return 3;
3507     case AV_PICTURE_TYPE_SI:
3508         return 4;
3509     default:
3510         return -1;
3511     }
3512 }
3513
3514 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3515                                                       MpegEncContext *const s,
3516                                                       int mb_type, int top_xy,
3517                                                       int left_xy[LEFT_MBS],
3518                                                       int top_type,
3519                                                       int left_type[LEFT_MBS],
3520                                                       int mb_xy, int list)
3521 {
3522     int b_stride = h->b_stride;
3523     int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3524     int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3525     if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3526         if (USES_LIST(top_type, list)) {
3527             const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;
3528             const int b8_xy = 4 * top_xy + 2;
3529             int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3530             AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
3531             ref_cache[0 - 1 * 8] =
3532             ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3533             ref_cache[2 - 1 * 8] =
3534             ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3535         } else {
3536             AV_ZERO128(mv_dst - 1 * 8);
3537             AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3538         }
3539
3540         if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3541             if (USES_LIST(left_type[LTOP], list)) {
3542                 const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;
3543                 const int b8_xy = 4 * left_xy[LTOP] + 1;
3544                 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3545                 AV_COPY32(mv_dst - 1 +  0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
3546                 AV_COPY32(mv_dst - 1 +  8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
3547                 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
3548                 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
3549                 ref_cache[-1 +  0] =
3550                 ref_cache[-1 +  8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
3551                 ref_cache[-1 + 16] =
3552                 ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
3553             } else {
3554                 AV_ZERO32(mv_dst - 1 +  0);
3555                 AV_ZERO32(mv_dst - 1 +  8);
3556                 AV_ZERO32(mv_dst - 1 + 16);
3557                 AV_ZERO32(mv_dst - 1 + 24);
3558                 ref_cache[-1 +  0] =
3559                 ref_cache[-1 +  8] =
3560                 ref_cache[-1 + 16] =
3561                 ref_cache[-1 + 24] = LIST_NOT_USED;
3562             }
3563         }
3564     }
3565
3566     if (!USES_LIST(mb_type, list)) {
3567         fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3568         AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3569         AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3570         AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3571         AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3572         return;
3573     }
3574
3575     {
3576         int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
3577         int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3578         uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3579         uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3580         AV_WN32A(&ref_cache[0 * 8], ref01);
3581         AV_WN32A(&ref_cache[1 * 8], ref01);
3582         AV_WN32A(&ref_cache[2 * 8], ref23);
3583         AV_WN32A(&ref_cache[3 * 8], ref23);
3584     }
3585
3586     {
3587         int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
3588         AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3589         AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3590         AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3591         AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3592     }
3593 }
3594
3595 /**
3596  *
3597  * @return non zero if the loop filter can be skipped
3598  */
3599 static int fill_filter_caches(H264Context *h, int mb_type)
3600 {
3601     MpegEncContext *const s = &h->s;
3602     const int mb_xy = h->mb_xy;
3603     int top_xy, left_xy[LEFT_MBS];
3604     int top_type, left_type[LEFT_MBS];
3605     uint8_t *nnz;
3606     uint8_t *nnz_cache;
3607
3608     top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3609
3610     /* Wow, what a mess, why didn't they simplify the interlacing & intra
3611      * stuff, I can't imagine that these complex rules are worth it. */
3612
3613     left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3614     if (FRAME_MBAFF) {
3615         const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3616         const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3617         if (s->mb_y & 1) {
3618             if (left_mb_field_flag != curr_mb_field_flag)
3619                 left_xy[LTOP] -= s->mb_stride;
3620         } else {
3621             if (curr_mb_field_flag)
3622                 top_xy += s->mb_stride &
3623                     (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3624             if (left_mb_field_flag != curr_mb_field_flag)
3625                 left_xy[LBOT] += s->mb_stride;
3626         }
3627     }
3628
3629     h->top_mb_xy        = top_xy;
3630     h->left_mb_xy[LTOP] = left_xy[LTOP];
3631     h->left_mb_xy[LBOT] = left_xy[LBOT];
3632     {
3633         /* For sufficiently low qp, filtering wouldn't do anything.
3634          * This is a conservative estimate: could also check beta_offset
3635          * and more accurate chroma_qp. */
3636         int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3637         int qp        = s->current_picture.f.qscale_table[mb_xy];
3638         if (qp <= qp_thresh &&
3639             (left_xy[LTOP] < 0 ||
3640              ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3641             (top_xy < 0 ||
3642              ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3643             if (!FRAME_MBAFF)
3644                 return 1;
3645             if ((left_xy[LTOP] < 0 ||
3646                  ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3647                 (top_xy < s->mb_stride ||
3648                  ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3649                 return 1;
3650         }
3651     }
3652
3653     top_type        = s->current_picture.f.mb_type[top_xy];
3654     left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3655     left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3656     if (h->deblocking_filter == 2) {
3657         if (h->slice_table[top_xy] != h->slice_num)
3658             top_type = 0;
3659         if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3660             left_type[LTOP] = left_type[LBOT] = 0;
3661     } else {
3662         if (h->slice_table[top_xy] == 0xFFFF)
3663             top_type = 0;
3664         if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3665             left_type[LTOP] = left_type[LBOT] = 0;
3666     }
3667     h->top_type        = top_type;
3668     h->left_type[LTOP] = left_type[LTOP];
3669     h->left_type[LBOT] = left_type[LBOT];
3670
3671     if (IS_INTRA(mb_type))
3672         return 0;
3673
3674     fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3675                              top_type, left_type, mb_xy, 0);
3676     if (h->list_count == 2)
3677         fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3678                                  top_type, left_type, mb_xy, 1);
3679
3680     nnz       = h->non_zero_count[mb_xy];
3681     nnz_cache = h->non_zero_count_cache;
3682     AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3683     AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3684     AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3685     AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3686     h->cbp = h->cbp_table[mb_xy];
3687
3688     if (top_type) {
3689         nnz = h->non_zero_count[top_xy];
3690         AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3691     }
3692
3693     if (left_type[LTOP]) {
3694         nnz = h->non_zero_count[left_xy[LTOP]];
3695         nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3696         nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3697         nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3698         nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3699     }
3700
3701     /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3702      * from what the loop filter needs */
3703     if (!CABAC && h->pps.transform_8x8_mode) {
3704         if (IS_8x8DCT(top_type)) {
3705             nnz_cache[4 + 8 * 0]     =
3706                 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3707             nnz_cache[6 + 8 * 0]     =
3708                 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3709         }
3710         if (IS_8x8DCT(left_type[LTOP])) {
3711             nnz_cache[3 + 8 * 1]     =
3712                 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3713         }
3714         if (IS_8x8DCT(left_type[LBOT])) {
3715             nnz_cache[3 + 8 * 3]     =
3716                 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3717         }
3718
3719         if (IS_8x8DCT(mb_type)) {
3720             nnz_cache[scan8[0]] =
3721             nnz_cache[scan8[1]] =
3722             nnz_cache[scan8[2]] =
3723             nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3724
3725             nnz_cache[scan8[0 + 4]] =
3726             nnz_cache[scan8[1 + 4]] =
3727             nnz_cache[scan8[2 + 4]] =
3728             nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3729
3730             nnz_cache[scan8[0 + 8]] =
3731             nnz_cache[scan8[1 + 8]] =
3732             nnz_cache[scan8[2 + 8]] =
3733             nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3734
3735             nnz_cache[scan8[0 + 12]] =
3736             nnz_cache[scan8[1 + 12]] =
3737             nnz_cache[scan8[2 + 12]] =
3738             nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3739         }
3740     }
3741
3742     return 0;
3743 }
3744
3745 static void loop_filter(H264Context *h, int start_x, int end_x)
3746 {
3747     MpegEncContext *const s = &h->s;
3748     uint8_t *dest_y, *dest_cb, *dest_cr;
3749     int linesize, uvlinesize, mb_x, mb_y;
3750     const int end_mb_y       = s->mb_y + FRAME_MBAFF;
3751     const int old_slice_type = h->slice_type;
3752     const int pixel_shift    = h->pixel_shift;
3753     const int block_h        = 16 >> s->chroma_y_shift;
3754
3755     if (h->deblocking_filter) {
3756         for (mb_x = start_x; mb_x < end_x; mb_x++)
3757             for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
3758                 int mb_xy, mb_type;
3759                 mb_xy         = h->mb_xy = mb_x + mb_y * s->mb_stride;
3760                 h->slice_num  = h->slice_table[mb_xy];
3761                 mb_type       = s->current_picture.f.mb_type[mb_xy];
3762                 h->list_count = h->list_counts[mb_xy];
3763
3764                 if (FRAME_MBAFF)
3765                     h->mb_mbaff               =
3766                     h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3767
3768                 s->mb_x = mb_x;
3769                 s->mb_y = mb_y;
3770                 dest_y  = s->current_picture.f.data[0] +
3771                           ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
3772                 dest_cb = s->current_picture.f.data[1] +
3773                           (mb_x << pixel_shift) * (8 << CHROMA444) +
3774                           mb_y * s->uvlinesize * block_h;
3775                 dest_cr = s->current_picture.f.data[2] +
3776                           (mb_x << pixel_shift) * (8 << CHROMA444) +
3777                           mb_y * s->uvlinesize * block_h;
3778                 // FIXME simplify above
3779
3780                 if (MB_FIELD) {
3781                     linesize   = h->mb_linesize   = s->linesize   * 2;
3782                     uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3783                     if (mb_y & 1) { // FIXME move out of this function?
3784                         dest_y  -= s->linesize   * 15;
3785                         dest_cb -= s->uvlinesize * (block_h - 1);
3786                         dest_cr -= s->uvlinesize * (block_h - 1);
3787                     }
3788                 } else {
3789                     linesize   = h->mb_linesize   = s->linesize;
3790                     uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3791                 }
3792                 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
3793                                  uvlinesize, 0);
3794                 if (fill_filter_caches(h, mb_type))
3795                     continue;
3796                 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3797                 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3798
3799                 if (FRAME_MBAFF) {
3800                     ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
3801                                       linesize, uvlinesize);
3802                 } else {
3803                     ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
3804                                            dest_cr, linesize, uvlinesize);
3805                 }
3806             }
3807     }
3808     h->slice_type   = old_slice_type;
3809     s->mb_x         = end_x;
3810     s->mb_y         = end_mb_y - FRAME_MBAFF;
3811     h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3812     h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3813 }
3814
3815 static void predict_field_decoding_flag(H264Context *h)
3816 {
3817     MpegEncContext *const s = &h->s;
3818     const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
3819     int mb_type     = (h->slice_table[mb_xy - 1] == h->slice_num) ?
3820                       s->current_picture.f.mb_type[mb_xy - 1] :
3821                       (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
3822                       s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
3823     h->mb_mbaff     = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3824 }
3825
3826 /**
3827  * Draw edges and report progress for the last MB row.
3828  */
3829 static void decode_finish_row(H264Context *h)
3830 {
3831     MpegEncContext *const s = &h->s;
3832     int top            = 16 * (s->mb_y      >> FIELD_PICTURE);
3833     int pic_height     = 16 *  s->mb_height >> FIELD_PICTURE;
3834     int height         =  16      << FRAME_MBAFF;
3835     int deblock_border = (16 + 4) << FRAME_MBAFF;
3836
3837     if (h->deblocking_filter) {
3838         if ((top + height) >= pic_height)
3839             height += deblock_border;
3840         top -= deblock_border;
3841     }
3842
3843     if (top >= pic_height || (top + height) < h->emu_edge_height)
3844         return;
3845
3846     height = FFMIN(height, pic_height - top);
3847     if (top < h->emu_edge_height) {
3848         height = top + height;
3849         top    = 0;
3850     }
3851
3852     ff_draw_horiz_band(s, top, height);
3853
3854     if (s->dropable)
3855         return;
3856
3857     ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
3858                               s->picture_structure == PICT_BOTTOM_FIELD);
3859 }
3860
3861 static int decode_slice(struct AVCodecContext *avctx, void *arg)
3862 {
3863     H264Context *h = *(void **)arg;
3864     MpegEncContext *const s = &h->s;
3865     const int part_mask     = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
3866                                                    : 0x7F;
3867     int lf_x_start = s->mb_x;
3868
3869     s->mb_skip_run = -1;
3870
3871     h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
3872                     s->codec_id != CODEC_ID_H264 ||
3873                     (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
3874
3875     if (h->pps.cabac) {
3876         /* realign */
3877         align_get_bits(&s->gb);
3878
3879         /* init cabac */
3880         ff_init_cabac_states(&h->cabac);
3881         ff_init_cabac_decoder(&h->cabac,
3882                               s->gb.buffer + get_bits_count(&s->gb) / 8,
3883                               (get_bits_left(&s->gb) + 7) / 8);
3884
3885         ff_h264_init_cabac_states(h);
3886
3887         for (;;) {
3888             // START_TIMER
3889             int ret = ff_h264_decode_mb_cabac(h);
3890             int eos;
3891             // STOP_TIMER("decode_mb_cabac")
3892
3893             if (ret >= 0)
3894                 ff_h264_hl_decode_mb(h);
3895
3896             // FIXME optimal? or let mb_decode decode 16x32 ?
3897             if (ret >= 0 && FRAME_MBAFF) {
3898                 s->mb_y++;
3899
3900                 ret = ff_h264_decode_mb_cabac(h);
3901
3902                 if (ret >= 0)
3903                     ff_h264_hl_decode_mb(h);
3904                 s->mb_y--;
3905             }
3906             eos = get_cabac_terminate(&h->cabac);
3907
3908             if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
3909                 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3910                 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3911                                 s->mb_y, ER_MB_END & part_mask);
3912                 if (s->mb_x >= lf_x_start)
3913                     loop_filter(h, lf_x_start, s->mb_x + 1);
3914                 return 0;
3915             }
3916             if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3917                 av_log(h->s.avctx, AV_LOG_ERROR,
3918                        "error while decoding MB %d %d, bytestream (%td)\n",
3919                        s->mb_x, s->mb_y,
3920                        h->cabac.bytestream_end - h->cabac.bytestream);
3921                 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3922                                 s->mb_y, ER_MB_ERROR & part_mask);
3923                 return -1;
3924             }
3925
3926             if (++s->mb_x >= s->mb_width) {
3927                 loop_filter(h, lf_x_start, s->mb_x);
3928                 s->mb_x = lf_x_start = 0;
3929                 decode_finish_row(h);
3930                 ++s->mb_y;
3931                 if (FIELD_OR_MBAFF_PICTURE) {
3932                     ++s->mb_y;
3933                     if (FRAME_MBAFF && s->mb_y < s->mb_height)
3934                         predict_field_decoding_flag(h);
3935                 }
3936             }
3937
3938             if (eos || s->mb_y >= s->mb_height) {
3939                 tprintf(s->avctx, "slice end %d %d\n",
3940                         get_bits_count(&s->gb), s->gb.size_in_bits);
3941                 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3942                                 s->mb_y, ER_MB_END & part_mask);
3943                 if (s->mb_x > lf_x_start)
3944                     loop_filter(h, lf_x_start, s->mb_x);
3945                 return 0;
3946             }
3947         }
3948     } else {
3949         for (;;) {
3950             int ret = ff_h264_decode_mb_cavlc(h);
3951
3952             if (ret >= 0)
3953                 ff_h264_hl_decode_mb(h);
3954
3955             // FIXME optimal? or let mb_decode decode 16x32 ?
3956             if (ret >= 0 && FRAME_MBAFF) {
3957                 s->mb_y++;
3958                 ret = ff_h264_decode_mb_cavlc(h);
3959
3960                 if (ret >= 0)
3961                     ff_h264_hl_decode_mb(h);
3962                 s->mb_y--;
3963             }
3964
3965             if (ret < 0) {
3966                 av_log(h->s.avctx, AV_LOG_ERROR,
3967                        "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3968                 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3969                                 s->mb_y, ER_MB_ERROR & part_mask);
3970                 return -1;
3971             }
3972
3973             if (++s->mb_x >= s->mb_width) {
3974                 loop_filter(h, lf_x_start, s->mb_x);
3975                 s->mb_x = lf_x_start = 0;
3976                 decode_finish_row(h);
3977                 ++s->mb_y;
3978                 if (FIELD_OR_MBAFF_PICTURE) {
3979                     ++s->mb_y;
3980                     if (FRAME_MBAFF && s->mb_y < s->mb_height)
3981                         predict_field_decoding_flag(h);
3982                 }
3983                 if (s->mb_y >= s->mb_height) {
3984                     tprintf(s->avctx, "slice end %d %d\n",
3985                             get_bits_count(&s->gb), s->gb.size_in_bits);
3986
3987                     if (get_bits_left(&s->gb) == 0) {
3988                         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3989                                         s->mb_x - 1, s->mb_y,
3990                                         ER_MB_END & part_mask);
3991
3992                         return 0;
3993                     } else {
3994                         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3995                                         s->mb_x, s->mb_y,
3996                                         ER_MB_END & part_mask);
3997
3998                         return -1;
3999                     }
4000                 }
4001             }
4002
4003             if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
4004                 tprintf(s->avctx, "slice end %d %d\n",
4005                         get_bits_count(&s->gb), s->gb.size_in_bits);
4006                 if (get_bits_left(&s->gb) == 0) {
4007                     ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
4008                                     s->mb_x - 1, s->mb_y,
4009                                     ER_MB_END & part_mask);
4010                     if (s->mb_x > lf_x_start)
4011                         loop_filter(h, lf_x_start, s->mb_x);
4012
4013                     return 0;
4014                 } else {
4015                     ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
4016                                     s->mb_y, ER_MB_ERROR & part_mask);
4017
4018                     return -1;
4019                 }
4020             }
4021         }
4022     }
4023 }
4024
4025 /**
4026  * Call decode_slice() for each context.
4027  *
4028  * @param h h264 master context
4029  * @param context_count number of contexts to execute
4030  */
4031 static int execute_decode_slices(H264Context *h, int context_count)
4032 {
4033     MpegEncContext *const s     = &h->s;
4034     AVCodecContext *const avctx = s->avctx;
4035     H264Context *hx;
4036     int i;
4037
4038     if (s->avctx->hwaccel ||
4039         s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4040         return 0;
4041     if (context_count == 1) {
4042         return decode_slice(avctx, &h);
4043     } else {
4044         for (i = 1; i < context_count; i++) {
4045             hx                    = h->thread_context[i];
4046             hx->s.err_recognition = avctx->err_recognition;
4047             hx->s.error_count     = 0;
4048         }
4049
4050         avctx->execute(avctx, decode_slice, h->thread_context,
4051                        NULL, context_count, sizeof(void *));
4052
4053         /* pull back stuff from slices to master context */
4054         hx                   = h->thread_context[context_count - 1];
4055         s->mb_x              = hx->s.mb_x;
4056         s->mb_y              = hx->s.mb_y;
4057         s->dropable          = hx->s.dropable;
4058         s->picture_structure = hx->s.picture_structure;
4059         for (i = 1; i < context_count; i++)
4060             h->s.error_count += h->thread_context[i]->s.error_count;
4061     }
4062
4063     return 0;
4064 }
4065
4066 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
4067 {
4068     MpegEncContext *const s     = &h->s;
4069     AVCodecContext *const avctx = s->avctx;
4070     H264Context *hx; ///< thread context
4071     int buf_index;
4072     int context_count;
4073     int next_avc;
4074     int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4075     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4076     int nal_index;
4077
4078     h->max_contexts = s->slice_context_count;
4079     if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
4080         h->current_slice = 0;
4081         if (!s->first_field)
4082             s->current_picture_ptr = NULL;
4083         ff_h264_reset_sei(h);
4084     }
4085
4086     for (; pass <= 1; pass++) {
4087         buf_index     = 0;
4088         context_count = 0;
4089         next_avc      = h->is_avc ? 0 : buf_size;
4090         nal_index     = 0;
4091         for (;;) {
4092             int consumed;
4093             int dst_length;
4094             int bit_length;
4095             const uint8_t *ptr;
4096             int i, nalsize = 0;
4097             int err;
4098
4099             if (buf_index >= next_avc) {
4100                 if (buf_index >= buf_size - h->nal_length_size)
4101                     break;
4102                 nalsize = 0;
4103                 for (i = 0; i < h->nal_length_size; i++)
4104                     nalsize = (nalsize << 8) | buf[buf_index++];
4105                 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4106                     av_log(h->s.avctx, AV_LOG_ERROR,
4107                            "AVC: nal size %d\n", nalsize);
4108                     break;
4109                 }
4110                 next_avc = buf_index + nalsize;
4111             } else {
4112                 // start code prefix search
4113                 for (; buf_index + 3 < next_avc; buf_index++)
4114                     // This should always succeed in the first iteration.
4115                     if (buf[buf_index]     == 0 &&
4116                         buf[buf_index + 1] == 0 &&
4117                         buf[buf_index + 2] == 1)
4118                         break;
4119
4120                 if (buf_index + 3 >= buf_size)
4121                     break;
4122
4123                 buf_index += 3;
4124                 if (buf_index >= next_avc)
4125                     continue;
4126             }
4127
4128             hx = h->thread_context[context_count];
4129
4130             ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4131                                      &consumed, next_avc - buf_index);
4132             if (ptr == NULL || dst_length < 0)
4133                 return -1;
4134             i = buf_index + consumed;
4135             if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4136                 buf[i]     == 0x00 && buf[i + 1] == 0x00 &&
4137                 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4138                 s->workaround_bugs |= FF_BUG_TRUNCATED;
4139
4140             if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
4141                 while (ptr[dst_length - 1] == 0 && dst_length > 0)
4142                     dst_length--;
4143             bit_length = !dst_length ? 0
4144                                      : (8 * dst_length -
4145                                         ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
4146
4147             if (s->avctx->debug & FF_DEBUG_STARTCODE)
4148                 av_log(h->s.avctx, AV_LOG_DEBUG,
4149                        "NAL %d at %d/%d length %d\n",
4150                        hx->nal_unit_type, buf_index, buf_size, dst_length);
4151
4152             if (h->is_avc && (nalsize != consumed) && nalsize)
4153                 av_log(h->s.avctx, AV_LOG_DEBUG,
4154                        "AVC: Consumed only %d bytes instead of %d\n",
4155                        consumed, nalsize);
4156
4157             buf_index += consumed;
4158             nal_index++;
4159
4160             if (pass == 0) {
4161                 /* packets can sometimes contain multiple PPS/SPS,
4162                  * e.g. two PAFF field pictures in one packet, or a demuxer
4163                  * which splits NALs strangely if so, when frame threading we
4164                  * can't start the next thread until we've read all of them */
4165                 switch (hx->nal_unit_type) {
4166                 case NAL_SPS:
4167                 case NAL_PPS:
4168                     nals_needed = nal_index;
4169                     break;
4170                 case NAL_IDR_SLICE:
4171                 case NAL_SLICE:
4172                     init_get_bits(&hx->s.gb, ptr, bit_length);
4173                     if (!get_ue_golomb(&hx->s.gb))
4174                         nals_needed = nal_index;
4175                 }
4176                 continue;
4177             }
4178
4179             // FIXME do not discard SEI id
4180             if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
4181                 continue;
4182
4183 again:
4184             err = 0;
4185             switch (hx->nal_unit_type) {
4186             case NAL_IDR_SLICE:
4187                 if (h->nal_unit_type != NAL_IDR_SLICE) {
4188                     av_log(h->s.avctx, AV_LOG_ERROR,
4189                            "Invalid mix of idr and non-idr slices");
4190                     return -1;
4191                 }
4192                 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4193             case NAL_SLICE:
4194                 init_get_bits(&hx->s.gb, ptr, bit_length);
4195                 hx->intra_gb_ptr        =
4196                     hx->inter_gb_ptr    = &hx->s.gb;
4197                 hx->s.data_partitioning = 0;
4198
4199                 if ((err = decode_slice_header(hx, h)))
4200                     break;
4201
4202                 s->current_picture_ptr->f.key_frame |=
4203                     (hx->nal_unit_type == NAL_IDR_SLICE) ||
4204                     (h->sei_recovery_frame_cnt >= 0);
4205
4206                 if (h->current_slice == 1) {
4207                     if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
4208                         decode_postinit(h, nal_index >= nals_needed);
4209
4210                     if (s->avctx->hwaccel &&
4211                         s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
4212                         return -1;
4213                     if (CONFIG_H264_VDPAU_DECODER &&
4214                         s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4215                         ff_vdpau_h264_picture_start(s);
4216                 }
4217
4218                 if (hx->redundant_pic_count == 0 &&
4219                     (avctx->skip_frame < AVDISCARD_NONREF ||
4220                      hx->nal_ref_idc) &&
4221                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
4222                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4223                     (avctx->skip_frame < AVDISCARD_NONKEY ||
4224                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4225                     avctx->skip_frame < AVDISCARD_ALL) {
4226                     if (avctx->hwaccel) {
4227                         if (avctx->hwaccel->decode_slice(avctx,
4228                                                          &buf[buf_index - consumed],
4229                                                          consumed) < 0)
4230                             return -1;
4231                     } else if (CONFIG_H264_VDPAU_DECODER &&
4232                                s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4233                         static const uint8_t start_code[] = {
4234                             0x00, 0x00, 0x01 };
4235                         ff_vdpau_add_data_chunk(s, start_code,
4236                                                 sizeof(start_code));
4237                         ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
4238                                                 consumed);
4239                     } else
4240                         context_count++;
4241                 }
4242                 break;
4243             case NAL_DPA:
4244                 init_get_bits(&hx->s.gb, ptr, bit_length);
4245                 hx->intra_gb_ptr =
4246                 hx->inter_gb_ptr = NULL;
4247
4248                 if ((err = decode_slice_header(hx, h)) < 0)
4249                     break;
4250
4251                 hx->s.data_partitioning = 1;
4252                 break;
4253             case NAL_DPB:
4254                 init_get_bits(&hx->intra_gb, ptr, bit_length);
4255                 hx->intra_gb_ptr = &hx->intra_gb;
4256                 break;
4257             case NAL_DPC:
4258                 init_get_bits(&hx->inter_gb, ptr, bit_length);
4259                 hx->inter_gb_ptr = &hx->inter_gb;
4260
4261                 if (hx->redundant_pic_count == 0 &&
4262                     hx->intra_gb_ptr &&
4263                     hx->s.data_partitioning &&
4264                     s->context_initialized &&
4265                     (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4266                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
4267                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4268                     (avctx->skip_frame < AVDISCARD_NONKEY ||
4269                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4270                     avctx->skip_frame < AVDISCARD_ALL)
4271                     context_count++;
4272                 break;
4273             case NAL_SEI:
4274                 init_get_bits(&s->gb, ptr, bit_length);
4275                 ff_h264_decode_sei(h);
4276                 break;
4277             case NAL_SPS:
4278                 init_get_bits(&s->gb, ptr, bit_length);
4279                 if (ff_h264_decode_seq_parameter_set(h) < 0 &&
4280                     h->is_avc && (nalsize != consumed) && nalsize) {
4281                     av_log(h->s.avctx, AV_LOG_DEBUG,
4282                            "SPS decoding failure, try parsing the coomplete NAL\n");
4283                     init_get_bits(&s->gb, buf + buf_index + 1 - consumed,
4284                                   8 * (nalsize - 1));
4285                     ff_h264_decode_seq_parameter_set(h);
4286                 }
4287
4288                 if (s->flags & CODEC_FLAG_LOW_DELAY ||
4289                     (h->sps.bitstream_restriction_flag &&
4290                      !h->sps.num_reorder_frames))
4291                     s->low_delay = 1;
4292
4293                 if (avctx->has_b_frames < 2)
4294                     avctx->has_b_frames = !s->low_delay;
4295
4296                 if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
4297                     h->cur_chroma_format_idc   != h->sps.chroma_format_idc) {
4298                     if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
4299                         avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
4300                         h->cur_chroma_format_idc   = h->sps.chroma_format_idc;
4301                         h->pixel_shift             = h->sps.bit_depth_luma > 8;
4302
4303                         ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
4304                                         h->sps.chroma_format_idc);
4305                         ff_h264_pred_init(&h->hpc, s->codec_id,
4306                                           h->sps.bit_depth_luma,
4307                                           h->sps.chroma_format_idc);
4308                         s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
4309                         ff_dsputil_init(&s->dsp, s->avctx);
4310                     } else {
4311                         av_log(avctx, AV_LOG_ERROR,
4312                                "Unsupported bit depth: %d\n",
4313                                h->sps.bit_depth_luma);
4314                         return -1;
4315                     }
4316                 }
4317                 break;
4318             case NAL_PPS:
4319                 init_get_bits(&s->gb, ptr, bit_length);
4320                 ff_h264_decode_picture_parameter_set(h, bit_length);
4321                 break;
4322             case NAL_AUD:
4323             case NAL_END_SEQUENCE:
4324             case NAL_END_STREAM:
4325             case NAL_FILLER_DATA:
4326             case NAL_SPS_EXT:
4327             case NAL_AUXILIARY_SLICE:
4328                 break;
4329             default:
4330                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4331                        hx->nal_unit_type, bit_length);
4332             }
4333
4334             if (context_count == h->max_contexts) {
4335                 execute_decode_slices(h, context_count);
4336                 context_count = 0;
4337             }
4338
4339             if (err < 0)
4340                 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4341             else if (err == 1) {
4342                 /* Slice could not be decoded in parallel mode, copy down
4343                  * NAL unit stuff to context 0 and restart. Note that
4344                  * rbsp_buffer is not transferred, but since we no longer
4345                  * run in parallel mode this should not be an issue. */
4346                 h->nal_unit_type = hx->nal_unit_type;
4347                 h->nal_ref_idc   = hx->nal_ref_idc;
4348                 hx               = h;
4349                 goto again;
4350             }
4351         }
4352     }
4353     if (context_count)
4354         execute_decode_slices(h, context_count);
4355     return buf_index;
4356 }
4357
4358 /**
4359  * Return the number of bytes consumed for building the current frame.
4360  */
4361 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
4362 {
4363     if (pos == 0)
4364         pos = 1;          // avoid infinite loops (i doubt that is needed but ...)
4365     if (pos + 10 > buf_size)
4366         pos = buf_size;                   // oops ;)
4367
4368     return pos;
4369 }
4370
4371 static int decode_frame(AVCodecContext *avctx, void *data,
4372                         int *data_size, AVPacket *avpkt)
4373 {
4374     const uint8_t *buf = avpkt->data;
4375     int buf_size       = avpkt->size;
4376     H264Context *h     = avctx->priv_data;
4377     MpegEncContext *s  = &h->s;
4378     AVFrame *pict      = data;
4379     int buf_index      = 0;
4380
4381     s->flags  = avctx->flags;
4382     s->flags2 = avctx->flags2;
4383
4384     /* end of stream, output what is still in the buffers */
4385 out:
4386     if (buf_size == 0) {
4387         Picture *out;
4388         int i, out_idx;
4389
4390         s->current_picture_ptr = NULL;
4391
4392         // FIXME factorize this with the output code below
4393         out     = h->delayed_pic[0];
4394         out_idx = 0;
4395         for (i = 1;
4396              h->delayed_pic[i] &&
4397              !h->delayed_pic[i]->f.key_frame &&
4398              !h->delayed_pic[i]->mmco_reset;
4399              i++)
4400             if (h->delayed_pic[i]->poc < out->poc) {
4401                 out     = h->delayed_pic[i];
4402                 out_idx = i;
4403             }
4404
4405         for (i = out_idx; h->delayed_pic[i]; i++)
4406             h->delayed_pic[i] = h->delayed_pic[i + 1];
4407
4408         if (out) {
4409             *data_size = sizeof(AVFrame);
4410             *pict      = out->f;
4411         }
4412
4413         return buf_index;
4414     }
4415
4416     buf_index = decode_nal_units(h, buf, buf_size);
4417     if (buf_index < 0)
4418         return -1;
4419
4420     if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4421         buf_size = 0;
4422         goto out;
4423     }
4424
4425     if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
4426         if (avctx->skip_frame >= AVDISCARD_NONREF)
4427             return 0;
4428         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4429         return -1;
4430     }
4431
4432     if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
4433         (s->mb_y >= s->mb_height && s->mb_height)) {
4434         if (s->flags2 & CODEC_FLAG2_CHUNKS)
4435             decode_postinit(h, 1);
4436
4437         field_end(h, 0);
4438
4439         if (!h->next_output_pic) {
4440             /* Wait for second field. */
4441             *data_size = 0;
4442         } else {
4443             *data_size = sizeof(AVFrame);
4444             *pict      = h->next_output_pic->f;
4445         }
4446     }
4447
4448     assert(pict->data[0] || !*data_size);
4449     ff_print_debug_info(s, pict);
4450     // printf("out %d\n", (int)pict->data[0]);
4451
4452     return get_consumed_bytes(s, buf_index, buf_size);
4453 }
4454
4455 av_cold void ff_h264_free_context(H264Context *h)
4456 {
4457     int i;
4458
4459     free_tables(h, 1); // FIXME cleanup init stuff perhaps
4460
4461     for (i = 0; i < MAX_SPS_COUNT; i++)
4462         av_freep(h->sps_buffers + i);
4463
4464     for (i = 0; i < MAX_PPS_COUNT; i++)
4465         av_freep(h->pps_buffers + i);
4466 }
4467
4468 av_cold int ff_h264_decode_end(AVCodecContext *avctx)
4469 {
4470     H264Context *h    = avctx->priv_data;
4471     MpegEncContext *s = &h->s;
4472
4473     ff_h264_free_context(h);
4474
4475     ff_MPV_common_end(s);
4476
4477     // memset(h, 0, sizeof(H264Context));
4478
4479     return 0;
4480 }
4481
4482 static const AVProfile profiles[] = {
4483     { FF_PROFILE_H264_BASELINE,             "Baseline"              },
4484     { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
4485     { FF_PROFILE_H264_MAIN,                 "Main"                  },
4486     { FF_PROFILE_H264_EXTENDED,             "Extended"              },
4487     { FF_PROFILE_H264_HIGH,                 "High"                  },
4488     { FF_PROFILE_H264_HIGH_10,              "High 10"               },
4489     { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
4490     { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
4491     { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
4492     { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
4493     { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
4494     { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
4495     { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
4496     { FF_PROFILE_UNKNOWN },
4497 };
4498
4499 AVCodec ff_h264_decoder = {
4500     .name                  = "h264",
4501     .type                  = AVMEDIA_TYPE_VIDEO,
4502     .id                    = CODEC_ID_H264,
4503     .priv_data_size        = sizeof(H264Context),
4504     .init                  = ff_h264_decode_init,
4505     .close                 = ff_h264_decode_end,
4506     .decode                = decode_frame,
4507     .capabilities          = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4508                              CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4509                              CODEC_CAP_FRAME_THREADS,
4510     .flush                 = flush_dpb,
4511     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4512     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4513     .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4514     .profiles              = NULL_IF_CONFIG_SMALL(profiles),
4515 };
4516
4517 #if CONFIG_H264_VDPAU_DECODER
4518 AVCodec ff_h264_vdpau_decoder = {
4519     .name           = "h264_vdpau",
4520     .type           = AVMEDIA_TYPE_VIDEO,
4521     .id             = CODEC_ID_H264,
4522     .priv_data_size = sizeof(H264Context),
4523     .init           = ff_h264_decode_init,
4524     .close          = ff_h264_decode_end,
4525     .decode         = decode_frame,
4526     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4527     .flush          = flush_dpb,
4528     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4529     .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_VDPAU_H264,
4530                                                    PIX_FMT_NONE},
4531     .profiles       = NULL_IF_CONFIG_SMALL(profiles),
4532 };
4533 #endif