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