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