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