]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
dsputil: Move RV40-specific bits into rv40dsp
[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/avassert.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/stereo3d.h"
31 #include "libavutil/timer.h"
32 #include "internal.h"
33 #include "cabac.h"
34 #include "cabac_functions.h"
35 #include "dsputil.h"
36 #include "error_resilience.h"
37 #include "avcodec.h"
38 #include "h264.h"
39 #include "h264data.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
42 #include "golomb.h"
43 #include "mathops.h"
44 #include "mpegutils.h"
45 #include "rectangle.h"
46 #include "svq3.h"
47 #include "thread.h"
48
49 #include <assert.h>
50
51 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
52
53 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
54                               int (*mv)[2][4][2],
55                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
56 {
57     H264Context *h = opaque;
58
59     h->mb_x  = mb_x;
60     h->mb_y  = mb_y;
61     h->mb_xy = mb_x + mb_y * h->mb_stride;
62     memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
63     assert(ref >= 0);
64     /* FIXME: It is possible albeit uncommon that slice references
65      * differ between slices. We take the easy approach and ignore
66      * it for now. If this turns out to have any relevance in
67      * practice then correct remapping should be added. */
68     if (ref >= h->ref_count[0])
69         ref = 0;
70     fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
71                    2, 2, 2, ref, 1);
72     fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
73     fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
74                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
75     assert(!FRAME_MBAFF(h));
76     ff_h264_hl_decode_mb(h);
77 }
78
79 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
80 {
81     AVCodecContext *avctx = h->avctx;
82     AVFrame *cur  = &h->cur_pic.f;
83     AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
84     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
85     int vshift = desc->log2_chroma_h;
86     const int field_pic = h->picture_structure != PICT_FRAME;
87     if (field_pic) {
88         height <<= 1;
89         y      <<= 1;
90     }
91
92     height = FFMIN(height, avctx->height - y);
93
94     if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
95         return;
96
97     if (avctx->draw_horiz_band) {
98         AVFrame *src;
99         int offset[AV_NUM_DATA_POINTERS];
100         int i;
101
102         if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
103             (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
104             src = cur;
105         else if (last)
106             src = last;
107         else
108             return;
109
110         offset[0] = y * src->linesize[0];
111         offset[1] =
112         offset[2] = (y >> vshift) * src->linesize[1];
113         for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
114             offset[i] = 0;
115
116         emms_c();
117
118         avctx->draw_horiz_band(avctx, src, offset,
119                                y, h->picture_structure, height);
120     }
121 }
122
123 /**
124  * Check if the top & left blocks are available if needed and
125  * change the dc mode so it only uses the available blocks.
126  */
127 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
128 {
129     static const int8_t top[12] = {
130         -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
131     };
132     static const int8_t left[12] = {
133         0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
134     };
135     int i;
136
137     if (!(h->top_samples_available & 0x8000)) {
138         for (i = 0; i < 4; i++) {
139             int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
140             if (status < 0) {
141                 av_log(h->avctx, AV_LOG_ERROR,
142                        "top block unavailable for requested intra4x4 mode %d at %d %d\n",
143                        status, h->mb_x, h->mb_y);
144                 return AVERROR_INVALIDDATA;
145             } else if (status) {
146                 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
147             }
148         }
149     }
150
151     if ((h->left_samples_available & 0x8888) != 0x8888) {
152         static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
153         for (i = 0; i < 4; i++)
154             if (!(h->left_samples_available & mask[i])) {
155                 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
156                 if (status < 0) {
157                     av_log(h->avctx, AV_LOG_ERROR,
158                            "left block unavailable for requested intra4x4 mode %d at %d %d\n",
159                            status, h->mb_x, h->mb_y);
160                     return AVERROR_INVALIDDATA;
161                 } else if (status) {
162                     h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
163                 }
164             }
165     }
166
167     return 0;
168 } // FIXME cleanup like ff_h264_check_intra_pred_mode
169
170 /**
171  * Check if the top & left blocks are available if needed and
172  * change the dc mode so it only uses the available blocks.
173  */
174 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
175 {
176     static const int8_t top[4]  = { LEFT_DC_PRED8x8, 1, -1, -1 };
177     static const int8_t left[5] = { TOP_DC_PRED8x8, -1,  2, -1, DC_128_PRED8x8 };
178
179     if (mode > 3U) {
180         av_log(h->avctx, AV_LOG_ERROR,
181                "out of range intra chroma pred mode at %d %d\n",
182                h->mb_x, h->mb_y);
183         return AVERROR_INVALIDDATA;
184     }
185
186     if (!(h->top_samples_available & 0x8000)) {
187         mode = top[mode];
188         if (mode < 0) {
189             av_log(h->avctx, AV_LOG_ERROR,
190                    "top block unavailable for requested intra mode at %d %d\n",
191                    h->mb_x, h->mb_y);
192             return AVERROR_INVALIDDATA;
193         }
194     }
195
196     if ((h->left_samples_available & 0x8080) != 0x8080) {
197         mode = left[mode];
198         if (is_chroma && (h->left_samples_available & 0x8080)) {
199             // mad cow disease mode, aka MBAFF + constrained_intra_pred
200             mode = ALZHEIMER_DC_L0T_PRED8x8 +
201                    (!(h->left_samples_available & 0x8000)) +
202                    2 * (mode == DC_128_PRED8x8);
203         }
204         if (mode < 0) {
205             av_log(h->avctx, AV_LOG_ERROR,
206                    "left block unavailable for requested intra mode at %d %d\n",
207                    h->mb_x, h->mb_y);
208             return AVERROR_INVALIDDATA;
209         }
210     }
211
212     return mode;
213 }
214
215 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
216                                   int *dst_length, int *consumed, int length)
217 {
218     int i, si, di;
219     uint8_t *dst;
220     int bufidx;
221
222     // src[0]&0x80; // forbidden bit
223     h->nal_ref_idc   = src[0] >> 5;
224     h->nal_unit_type = src[0] & 0x1F;
225
226     src++;
227     length--;
228
229 #define STARTCODE_TEST                                                  \
230     if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {         \
231         if (src[i + 2] != 3) {                                          \
232             /* startcode, so we must be past the end */                 \
233             length = i;                                                 \
234         }                                                               \
235         break;                                                          \
236     }
237
238 #if HAVE_FAST_UNALIGNED
239 #define FIND_FIRST_ZERO                                                 \
240     if (i > 0 && !src[i])                                               \
241         i--;                                                            \
242     while (src[i])                                                      \
243         i++
244
245 #if HAVE_FAST_64BIT
246     for (i = 0; i + 1 < length; i += 9) {
247         if (!((~AV_RN64A(src + i) &
248                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
249               0x8000800080008080ULL))
250             continue;
251         FIND_FIRST_ZERO;
252         STARTCODE_TEST;
253         i -= 7;
254     }
255 #else
256     for (i = 0; i + 1 < length; i += 5) {
257         if (!((~AV_RN32A(src + i) &
258                (AV_RN32A(src + i) - 0x01000101U)) &
259               0x80008080U))
260             continue;
261         FIND_FIRST_ZERO;
262         STARTCODE_TEST;
263         i -= 3;
264     }
265 #endif
266 #else
267     for (i = 0; i + 1 < length; i += 2) {
268         if (src[i])
269             continue;
270         if (i > 0 && src[i - 1] == 0)
271             i--;
272         STARTCODE_TEST;
273     }
274 #endif
275
276     if (i >= length - 1) { // no escaped 0
277         *dst_length = length;
278         *consumed   = length + 1; // +1 for the header
279         return src;
280     }
281
282     // use second escape buffer for inter data
283     bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
284     av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
285                    length + FF_INPUT_BUFFER_PADDING_SIZE);
286     dst = h->rbsp_buffer[bufidx];
287
288     if (dst == NULL)
289         return NULL;
290
291     memcpy(dst, src, i);
292     si = di = i;
293     while (si + 2 < length) {
294         // remove escapes (very rare 1:2^22)
295         if (src[si + 2] > 3) {
296             dst[di++] = src[si++];
297             dst[di++] = src[si++];
298         } else if (src[si] == 0 && src[si + 1] == 0) {
299             if (src[si + 2] == 3) { // escape
300                 dst[di++]  = 0;
301                 dst[di++]  = 0;
302                 si        += 3;
303                 continue;
304             } else // next start code
305                 goto nsc;
306         }
307
308         dst[di++] = src[si++];
309     }
310     while (si < length)
311         dst[di++] = src[si++];
312
313 nsc:
314     memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
315
316     *dst_length = di;
317     *consumed   = si + 1; // +1 for the header
318     /* FIXME store exact number of bits in the getbitcontext
319      * (it is needed for decoding) */
320     return dst;
321 }
322
323 /**
324  * Identify the exact end of the bitstream
325  * @return the length of the trailing, or 0 if damaged
326  */
327 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
328 {
329     int v = *src;
330     int r;
331
332     tprintf(h->avctx, "rbsp trailing %X\n", v);
333
334     for (r = 1; r < 9; r++) {
335         if (v & 1)
336             return r;
337         v >>= 1;
338     }
339     return 0;
340 }
341
342 void ff_h264_free_tables(H264Context *h, int free_rbsp)
343 {
344     int i;
345     H264Context *hx;
346
347     av_freep(&h->intra4x4_pred_mode);
348     av_freep(&h->chroma_pred_mode_table);
349     av_freep(&h->cbp_table);
350     av_freep(&h->mvd_table[0]);
351     av_freep(&h->mvd_table[1]);
352     av_freep(&h->direct_table);
353     av_freep(&h->non_zero_count);
354     av_freep(&h->slice_table_base);
355     h->slice_table = NULL;
356     av_freep(&h->list_counts);
357
358     av_freep(&h->mb2b_xy);
359     av_freep(&h->mb2br_xy);
360
361     av_buffer_pool_uninit(&h->qscale_table_pool);
362     av_buffer_pool_uninit(&h->mb_type_pool);
363     av_buffer_pool_uninit(&h->motion_val_pool);
364     av_buffer_pool_uninit(&h->ref_index_pool);
365
366     if (free_rbsp && h->DPB) {
367         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
368             ff_h264_unref_picture(h, &h->DPB[i]);
369         av_freep(&h->DPB);
370     } else if (h->DPB) {
371         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
372             h->DPB[i].needs_realloc = 1;
373     }
374
375     h->cur_pic_ptr = NULL;
376
377     for (i = 0; i < H264_MAX_THREADS; i++) {
378         hx = h->thread_context[i];
379         if (!hx)
380             continue;
381         av_freep(&hx->top_borders[1]);
382         av_freep(&hx->top_borders[0]);
383         av_freep(&hx->bipred_scratchpad);
384         av_freep(&hx->edge_emu_buffer);
385         av_freep(&hx->dc_val_base);
386         av_freep(&hx->er.mb_index2xy);
387         av_freep(&hx->er.error_status_table);
388         av_freep(&hx->er.er_temp_buffer);
389         av_freep(&hx->er.mbintra_table);
390         av_freep(&hx->er.mbskip_table);
391
392         if (free_rbsp) {
393             av_freep(&hx->rbsp_buffer[1]);
394             av_freep(&hx->rbsp_buffer[0]);
395             hx->rbsp_buffer_size[0] = 0;
396             hx->rbsp_buffer_size[1] = 0;
397         }
398         if (i)
399             av_freep(&h->thread_context[i]);
400     }
401 }
402
403 int ff_h264_alloc_tables(H264Context *h)
404 {
405     const int big_mb_num = h->mb_stride * (h->mb_height + 1);
406     const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
407     int x, y, i;
408
409     FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
410                       row_mb_num * 8 * sizeof(uint8_t), fail)
411     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
412                       big_mb_num * 48 * sizeof(uint8_t), fail)
413     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
414                       (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
415     FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
416                       big_mb_num * sizeof(uint16_t), fail)
417     FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
418                       big_mb_num * sizeof(uint8_t), fail)
419     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
420                       16 * row_mb_num * sizeof(uint8_t), fail);
421     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
422                       16 * row_mb_num * sizeof(uint8_t), fail);
423     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
424                       4 * big_mb_num * sizeof(uint8_t), fail);
425     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
426                       big_mb_num * sizeof(uint8_t), fail)
427
428     memset(h->slice_table_base, -1,
429            (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
430     h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
431
432     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
433                       big_mb_num * sizeof(uint32_t), fail);
434     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
435                       big_mb_num * sizeof(uint32_t), fail);
436     for (y = 0; y < h->mb_height; y++)
437         for (x = 0; x < h->mb_width; x++) {
438             const int mb_xy = x + y * h->mb_stride;
439             const int b_xy  = 4 * x + 4 * y * h->b_stride;
440
441             h->mb2b_xy[mb_xy]  = b_xy;
442             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
443         }
444
445     if (!h->dequant4_coeff[0])
446         h264_init_dequant_tables(h);
447
448     if (!h->DPB) {
449         h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
450         if (!h->DPB)
451             return AVERROR(ENOMEM);
452         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
453             av_frame_unref(&h->DPB[i].f);
454         av_frame_unref(&h->cur_pic.f);
455     }
456
457     return 0;
458
459 fail:
460     ff_h264_free_tables(h, 1);
461     return AVERROR(ENOMEM);
462 }
463
464 /**
465  * Init context
466  * Allocate buffers which are not shared amongst multiple threads.
467  */
468 int ff_h264_context_init(H264Context *h)
469 {
470     ERContext *er = &h->er;
471     int mb_array_size = h->mb_height * h->mb_stride;
472     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
473     int c_size  = h->mb_stride * (h->mb_height + 1);
474     int yc_size = y_size + 2   * c_size;
475     int x, y, i;
476
477     FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
478                       h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
479     FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
480                       h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
481
482     h->ref_cache[0][scan8[5]  + 1] =
483     h->ref_cache[0][scan8[7]  + 1] =
484     h->ref_cache[0][scan8[13] + 1] =
485     h->ref_cache[1][scan8[5]  + 1] =
486     h->ref_cache[1][scan8[7]  + 1] =
487     h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
488
489     if (CONFIG_ERROR_RESILIENCE) {
490         /* init ER */
491         er->avctx          = h->avctx;
492         er->dsp            = &h->dsp;
493         er->decode_mb      = h264_er_decode_mb;
494         er->opaque         = h;
495         er->quarter_sample = 1;
496
497         er->mb_num      = h->mb_num;
498         er->mb_width    = h->mb_width;
499         er->mb_height   = h->mb_height;
500         er->mb_stride   = h->mb_stride;
501         er->b8_stride   = h->mb_width * 2 + 1;
502
503         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
504                           fail); // error ressilience code looks cleaner with this
505         for (y = 0; y < h->mb_height; y++)
506             for (x = 0; x < h->mb_width; x++)
507                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
508
509         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
510                                                       h->mb_stride + h->mb_width;
511
512         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
513                           mb_array_size * sizeof(uint8_t), fail);
514
515         FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
516         memset(er->mbintra_table, 1, mb_array_size);
517
518         FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
519
520         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
521                          fail);
522
523         FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
524         er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
525         er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
526         er->dc_val[2] = er->dc_val[1] + c_size;
527         for (i = 0; i < yc_size; i++)
528             h->dc_val_base[i] = 1024;
529     }
530
531     return 0;
532
533 fail:
534     return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
535 }
536
537 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
538                             int parse_extradata);
539
540 int ff_h264_decode_extradata(H264Context *h)
541 {
542     AVCodecContext *avctx = h->avctx;
543     int ret;
544
545     if (avctx->extradata[0] == 1) {
546         int i, cnt, nalsize;
547         unsigned char *p = avctx->extradata;
548
549         h->is_avc = 1;
550
551         if (avctx->extradata_size < 7) {
552             av_log(avctx, AV_LOG_ERROR,
553                    "avcC %d too short\n", avctx->extradata_size);
554             return AVERROR_INVALIDDATA;
555         }
556         /* sps and pps in the avcC always have length coded with 2 bytes,
557          * so put a fake nal_length_size = 2 while parsing them */
558         h->nal_length_size = 2;
559         // Decode sps from avcC
560         cnt = *(p + 5) & 0x1f; // Number of sps
561         p  += 6;
562         for (i = 0; i < cnt; i++) {
563             nalsize = AV_RB16(p) + 2;
564             if (p - avctx->extradata + nalsize > avctx->extradata_size)
565                 return AVERROR_INVALIDDATA;
566             ret = decode_nal_units(h, p, nalsize, 1);
567             if (ret < 0) {
568                 av_log(avctx, AV_LOG_ERROR,
569                        "Decoding sps %d from avcC failed\n", i);
570                 return ret;
571             }
572             p += nalsize;
573         }
574         // Decode pps from avcC
575         cnt = *(p++); // Number of pps
576         for (i = 0; i < cnt; i++) {
577             nalsize = AV_RB16(p) + 2;
578             if (p - avctx->extradata + nalsize > avctx->extradata_size)
579                 return AVERROR_INVALIDDATA;
580             ret = decode_nal_units(h, p, nalsize, 1);
581             if (ret < 0) {
582                 av_log(avctx, AV_LOG_ERROR,
583                        "Decoding pps %d from avcC failed\n", i);
584                 return ret;
585             }
586             p += nalsize;
587         }
588         // Now store right nal length size, that will be used to parse all other nals
589         h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
590     } else {
591         h->is_avc = 0;
592         ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
593         if (ret < 0)
594             return ret;
595     }
596     return 0;
597 }
598
599 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
600 {
601     H264Context *h = avctx->priv_data;
602     int i;
603     int ret;
604
605     h->avctx = avctx;
606
607     h->bit_depth_luma    = 8;
608     h->chroma_format_idc = 1;
609
610     ff_h264dsp_init(&h->h264dsp, 8, 1);
611     ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
612     ff_h264qpel_init(&h->h264qpel, 8);
613     ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
614
615     h->dequant_coeff_pps = -1;
616
617     /* needed so that IDCT permutation is known early */
618     if (CONFIG_ERROR_RESILIENCE)
619         ff_dsputil_init(&h->dsp, h->avctx);
620     ff_videodsp_init(&h->vdsp, 8);
621
622     memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
623     memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
624
625     h->picture_structure   = PICT_FRAME;
626     h->slice_context_count = 1;
627     h->workaround_bugs     = avctx->workaround_bugs;
628     h->flags               = avctx->flags;
629
630     /* set defaults */
631     // s->decode_mb = ff_h263_decode_mb;
632     if (!avctx->has_b_frames)
633         h->low_delay = 1;
634
635     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
636
637     ff_h264_decode_init_vlc();
638
639     ff_init_cabac_states();
640
641     h->pixel_shift        = 0;
642     h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
643
644     h->thread_context[0] = h;
645     h->outputed_poc      = h->next_outputed_poc = INT_MIN;
646     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
647         h->last_pocs[i] = INT_MIN;
648     h->prev_poc_msb = 1 << 16;
649     h->x264_build   = -1;
650     ff_h264_reset_sei(h);
651     h->recovery_frame = -1;
652     h->frame_recovered = 0;
653     if (avctx->codec_id == AV_CODEC_ID_H264) {
654         if (avctx->ticks_per_frame == 1)
655             h->avctx->time_base.den *= 2;
656         avctx->ticks_per_frame = 2;
657     }
658
659     if (avctx->extradata_size > 0 && avctx->extradata) {
660        ret = ff_h264_decode_extradata(h);
661        if (ret < 0)
662            return ret;
663     }
664
665     if (h->sps.bitstream_restriction_flag &&
666         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
667         h->avctx->has_b_frames = h->sps.num_reorder_frames;
668         h->low_delay           = 0;
669     }
670
671     avctx->internal->allocate_progress = 1;
672
673     return 0;
674 }
675
676 static int decode_init_thread_copy(AVCodecContext *avctx)
677 {
678     H264Context *h = avctx->priv_data;
679
680     if (!avctx->internal->is_copy)
681         return 0;
682     memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
683     memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
684
685     h->context_initialized = 0;
686
687     return 0;
688 }
689
690 /**
691  * Run setup operations that must be run after slice header decoding.
692  * This includes finding the next displayed frame.
693  *
694  * @param h h264 master context
695  * @param setup_finished enough NALs have been read that we can call
696  * ff_thread_finish_setup()
697  */
698 static void decode_postinit(H264Context *h, int setup_finished)
699 {
700     H264Picture *out = h->cur_pic_ptr;
701     H264Picture *cur = h->cur_pic_ptr;
702     int i, pics, out_of_order, out_idx;
703     int invalid = 0, cnt = 0;
704
705     h->cur_pic_ptr->f.pict_type = h->pict_type;
706
707     if (h->next_output_pic)
708         return;
709
710     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
711         /* FIXME: if we have two PAFF fields in one packet, we can't start
712          * the next thread here. If we have one field per packet, we can.
713          * The check in decode_nal_units() is not good enough to find this
714          * yet, so we assume the worst for now. */
715         // if (setup_finished)
716         //    ff_thread_finish_setup(h->avctx);
717         return;
718     }
719
720     cur->f.interlaced_frame = 0;
721     cur->f.repeat_pict      = 0;
722
723     /* Signal interlacing information externally. */
724     /* Prioritize picture timing SEI information over used
725      * decoding process if it exists. */
726
727     if (h->sps.pic_struct_present_flag) {
728         switch (h->sei_pic_struct) {
729         case SEI_PIC_STRUCT_FRAME:
730             break;
731         case SEI_PIC_STRUCT_TOP_FIELD:
732         case SEI_PIC_STRUCT_BOTTOM_FIELD:
733             cur->f.interlaced_frame = 1;
734             break;
735         case SEI_PIC_STRUCT_TOP_BOTTOM:
736         case SEI_PIC_STRUCT_BOTTOM_TOP:
737             if (FIELD_OR_MBAFF_PICTURE(h))
738                 cur->f.interlaced_frame = 1;
739             else
740                 // try to flag soft telecine progressive
741                 cur->f.interlaced_frame = h->prev_interlaced_frame;
742             break;
743         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
744         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
745             /* Signal the possibility of telecined film externally
746              * (pic_struct 5,6). From these hints, let the applications
747              * decide if they apply deinterlacing. */
748             cur->f.repeat_pict = 1;
749             break;
750         case SEI_PIC_STRUCT_FRAME_DOUBLING:
751             cur->f.repeat_pict = 2;
752             break;
753         case SEI_PIC_STRUCT_FRAME_TRIPLING:
754             cur->f.repeat_pict = 4;
755             break;
756         }
757
758         if ((h->sei_ct_type & 3) &&
759             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
760             cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
761     } else {
762         /* Derive interlacing flag from used decoding process. */
763         cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
764     }
765     h->prev_interlaced_frame = cur->f.interlaced_frame;
766
767     if (cur->field_poc[0] != cur->field_poc[1]) {
768         /* Derive top_field_first from field pocs. */
769         cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
770     } else {
771         if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
772             /* Use picture timing SEI information. Even if it is a
773              * information of a past frame, better than nothing. */
774             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
775                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
776                 cur->f.top_field_first = 1;
777             else
778                 cur->f.top_field_first = 0;
779         } else {
780             /* Most likely progressive */
781             cur->f.top_field_first = 0;
782         }
783     }
784
785     if (h->sei_frame_packing_present &&
786         h->frame_packing_arrangement_type >= 0 &&
787         h->frame_packing_arrangement_type <= 6 &&
788         h->content_interpretation_type > 0 &&
789         h->content_interpretation_type < 3) {
790         AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
791         if (!stereo)
792             return;
793
794         switch (h->frame_packing_arrangement_type) {
795         case 0:
796             stereo->type = AV_STEREO3D_CHECKERBOARD;
797             break;
798         case 1:
799             stereo->type = AV_STEREO3D_LINES;
800             break;
801         case 2:
802             stereo->type = AV_STEREO3D_COLUMNS;
803             break;
804         case 3:
805             if (h->quincunx_subsampling)
806                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
807             else
808                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
809             break;
810         case 4:
811             stereo->type = AV_STEREO3D_TOPBOTTOM;
812             break;
813         case 5:
814             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
815             break;
816         case 6:
817             stereo->type = AV_STEREO3D_2D;
818             break;
819         }
820
821         if (h->content_interpretation_type == 2)
822             stereo->flags = AV_STEREO3D_FLAG_INVERT;
823     }
824
825     // FIXME do something with unavailable reference frames
826
827     /* Sort B-frames into display order */
828
829     if (h->sps.bitstream_restriction_flag &&
830         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
831         h->avctx->has_b_frames = h->sps.num_reorder_frames;
832         h->low_delay           = 0;
833     }
834
835     if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
836         !h->sps.bitstream_restriction_flag) {
837         h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
838         h->low_delay           = 0;
839     }
840
841     pics = 0;
842     while (h->delayed_pic[pics])
843         pics++;
844
845     assert(pics <= MAX_DELAYED_PIC_COUNT);
846
847     h->delayed_pic[pics++] = cur;
848     if (cur->reference == 0)
849         cur->reference = DELAYED_PIC_REF;
850
851     /* Frame reordering. This code takes pictures from coding order and sorts
852      * them by their incremental POC value into display order. It supports POC
853      * gaps, MMCO reset codes and random resets.
854      * A "display group" can start either with a IDR frame (f.key_frame = 1),
855      * and/or can be closed down with a MMCO reset code. In sequences where
856      * there is no delay, we can't detect that (since the frame was already
857      * output to the user), so we also set h->mmco_reset to detect the MMCO
858      * reset code.
859      * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
860      * we increase the delay between input and output. All frames affected by
861      * the lag (e.g. those that should have been output before another frame
862      * that we already returned to the user) will be dropped. This is a bug
863      * that we will fix later. */
864     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
865         cnt     += out->poc < h->last_pocs[i];
866         invalid += out->poc == INT_MIN;
867     }
868     if (!h->mmco_reset && !cur->f.key_frame &&
869         cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
870         h->mmco_reset = 2;
871         if (pics > 1)
872             h->delayed_pic[pics - 2]->mmco_reset = 2;
873     }
874     if (h->mmco_reset || cur->f.key_frame) {
875         for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
876             h->last_pocs[i] = INT_MIN;
877         cnt     = 0;
878         invalid = MAX_DELAYED_PIC_COUNT;
879     }
880     out     = h->delayed_pic[0];
881     out_idx = 0;
882     for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
883                 h->delayed_pic[i] &&
884                 !h->delayed_pic[i - 1]->mmco_reset &&
885                 !h->delayed_pic[i]->f.key_frame;
886          i++)
887         if (h->delayed_pic[i]->poc < out->poc) {
888             out     = h->delayed_pic[i];
889             out_idx = i;
890         }
891     if (h->avctx->has_b_frames == 0 &&
892         (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
893         h->next_outputed_poc = INT_MIN;
894     out_of_order = !out->f.key_frame && !h->mmco_reset &&
895                    (out->poc < h->next_outputed_poc);
896
897     if (h->sps.bitstream_restriction_flag &&
898         h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
899     } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
900                h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
901         if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
902             h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
903         }
904         h->low_delay = 0;
905     } else if (h->low_delay &&
906                ((h->next_outputed_poc != INT_MIN &&
907                  out->poc > h->next_outputed_poc + 2) ||
908                 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
909         h->low_delay = 0;
910         h->avctx->has_b_frames++;
911     }
912
913     if (pics > h->avctx->has_b_frames) {
914         out->reference &= ~DELAYED_PIC_REF;
915         // for frame threading, the owner must be the second field's thread or
916         // else the first thread can release the picture and reuse it unsafely
917         for (i = out_idx; h->delayed_pic[i]; i++)
918             h->delayed_pic[i] = h->delayed_pic[i + 1];
919     }
920     memmove(h->last_pocs, &h->last_pocs[1],
921             sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
922     h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
923     if (!out_of_order && pics > h->avctx->has_b_frames) {
924         h->next_output_pic = out;
925         if (out->mmco_reset) {
926             if (out_idx > 0) {
927                 h->next_outputed_poc                    = out->poc;
928                 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
929             } else {
930                 h->next_outputed_poc = INT_MIN;
931             }
932         } else {
933             if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
934                 h->next_outputed_poc = INT_MIN;
935             } else {
936                 h->next_outputed_poc = out->poc;
937             }
938         }
939         h->mmco_reset = 0;
940     } else {
941         av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
942     }
943
944     if (h->next_output_pic) {
945         if (h->next_output_pic->recovered) {
946             // We have reached an recovery point and all frames after it in
947             // display order are "recovered".
948             h->frame_recovered |= FRAME_RECOVERED_SEI;
949         }
950         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
951     }
952
953     if (setup_finished && !h->avctx->hwaccel)
954         ff_thread_finish_setup(h->avctx);
955 }
956
957 int ff_pred_weight_table(H264Context *h)
958 {
959     int list, i;
960     int luma_def, chroma_def;
961
962     h->use_weight             = 0;
963     h->use_weight_chroma      = 0;
964     h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
965     if (h->sps.chroma_format_idc)
966         h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
967     luma_def   = 1 << h->luma_log2_weight_denom;
968     chroma_def = 1 << h->chroma_log2_weight_denom;
969
970     for (list = 0; list < 2; list++) {
971         h->luma_weight_flag[list]   = 0;
972         h->chroma_weight_flag[list] = 0;
973         for (i = 0; i < h->ref_count[list]; i++) {
974             int luma_weight_flag, chroma_weight_flag;
975
976             luma_weight_flag = get_bits1(&h->gb);
977             if (luma_weight_flag) {
978                 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
979                 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
980                 if (h->luma_weight[i][list][0] != luma_def ||
981                     h->luma_weight[i][list][1] != 0) {
982                     h->use_weight             = 1;
983                     h->luma_weight_flag[list] = 1;
984                 }
985             } else {
986                 h->luma_weight[i][list][0] = luma_def;
987                 h->luma_weight[i][list][1] = 0;
988             }
989
990             if (h->sps.chroma_format_idc) {
991                 chroma_weight_flag = get_bits1(&h->gb);
992                 if (chroma_weight_flag) {
993                     int j;
994                     for (j = 0; j < 2; j++) {
995                         h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
996                         h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
997                         if (h->chroma_weight[i][list][j][0] != chroma_def ||
998                             h->chroma_weight[i][list][j][1] != 0) {
999                             h->use_weight_chroma        = 1;
1000                             h->chroma_weight_flag[list] = 1;
1001                         }
1002                     }
1003                 } else {
1004                     int j;
1005                     for (j = 0; j < 2; j++) {
1006                         h->chroma_weight[i][list][j][0] = chroma_def;
1007                         h->chroma_weight[i][list][j][1] = 0;
1008                     }
1009                 }
1010             }
1011         }
1012         if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1013             break;
1014     }
1015     h->use_weight = h->use_weight || h->use_weight_chroma;
1016     return 0;
1017 }
1018
1019 /**
1020  * instantaneous decoder refresh.
1021  */
1022 static void idr(H264Context *h)
1023 {
1024     ff_h264_remove_all_refs(h);
1025     h->prev_frame_num        = 0;
1026     h->prev_frame_num_offset = 0;
1027     h->prev_poc_msb          =
1028     h->prev_poc_lsb          = 0;
1029 }
1030
1031 /* forget old pics after a seek */
1032 void ff_h264_flush_change(H264Context *h)
1033 {
1034     int i;
1035     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1036         h->last_pocs[i] = INT_MIN;
1037     h->outputed_poc          = h->next_outputed_poc = INT_MIN;
1038     h->prev_interlaced_frame = 1;
1039     idr(h);
1040     if (h->cur_pic_ptr)
1041         h->cur_pic_ptr->reference = 0;
1042     h->first_field = 0;
1043     memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
1044     memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
1045     memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
1046     memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
1047     ff_h264_reset_sei(h);
1048     h->recovery_frame = -1;
1049     h->frame_recovered = 0;
1050 }
1051
1052 /* forget old pics after a seek */
1053 static void flush_dpb(AVCodecContext *avctx)
1054 {
1055     H264Context *h = avctx->priv_data;
1056     int i;
1057
1058     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1059         if (h->delayed_pic[i])
1060             h->delayed_pic[i]->reference = 0;
1061         h->delayed_pic[i] = NULL;
1062     }
1063
1064     ff_h264_flush_change(h);
1065
1066     if (h->DPB)
1067         for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1068             ff_h264_unref_picture(h, &h->DPB[i]);
1069     h->cur_pic_ptr = NULL;
1070     ff_h264_unref_picture(h, &h->cur_pic);
1071
1072     h->mb_x = h->mb_y = 0;
1073
1074     h->parse_context.state             = -1;
1075     h->parse_context.frame_start_found = 0;
1076     h->parse_context.overread          = 0;
1077     h->parse_context.overread_index    = 0;
1078     h->parse_context.index             = 0;
1079     h->parse_context.last_index        = 0;
1080
1081     ff_h264_free_tables(h, 1);
1082     h->context_initialized = 0;
1083 }
1084
1085 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1086 {
1087     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1088     int field_poc[2];
1089
1090     h->frame_num_offset = h->prev_frame_num_offset;
1091     if (h->frame_num < h->prev_frame_num)
1092         h->frame_num_offset += max_frame_num;
1093
1094     if (h->sps.poc_type == 0) {
1095         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1096
1097         if (h->poc_lsb < h->prev_poc_lsb &&
1098             h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1099             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1100         else if (h->poc_lsb > h->prev_poc_lsb &&
1101                  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1102             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1103         else
1104             h->poc_msb = h->prev_poc_msb;
1105         field_poc[0] =
1106         field_poc[1] = h->poc_msb + h->poc_lsb;
1107         if (h->picture_structure == PICT_FRAME)
1108             field_poc[1] += h->delta_poc_bottom;
1109     } else if (h->sps.poc_type == 1) {
1110         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1111         int i;
1112
1113         if (h->sps.poc_cycle_length != 0)
1114             abs_frame_num = h->frame_num_offset + h->frame_num;
1115         else
1116             abs_frame_num = 0;
1117
1118         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1119             abs_frame_num--;
1120
1121         expected_delta_per_poc_cycle = 0;
1122         for (i = 0; i < h->sps.poc_cycle_length; i++)
1123             // FIXME integrate during sps parse
1124             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1125
1126         if (abs_frame_num > 0) {
1127             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1128             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1129
1130             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1131             for (i = 0; i <= frame_num_in_poc_cycle; i++)
1132                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1133         } else
1134             expectedpoc = 0;
1135
1136         if (h->nal_ref_idc == 0)
1137             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1138
1139         field_poc[0] = expectedpoc + h->delta_poc[0];
1140         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1141
1142         if (h->picture_structure == PICT_FRAME)
1143             field_poc[1] += h->delta_poc[1];
1144     } else {
1145         int poc = 2 * (h->frame_num_offset + h->frame_num);
1146
1147         if (!h->nal_ref_idc)
1148             poc--;
1149
1150         field_poc[0] = poc;
1151         field_poc[1] = poc;
1152     }
1153
1154     if (h->picture_structure != PICT_BOTTOM_FIELD)
1155         pic_field_poc[0] = field_poc[0];
1156     if (h->picture_structure != PICT_TOP_FIELD)
1157         pic_field_poc[1] = field_poc[1];
1158     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1159
1160     return 0;
1161 }
1162
1163 /**
1164  * Compute profile from profile_idc and constraint_set?_flags.
1165  *
1166  * @param sps SPS
1167  *
1168  * @return profile as defined by FF_PROFILE_H264_*
1169  */
1170 int ff_h264_get_profile(SPS *sps)
1171 {
1172     int profile = sps->profile_idc;
1173
1174     switch (sps->profile_idc) {
1175     case FF_PROFILE_H264_BASELINE:
1176         // constraint_set1_flag set to 1
1177         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1178         break;
1179     case FF_PROFILE_H264_HIGH_10:
1180     case FF_PROFILE_H264_HIGH_422:
1181     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1182         // constraint_set3_flag set to 1
1183         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1184         break;
1185     }
1186
1187     return profile;
1188 }
1189
1190 int ff_h264_set_parameter_from_sps(H264Context *h)
1191 {
1192     if (h->flags & CODEC_FLAG_LOW_DELAY ||
1193         (h->sps.bitstream_restriction_flag &&
1194          !h->sps.num_reorder_frames)) {
1195         if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1196             av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1197                    "Reenabling low delay requires a codec flush.\n");
1198         else
1199             h->low_delay = 1;
1200     }
1201
1202     if (h->avctx->has_b_frames < 2)
1203         h->avctx->has_b_frames = !h->low_delay;
1204
1205     if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1206         h->cur_chroma_format_idc      != h->sps.chroma_format_idc) {
1207         if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
1208             h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1209             h->cur_chroma_format_idc      = h->sps.chroma_format_idc;
1210             h->pixel_shift                = h->sps.bit_depth_luma > 8;
1211
1212             ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1213                             h->sps.chroma_format_idc);
1214             ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1215             ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1216             ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1217                               h->sps.chroma_format_idc);
1218             if (CONFIG_ERROR_RESILIENCE)
1219                 ff_dsputil_init(&h->dsp, h->avctx);
1220             ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1221         } else {
1222             av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1223                    h->sps.bit_depth_luma);
1224             return AVERROR_INVALIDDATA;
1225         }
1226     }
1227     return 0;
1228 }
1229
1230 int ff_set_ref_count(H264Context *h)
1231 {
1232     int ref_count[2], list_count;
1233     int num_ref_idx_active_override_flag, max_refs;
1234
1235     // set defaults, might be overridden a few lines later
1236     ref_count[0] = h->pps.ref_count[0];
1237     ref_count[1] = h->pps.ref_count[1];
1238
1239     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1240         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1241             h->direct_spatial_mv_pred = get_bits1(&h->gb);
1242         num_ref_idx_active_override_flag = get_bits1(&h->gb);
1243
1244         if (num_ref_idx_active_override_flag) {
1245             ref_count[0] = get_ue_golomb(&h->gb) + 1;
1246             if (ref_count[0] < 1)
1247                 return AVERROR_INVALIDDATA;
1248             if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1249                 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1250                 if (ref_count[1] < 1)
1251                     return AVERROR_INVALIDDATA;
1252             }
1253         }
1254
1255         if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1256             list_count = 2;
1257         else
1258             list_count = 1;
1259     } else {
1260         list_count   = 0;
1261         ref_count[0] = ref_count[1] = 0;
1262     }
1263
1264     max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1265
1266     if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1267         av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1268         h->ref_count[0] = h->ref_count[1] = 0;
1269         return AVERROR_INVALIDDATA;
1270     }
1271
1272     if (list_count != h->list_count ||
1273         ref_count[0] != h->ref_count[0] ||
1274         ref_count[1] != h->ref_count[1]) {
1275         h->ref_count[0] = ref_count[0];
1276         h->ref_count[1] = ref_count[1];
1277         h->list_count   = list_count;
1278         return 1;
1279     }
1280
1281     return 0;
1282 }
1283
1284 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1285                             int parse_extradata)
1286 {
1287     AVCodecContext *const avctx = h->avctx;
1288     H264Context *hx; ///< thread context
1289     int buf_index;
1290     unsigned context_count;
1291     int next_avc;
1292     int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
1293     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1294     int nal_index;
1295     int ret = 0;
1296
1297     h->max_contexts = h->slice_context_count;
1298     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1299         h->current_slice = 0;
1300         if (!h->first_field)
1301             h->cur_pic_ptr = NULL;
1302         ff_h264_reset_sei(h);
1303     }
1304
1305     for (; pass <= 1; pass++) {
1306         buf_index     = 0;
1307         context_count = 0;
1308         next_avc      = h->is_avc ? 0 : buf_size;
1309         nal_index     = 0;
1310         for (;;) {
1311             int consumed;
1312             int dst_length;
1313             int bit_length;
1314             const uint8_t *ptr;
1315             int i, nalsize = 0;
1316             int err;
1317
1318             if (buf_index >= next_avc) {
1319                 if (buf_index >= buf_size - h->nal_length_size)
1320                     break;
1321                 nalsize = 0;
1322                 for (i = 0; i < h->nal_length_size; i++)
1323                     nalsize = (nalsize << 8) | buf[buf_index++];
1324                 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
1325                     av_log(h->avctx, AV_LOG_ERROR,
1326                            "AVC: nal size %d\n", nalsize);
1327                     break;
1328                 }
1329                 next_avc = buf_index + nalsize;
1330             } else {
1331                 // start code prefix search
1332                 for (; buf_index + 3 < next_avc; buf_index++)
1333                     // This should always succeed in the first iteration.
1334                     if (buf[buf_index]     == 0 &&
1335                         buf[buf_index + 1] == 0 &&
1336                         buf[buf_index + 2] == 1)
1337                         break;
1338
1339                 if (buf_index + 3 >= buf_size) {
1340                     buf_index = buf_size;
1341                     break;
1342                 }
1343
1344                 buf_index += 3;
1345                 if (buf_index >= next_avc)
1346                     continue;
1347             }
1348
1349             hx = h->thread_context[context_count];
1350
1351             ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1352                                      &consumed, next_avc - buf_index);
1353             if (ptr == NULL || dst_length < 0) {
1354                 ret = -1;
1355                 goto end;
1356             }
1357             i = buf_index + consumed;
1358             if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1359                 buf[i]     == 0x00 && buf[i + 1] == 0x00 &&
1360                 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1361                 h->workaround_bugs |= FF_BUG_TRUNCATED;
1362
1363             if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1364                 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1365                     dst_length--;
1366             bit_length = !dst_length ? 0
1367                                      : (8 * dst_length -
1368                                         decode_rbsp_trailing(h, ptr + dst_length - 1));
1369
1370             if (h->avctx->debug & FF_DEBUG_STARTCODE)
1371                 av_log(h->avctx, AV_LOG_DEBUG,
1372                        "NAL %d at %d/%d length %d\n",
1373                        hx->nal_unit_type, buf_index, buf_size, dst_length);
1374
1375             if (h->is_avc && (nalsize != consumed) && nalsize)
1376                 av_log(h->avctx, AV_LOG_DEBUG,
1377                        "AVC: Consumed only %d bytes instead of %d\n",
1378                        consumed, nalsize);
1379
1380             buf_index += consumed;
1381             nal_index++;
1382
1383             if (pass == 0) {
1384                 /* packets can sometimes contain multiple PPS/SPS,
1385                  * e.g. two PAFF field pictures in one packet, or a demuxer
1386                  * which splits NALs strangely if so, when frame threading we
1387                  * can't start the next thread until we've read all of them */
1388                 switch (hx->nal_unit_type) {
1389                 case NAL_SPS:
1390                 case NAL_PPS:
1391                     nals_needed = nal_index;
1392                     break;
1393                 case NAL_DPA:
1394                 case NAL_IDR_SLICE:
1395                 case NAL_SLICE:
1396                     init_get_bits(&hx->gb, ptr, bit_length);
1397                     if (!get_ue_golomb(&hx->gb))
1398                         nals_needed = nal_index;
1399                 }
1400                 continue;
1401             }
1402
1403             if (avctx->skip_frame >= AVDISCARD_NONREF &&
1404                 h->nal_ref_idc == 0 &&
1405                 h->nal_unit_type != NAL_SEI)
1406                 continue;
1407
1408 again:
1409             /* Ignore every NAL unit type except PPS and SPS during extradata
1410              * parsing. Decoding slices is not possible in codec init
1411              * with frame-mt */
1412             if (parse_extradata && HAVE_THREADS &&
1413                 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1414                 (hx->nal_unit_type != NAL_PPS &&
1415                  hx->nal_unit_type != NAL_SPS)) {
1416                 if (hx->nal_unit_type < NAL_AUD ||
1417                     hx->nal_unit_type > NAL_AUXILIARY_SLICE)
1418                     av_log(avctx, AV_LOG_INFO,
1419                            "Ignoring NAL unit %d during extradata parsing\n",
1420                            hx->nal_unit_type);
1421                 hx->nal_unit_type = NAL_FF_IGNORE;
1422             }
1423             err = 0;
1424             switch (hx->nal_unit_type) {
1425             case NAL_IDR_SLICE:
1426                 if (h->nal_unit_type != NAL_IDR_SLICE) {
1427                     av_log(h->avctx, AV_LOG_ERROR,
1428                            "Invalid mix of idr and non-idr slices\n");
1429                     ret = -1;
1430                     goto end;
1431                 }
1432                 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1433             case NAL_SLICE:
1434                 init_get_bits(&hx->gb, ptr, bit_length);
1435                 hx->intra_gb_ptr      =
1436                 hx->inter_gb_ptr      = &hx->gb;
1437                 hx->data_partitioning = 0;
1438
1439                 if ((err = ff_h264_decode_slice_header(hx, h)))
1440                     break;
1441
1442                 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1443                     h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1444                                         ((1 << h->sps.log2_max_frame_num) - 1);
1445                 }
1446
1447                 h->cur_pic_ptr->f.key_frame |=
1448                     (hx->nal_unit_type == NAL_IDR_SLICE) ||
1449                     (h->sei_recovery_frame_cnt >= 0);
1450
1451                 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1452                     h->recovery_frame == h->frame_num) {
1453                     h->recovery_frame         = -1;
1454                     h->cur_pic_ptr->recovered = 1;
1455                 }
1456                 // If we have an IDR, all frames after it in decoded order are
1457                 // "recovered".
1458                 if (hx->nal_unit_type == NAL_IDR_SLICE)
1459                     h->frame_recovered |= FRAME_RECOVERED_IDR;
1460                 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1461
1462                 if (h->current_slice == 1) {
1463                     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1464                         decode_postinit(h, nal_index >= nals_needed);
1465
1466                     if (h->avctx->hwaccel &&
1467                         (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1468                         return ret;
1469                 }
1470
1471                 if (hx->redundant_pic_count == 0 &&
1472                     (avctx->skip_frame < AVDISCARD_NONREF ||
1473                      hx->nal_ref_idc) &&
1474                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
1475                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1476                     (avctx->skip_frame < AVDISCARD_NONKEY ||
1477                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1478                     avctx->skip_frame < AVDISCARD_ALL) {
1479                     if (avctx->hwaccel) {
1480                         ret = avctx->hwaccel->decode_slice(avctx,
1481                                                            &buf[buf_index - consumed],
1482                                                            consumed);
1483                         if (ret < 0)
1484                             return ret;
1485                     } else
1486                         context_count++;
1487                 }
1488                 break;
1489             case NAL_DPA:
1490                 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
1491                     av_log(h->avctx, AV_LOG_ERROR,
1492                            "Decoding in chunks is not supported for "
1493                            "partitioned slices.\n");
1494                     return AVERROR(ENOSYS);
1495                 }
1496
1497                 init_get_bits(&hx->gb, ptr, bit_length);
1498                 hx->intra_gb_ptr =
1499                 hx->inter_gb_ptr = NULL;
1500
1501                 if ((err = ff_h264_decode_slice_header(hx, h)) < 0) {
1502                     /* make sure data_partitioning is cleared if it was set
1503                      * before, so we don't try decoding a slice without a valid
1504                      * slice header later */
1505                     h->data_partitioning = 0;
1506                     break;
1507                 }
1508
1509                 hx->data_partitioning = 1;
1510                 break;
1511             case NAL_DPB:
1512                 init_get_bits(&hx->intra_gb, ptr, bit_length);
1513                 hx->intra_gb_ptr = &hx->intra_gb;
1514                 break;
1515             case NAL_DPC:
1516                 init_get_bits(&hx->inter_gb, ptr, bit_length);
1517                 hx->inter_gb_ptr = &hx->inter_gb;
1518
1519                 if (hx->redundant_pic_count == 0 &&
1520                     hx->intra_gb_ptr &&
1521                     hx->data_partitioning &&
1522                     h->cur_pic_ptr && h->context_initialized &&
1523                     (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
1524                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
1525                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1526                     (avctx->skip_frame < AVDISCARD_NONKEY ||
1527                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1528                     avctx->skip_frame < AVDISCARD_ALL)
1529                     context_count++;
1530                 break;
1531             case NAL_SEI:
1532                 init_get_bits(&h->gb, ptr, bit_length);
1533                 ff_h264_decode_sei(h);
1534                 break;
1535             case NAL_SPS:
1536                 init_get_bits(&h->gb, ptr, bit_length);
1537                 ret = ff_h264_decode_seq_parameter_set(h);
1538                 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
1539                     av_log(h->avctx, AV_LOG_DEBUG,
1540                            "SPS decoding failure, trying again with the complete NAL\n");
1541                     init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
1542                                   8 * (nalsize - 1));
1543                     ff_h264_decode_seq_parameter_set(h);
1544                 }
1545
1546                 ret = ff_h264_set_parameter_from_sps(h);
1547                 if (ret < 0)
1548                     goto end;
1549
1550                 break;
1551             case NAL_PPS:
1552                 init_get_bits(&h->gb, ptr, bit_length);
1553                 ff_h264_decode_picture_parameter_set(h, bit_length);
1554                 break;
1555             case NAL_AUD:
1556             case NAL_END_SEQUENCE:
1557             case NAL_END_STREAM:
1558             case NAL_FILLER_DATA:
1559             case NAL_SPS_EXT:
1560             case NAL_AUXILIARY_SLICE:
1561                 break;
1562             case NAL_FF_IGNORE:
1563                 break;
1564             default:
1565                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1566                        hx->nal_unit_type, bit_length);
1567             }
1568
1569             if (context_count == h->max_contexts) {
1570                 ff_h264_execute_decode_slices(h, context_count);
1571                 context_count = 0;
1572             }
1573
1574             if (err < 0) {
1575                 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1576                 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1577             } else if (err == 1) {
1578                 /* Slice could not be decoded in parallel mode, copy down
1579                  * NAL unit stuff to context 0 and restart. Note that
1580                  * rbsp_buffer is not transferred, but since we no longer
1581                  * run in parallel mode this should not be an issue. */
1582                 h->nal_unit_type = hx->nal_unit_type;
1583                 h->nal_ref_idc   = hx->nal_ref_idc;
1584                 hx               = h;
1585                 goto again;
1586             }
1587         }
1588     }
1589     if (context_count)
1590         ff_h264_execute_decode_slices(h, context_count);
1591
1592 end:
1593     /* clean up */
1594     if (h->cur_pic_ptr && !h->droppable) {
1595         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1596                                   h->picture_structure == PICT_BOTTOM_FIELD);
1597     }
1598
1599     return (ret < 0) ? ret : buf_index;
1600 }
1601
1602 /**
1603  * Return the number of bytes consumed for building the current frame.
1604  */
1605 static int get_consumed_bytes(int pos, int buf_size)
1606 {
1607     if (pos == 0)
1608         pos = 1;          // avoid infinite loops (i doubt that is needed but ...)
1609     if (pos + 10 > buf_size)
1610         pos = buf_size;                   // oops ;)
1611
1612     return pos;
1613 }
1614
1615 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1616 {
1617     int i;
1618     int ret = av_frame_ref(dst, src);
1619     if (ret < 0)
1620         return ret;
1621
1622     if (!h->sps.crop)
1623         return 0;
1624
1625     for (i = 0; i < 3; i++) {
1626         int hshift = (i > 0) ? h->chroma_x_shift : 0;
1627         int vshift = (i > 0) ? h->chroma_y_shift : 0;
1628         int off    = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1629                      (h->sps.crop_top >> vshift) * dst->linesize[i];
1630         dst->data[i] += off;
1631     }
1632     return 0;
1633 }
1634
1635 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1636                              int *got_frame, AVPacket *avpkt)
1637 {
1638     const uint8_t *buf = avpkt->data;
1639     int buf_size       = avpkt->size;
1640     H264Context *h     = avctx->priv_data;
1641     AVFrame *pict      = data;
1642     int buf_index      = 0;
1643     int ret;
1644
1645     h->flags = avctx->flags;
1646     /* reset data partitioning here, to ensure GetBitContexts from previous
1647      * packets do not get used. */
1648     h->data_partitioning = 0;
1649
1650     /* end of stream, output what is still in the buffers */
1651 out:
1652     if (buf_size == 0) {
1653         H264Picture *out;
1654         int i, out_idx;
1655
1656         h->cur_pic_ptr = NULL;
1657
1658         // FIXME factorize this with the output code below
1659         out     = h->delayed_pic[0];
1660         out_idx = 0;
1661         for (i = 1;
1662              h->delayed_pic[i] &&
1663              !h->delayed_pic[i]->f.key_frame &&
1664              !h->delayed_pic[i]->mmco_reset;
1665              i++)
1666             if (h->delayed_pic[i]->poc < out->poc) {
1667                 out     = h->delayed_pic[i];
1668                 out_idx = i;
1669             }
1670
1671         for (i = out_idx; h->delayed_pic[i]; i++)
1672             h->delayed_pic[i] = h->delayed_pic[i + 1];
1673
1674         if (out) {
1675             ret = output_frame(h, pict, &out->f);
1676             if (ret < 0)
1677                 return ret;
1678             *got_frame = 1;
1679         }
1680
1681         return buf_index;
1682     }
1683
1684     buf_index = decode_nal_units(h, buf, buf_size, 0);
1685     if (buf_index < 0)
1686         return AVERROR_INVALIDDATA;
1687
1688     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1689         buf_size = 0;
1690         goto out;
1691     }
1692
1693     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1694         if (avctx->skip_frame >= AVDISCARD_NONREF)
1695             return 0;
1696         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1697         return AVERROR_INVALIDDATA;
1698     }
1699
1700     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1701         (h->mb_y >= h->mb_height && h->mb_height)) {
1702         if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1703             decode_postinit(h, 1);
1704
1705         ff_h264_field_end(h, 0);
1706
1707         *got_frame = 0;
1708         if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1709                                    h->next_output_pic->recovered)) {
1710             if (!h->next_output_pic->recovered)
1711                 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1712
1713             ret = output_frame(h, pict, &h->next_output_pic->f);
1714             if (ret < 0)
1715                 return ret;
1716             *got_frame = 1;
1717         }
1718     }
1719
1720     assert(pict->buf[0] || !*got_frame);
1721
1722     return get_consumed_bytes(buf_index, buf_size);
1723 }
1724
1725 av_cold void ff_h264_free_context(H264Context *h)
1726 {
1727     int i;
1728
1729     ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1730
1731     for (i = 0; i < MAX_SPS_COUNT; i++)
1732         av_freep(h->sps_buffers + i);
1733
1734     for (i = 0; i < MAX_PPS_COUNT; i++)
1735         av_freep(h->pps_buffers + i);
1736 }
1737
1738 static av_cold int h264_decode_end(AVCodecContext *avctx)
1739 {
1740     H264Context *h = avctx->priv_data;
1741
1742     ff_h264_free_context(h);
1743
1744     ff_h264_unref_picture(h, &h->cur_pic);
1745
1746     return 0;
1747 }
1748
1749 static const AVProfile profiles[] = {
1750     { FF_PROFILE_H264_BASELINE,             "Baseline"              },
1751     { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
1752     { FF_PROFILE_H264_MAIN,                 "Main"                  },
1753     { FF_PROFILE_H264_EXTENDED,             "Extended"              },
1754     { FF_PROFILE_H264_HIGH,                 "High"                  },
1755     { FF_PROFILE_H264_HIGH_10,              "High 10"               },
1756     { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
1757     { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
1758     { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
1759     { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
1760     { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
1761     { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
1762     { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
1763     { FF_PROFILE_UNKNOWN },
1764 };
1765
1766 AVCodec ff_h264_decoder = {
1767     .name                  = "h264",
1768     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1769     .type                  = AVMEDIA_TYPE_VIDEO,
1770     .id                    = AV_CODEC_ID_H264,
1771     .priv_data_size        = sizeof(H264Context),
1772     .init                  = ff_h264_decode_init,
1773     .close                 = h264_decode_end,
1774     .decode                = h264_decode_frame,
1775     .capabilities          = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1776                              CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1777                              CODEC_CAP_FRAME_THREADS,
1778     .flush                 = flush_dpb,
1779     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1780     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1781     .profiles              = NULL_IF_CONFIG_SMALL(profiles),
1782 };