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