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