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