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