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