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