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