]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
Merge commit 'd3ea79e8a65ddad4da11813bb43c46701295f68c'
[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     h->has_afd               = 0;
612
613     h->next_outputed_poc = INT_MIN;
614     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
615         h->last_pocs[i] = INT_MIN;
616
617     ff_h264_reset_sei(h);
618
619     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
620
621     h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;
622     h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
623     if (!h->slice_ctx) {
624         h->nb_slice_ctx = 0;
625         return AVERROR(ENOMEM);
626     }
627
628     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
629         h->DPB[i].f = av_frame_alloc();
630         if (!h->DPB[i].f)
631             return AVERROR(ENOMEM);
632     }
633
634     h->cur_pic.f = av_frame_alloc();
635     if (!h->cur_pic.f)
636         return AVERROR(ENOMEM);
637
638     h->last_pic_for_ec.f = av_frame_alloc();
639     if (!h->last_pic_for_ec.f)
640         return AVERROR(ENOMEM);
641
642     for (i = 0; i < h->nb_slice_ctx; i++)
643         h->slice_ctx[i].h264 = h;
644
645     return 0;
646 }
647
648 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
649 {
650     H264Context *h = avctx->priv_data;
651     int ret;
652
653     ret = h264_init_context(avctx, h);
654     if (ret < 0)
655         return ret;
656
657     /* set defaults */
658     if (!avctx->has_b_frames)
659         h->low_delay = 1;
660
661     ff_h264_decode_init_vlc();
662
663     ff_init_cabac_states();
664
665     if (avctx->codec_id == AV_CODEC_ID_H264) {
666         if (avctx->ticks_per_frame == 1) {
667             if(h->avctx->time_base.den < INT_MAX/2) {
668                 h->avctx->time_base.den *= 2;
669             } else
670                 h->avctx->time_base.num /= 2;
671         }
672         avctx->ticks_per_frame = 2;
673     }
674
675     if (avctx->extradata_size > 0 && avctx->extradata) {
676         ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
677         if (ret < 0) {
678             ff_h264_free_context(h);
679             return ret;
680         }
681     }
682
683     if (h->sps.bitstream_restriction_flag &&
684         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
685         h->avctx->has_b_frames = h->sps.num_reorder_frames;
686         h->low_delay           = 0;
687     }
688
689     avctx->internal->allocate_progress = 1;
690
691     ff_h264_flush_change(h);
692
693     if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
694         h->enable_er = 0;
695
696     if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
697         av_log(avctx, AV_LOG_WARNING,
698                "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
699                "Use it at your own risk\n");
700     }
701
702     return 0;
703 }
704
705 static int decode_init_thread_copy(AVCodecContext *avctx)
706 {
707     H264Context *h = avctx->priv_data;
708     int ret;
709
710     if (!avctx->internal->is_copy)
711         return 0;
712
713     memset(h, 0, sizeof(*h));
714
715     ret = h264_init_context(avctx, h);
716     if (ret < 0)
717         return ret;
718
719     h->context_initialized = 0;
720
721     return 0;
722 }
723
724 /**
725  * Run setup operations that must be run after slice header decoding.
726  * This includes finding the next displayed frame.
727  *
728  * @param h h264 master context
729  * @param setup_finished enough NALs have been read that we can call
730  * ff_thread_finish_setup()
731  */
732 static void decode_postinit(H264Context *h, int setup_finished)
733 {
734     H264Picture *out = h->cur_pic_ptr;
735     H264Picture *cur = h->cur_pic_ptr;
736     int i, pics, out_of_order, out_idx;
737
738     h->cur_pic_ptr->f->pict_type = h->pict_type;
739
740     if (h->next_output_pic)
741         return;
742
743     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
744         /* FIXME: if we have two PAFF fields in one packet, we can't start
745          * the next thread here. If we have one field per packet, we can.
746          * The check in decode_nal_units() is not good enough to find this
747          * yet, so we assume the worst for now. */
748         // if (setup_finished)
749         //    ff_thread_finish_setup(h->avctx);
750         if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
751             return;
752         if (h->avctx->hwaccel || h->missing_fields <=1)
753             return;
754     }
755
756     cur->f->interlaced_frame = 0;
757     cur->f->repeat_pict      = 0;
758
759     /* Signal interlacing information externally. */
760     /* Prioritize picture timing SEI information over used
761      * decoding process if it exists. */
762
763     if (h->sps.pic_struct_present_flag) {
764         switch (h->sei_pic_struct) {
765         case SEI_PIC_STRUCT_FRAME:
766             break;
767         case SEI_PIC_STRUCT_TOP_FIELD:
768         case SEI_PIC_STRUCT_BOTTOM_FIELD:
769             cur->f->interlaced_frame = 1;
770             break;
771         case SEI_PIC_STRUCT_TOP_BOTTOM:
772         case SEI_PIC_STRUCT_BOTTOM_TOP:
773             if (FIELD_OR_MBAFF_PICTURE(h))
774                 cur->f->interlaced_frame = 1;
775             else
776                 // try to flag soft telecine progressive
777                 cur->f->interlaced_frame = h->prev_interlaced_frame;
778             break;
779         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
780         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
781             /* Signal the possibility of telecined film externally
782              * (pic_struct 5,6). From these hints, let the applications
783              * decide if they apply deinterlacing. */
784             cur->f->repeat_pict = 1;
785             break;
786         case SEI_PIC_STRUCT_FRAME_DOUBLING:
787             cur->f->repeat_pict = 2;
788             break;
789         case SEI_PIC_STRUCT_FRAME_TRIPLING:
790             cur->f->repeat_pict = 4;
791             break;
792         }
793
794         if ((h->sei_ct_type & 3) &&
795             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
796             cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
797     } else {
798         /* Derive interlacing flag from used decoding process. */
799         cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
800     }
801     h->prev_interlaced_frame = cur->f->interlaced_frame;
802
803     if (cur->field_poc[0] != cur->field_poc[1]) {
804         /* Derive top_field_first from field pocs. */
805         cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
806     } else {
807         if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
808             /* Use picture timing SEI information. Even if it is a
809              * information of a past frame, better than nothing. */
810             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
811                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
812                 cur->f->top_field_first = 1;
813             else
814                 cur->f->top_field_first = 0;
815         } else {
816             /* Most likely progressive */
817             cur->f->top_field_first = 0;
818         }
819     }
820
821     if (h->sei_frame_packing_present &&
822         h->frame_packing_arrangement_type >= 0 &&
823         h->frame_packing_arrangement_type <= 6 &&
824         h->content_interpretation_type > 0 &&
825         h->content_interpretation_type < 3) {
826         AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
827         if (stereo) {
828         switch (h->frame_packing_arrangement_type) {
829         case 0:
830             stereo->type = AV_STEREO3D_CHECKERBOARD;
831             break;
832         case 1:
833             stereo->type = AV_STEREO3D_COLUMNS;
834             break;
835         case 2:
836             stereo->type = AV_STEREO3D_LINES;
837             break;
838         case 3:
839             if (h->quincunx_subsampling)
840                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
841             else
842                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
843             break;
844         case 4:
845             stereo->type = AV_STEREO3D_TOPBOTTOM;
846             break;
847         case 5:
848             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
849             break;
850         case 6:
851             stereo->type = AV_STEREO3D_2D;
852             break;
853         }
854
855         if (h->content_interpretation_type == 2)
856             stereo->flags = AV_STEREO3D_FLAG_INVERT;
857         }
858     }
859
860     if (h->sei_display_orientation_present &&
861         (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
862         double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
863         AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
864                                                            AV_FRAME_DATA_DISPLAYMATRIX,
865                                                            sizeof(int32_t) * 9);
866         if (rotation) {
867             av_display_rotation_set((int32_t *)rotation->data, angle);
868             av_display_matrix_flip((int32_t *)rotation->data,
869                                    h->sei_hflip, h->sei_vflip);
870         }
871     }
872
873     if (h->has_afd) {
874         AVFrameSideData *sd =
875             av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD, 1);
876         if (sd) {
877             *sd->data   = h->afd;
878             h->has_afd = 0;
879         }
880     }
881
882     cur->mmco_reset = h->mmco_reset;
883     h->mmco_reset = 0;
884
885     // FIXME do something with unavailable reference frames
886
887     /* Sort B-frames into display order */
888
889     if (h->sps.bitstream_restriction_flag &&
890         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
891         h->avctx->has_b_frames = h->sps.num_reorder_frames;
892         h->low_delay           = 0;
893     }
894
895     if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
896         !h->sps.bitstream_restriction_flag) {
897         h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
898         h->low_delay           = 0;
899     }
900
901     for (i = 0; 1; i++) {
902         if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
903             if(i)
904                 h->last_pocs[i-1] = cur->poc;
905             break;
906         } else if(i) {
907             h->last_pocs[i-1]= h->last_pocs[i];
908         }
909     }
910     out_of_order = MAX_DELAYED_PIC_COUNT - i;
911     if(   cur->f->pict_type == AV_PICTURE_TYPE_B
912        || (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))
913         out_of_order = FFMAX(out_of_order, 1);
914     if (out_of_order == MAX_DELAYED_PIC_COUNT) {
915         av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
916         for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
917             h->last_pocs[i] = INT_MIN;
918         h->last_pocs[0] = cur->poc;
919         cur->mmco_reset = 1;
920     } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
921         av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
922         h->avctx->has_b_frames = out_of_order;
923         h->low_delay = 0;
924     }
925
926     pics = 0;
927     while (h->delayed_pic[pics])
928         pics++;
929
930     av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
931
932     h->delayed_pic[pics++] = cur;
933     if (cur->reference == 0)
934         cur->reference = DELAYED_PIC_REF;
935
936     out     = h->delayed_pic[0];
937     out_idx = 0;
938     for (i = 1; h->delayed_pic[i] &&
939                 !h->delayed_pic[i]->f->key_frame &&
940                 !h->delayed_pic[i]->mmco_reset;
941          i++)
942         if (h->delayed_pic[i]->poc < out->poc) {
943             out     = h->delayed_pic[i];
944             out_idx = i;
945         }
946     if (h->avctx->has_b_frames == 0 &&
947         (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
948         h->next_outputed_poc = INT_MIN;
949     out_of_order = out->poc < h->next_outputed_poc;
950
951     if (out_of_order || pics > h->avctx->has_b_frames) {
952         out->reference &= ~DELAYED_PIC_REF;
953         // for frame threading, the owner must be the second field's thread or
954         // else the first thread can release the picture and reuse it unsafely
955         for (i = out_idx; h->delayed_pic[i]; i++)
956             h->delayed_pic[i] = h->delayed_pic[i + 1];
957     }
958     if (!out_of_order && pics > h->avctx->has_b_frames) {
959         h->next_output_pic = out;
960         if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
961             h->next_outputed_poc = INT_MIN;
962         } else
963             h->next_outputed_poc = out->poc;
964     } else {
965         av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
966     }
967
968     if (h->next_output_pic) {
969         if (h->next_output_pic->recovered) {
970             // We have reached an recovery point and all frames after it in
971             // display order are "recovered".
972             h->frame_recovered |= FRAME_RECOVERED_SEI;
973         }
974         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
975     }
976
977     if (setup_finished && !h->avctx->hwaccel) {
978         ff_thread_finish_setup(h->avctx);
979
980         if (h->avctx->active_thread_type & FF_THREAD_FRAME)
981             h->setup_finished = 1;
982     }
983 }
984
985 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
986 {
987     int list, i;
988     int luma_def, chroma_def;
989
990     sl->use_weight             = 0;
991     sl->use_weight_chroma      = 0;
992     sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
993     if (h->sps.chroma_format_idc)
994         sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
995
996     if (sl->luma_log2_weight_denom > 7U) {
997         av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
998         sl->luma_log2_weight_denom = 0;
999     }
1000     if (sl->chroma_log2_weight_denom > 7U) {
1001         av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
1002         sl->chroma_log2_weight_denom = 0;
1003     }
1004
1005     luma_def   = 1 << sl->luma_log2_weight_denom;
1006     chroma_def = 1 << sl->chroma_log2_weight_denom;
1007
1008     for (list = 0; list < 2; list++) {
1009         sl->luma_weight_flag[list]   = 0;
1010         sl->chroma_weight_flag[list] = 0;
1011         for (i = 0; i < sl->ref_count[list]; i++) {
1012             int luma_weight_flag, chroma_weight_flag;
1013
1014             luma_weight_flag = get_bits1(&sl->gb);
1015             if (luma_weight_flag) {
1016                 sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
1017                 sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
1018                 if (sl->luma_weight[i][list][0] != luma_def ||
1019                     sl->luma_weight[i][list][1] != 0) {
1020                     sl->use_weight             = 1;
1021                     sl->luma_weight_flag[list] = 1;
1022                 }
1023             } else {
1024                 sl->luma_weight[i][list][0] = luma_def;
1025                 sl->luma_weight[i][list][1] = 0;
1026             }
1027
1028             if (h->sps.chroma_format_idc) {
1029                 chroma_weight_flag = get_bits1(&sl->gb);
1030                 if (chroma_weight_flag) {
1031                     int j;
1032                     for (j = 0; j < 2; j++) {
1033                         sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
1034                         sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
1035                         if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1036                             sl->chroma_weight[i][list][j][1] != 0) {
1037                             sl->use_weight_chroma        = 1;
1038                             sl->chroma_weight_flag[list] = 1;
1039                         }
1040                     }
1041                 } else {
1042                     int j;
1043                     for (j = 0; j < 2; j++) {
1044                         sl->chroma_weight[i][list][j][0] = chroma_def;
1045                         sl->chroma_weight[i][list][j][1] = 0;
1046                     }
1047                 }
1048             }
1049         }
1050         if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1051             break;
1052     }
1053     sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1054     return 0;
1055 }
1056
1057 /**
1058  * instantaneous decoder refresh.
1059  */
1060 static void idr(H264Context *h)
1061 {
1062     int i;
1063     ff_h264_remove_all_refs(h);
1064     h->prev_frame_num        =
1065     h->prev_frame_num_offset = 0;
1066     h->prev_poc_msb          = 1<<16;
1067     h->prev_poc_lsb          = 0;
1068     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1069         h->last_pocs[i] = INT_MIN;
1070 }
1071
1072 /* forget old pics after a seek */
1073 void ff_h264_flush_change(H264Context *h)
1074 {
1075     int i, j;
1076
1077     h->next_outputed_poc = INT_MIN;
1078     h->prev_interlaced_frame = 1;
1079     idr(h);
1080
1081     h->prev_frame_num = -1;
1082     if (h->cur_pic_ptr) {
1083         h->cur_pic_ptr->reference = 0;
1084         for (j=i=0; h->delayed_pic[i]; i++)
1085             if (h->delayed_pic[i] != h->cur_pic_ptr)
1086                 h->delayed_pic[j++] = h->delayed_pic[i];
1087         h->delayed_pic[j] = NULL;
1088     }
1089     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1090
1091     h->first_field = 0;
1092     ff_h264_reset_sei(h);
1093     h->recovery_frame = -1;
1094     h->frame_recovered = 0;
1095     h->current_slice = 0;
1096     h->mmco_reset = 1;
1097     for (i = 0; i < h->nb_slice_ctx; i++)
1098         h->slice_ctx[i].list_count = 0;
1099 }
1100
1101 /* forget old pics after a seek */
1102 static void flush_dpb(AVCodecContext *avctx)
1103 {
1104     H264Context *h = avctx->priv_data;
1105     int i;
1106
1107     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1108
1109     ff_h264_flush_change(h);
1110
1111     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1112         ff_h264_unref_picture(h, &h->DPB[i]);
1113     h->cur_pic_ptr = NULL;
1114     ff_h264_unref_picture(h, &h->cur_pic);
1115
1116     h->mb_y = 0;
1117
1118     ff_h264_free_tables(h);
1119     h->context_initialized = 0;
1120 }
1121
1122 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1123 {
1124     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1125     int field_poc[2];
1126
1127     h->frame_num_offset = h->prev_frame_num_offset;
1128     if (h->frame_num < h->prev_frame_num)
1129         h->frame_num_offset += max_frame_num;
1130
1131     if (h->sps.poc_type == 0) {
1132         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1133
1134         if (h->poc_lsb < h->prev_poc_lsb &&
1135             h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1136             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1137         else if (h->poc_lsb > h->prev_poc_lsb &&
1138                  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1139             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1140         else
1141             h->poc_msb = h->prev_poc_msb;
1142         field_poc[0] =
1143         field_poc[1] = h->poc_msb + h->poc_lsb;
1144         if (h->picture_structure == PICT_FRAME)
1145             field_poc[1] += h->delta_poc_bottom;
1146     } else if (h->sps.poc_type == 1) {
1147         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1148         int i;
1149
1150         if (h->sps.poc_cycle_length != 0)
1151             abs_frame_num = h->frame_num_offset + h->frame_num;
1152         else
1153             abs_frame_num = 0;
1154
1155         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1156             abs_frame_num--;
1157
1158         expected_delta_per_poc_cycle = 0;
1159         for (i = 0; i < h->sps.poc_cycle_length; i++)
1160             // FIXME integrate during sps parse
1161             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1162
1163         if (abs_frame_num > 0) {
1164             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1165             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1166
1167             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1168             for (i = 0; i <= frame_num_in_poc_cycle; i++)
1169                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1170         } else
1171             expectedpoc = 0;
1172
1173         if (h->nal_ref_idc == 0)
1174             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1175
1176         field_poc[0] = expectedpoc + h->delta_poc[0];
1177         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1178
1179         if (h->picture_structure == PICT_FRAME)
1180             field_poc[1] += h->delta_poc[1];
1181     } else {
1182         int poc = 2 * (h->frame_num_offset + h->frame_num);
1183
1184         if (!h->nal_ref_idc)
1185             poc--;
1186
1187         field_poc[0] = poc;
1188         field_poc[1] = poc;
1189     }
1190
1191     if (h->picture_structure != PICT_BOTTOM_FIELD)
1192         pic_field_poc[0] = field_poc[0];
1193     if (h->picture_structure != PICT_TOP_FIELD)
1194         pic_field_poc[1] = field_poc[1];
1195     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1196
1197     return 0;
1198 }
1199
1200 /**
1201  * Compute profile from profile_idc and constraint_set?_flags.
1202  *
1203  * @param sps SPS
1204  *
1205  * @return profile as defined by FF_PROFILE_H264_*
1206  */
1207 int ff_h264_get_profile(SPS *sps)
1208 {
1209     int profile = sps->profile_idc;
1210
1211     switch (sps->profile_idc) {
1212     case FF_PROFILE_H264_BASELINE:
1213         // constraint_set1_flag set to 1
1214         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1215         break;
1216     case FF_PROFILE_H264_HIGH_10:
1217     case FF_PROFILE_H264_HIGH_422:
1218     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1219         // constraint_set3_flag set to 1
1220         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1221         break;
1222     }
1223
1224     return profile;
1225 }
1226
1227 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1228 {
1229     int ref_count[2], list_count;
1230     int num_ref_idx_active_override_flag;
1231
1232     // set defaults, might be overridden a few lines later
1233     ref_count[0] = h->pps.ref_count[0];
1234     ref_count[1] = h->pps.ref_count[1];
1235
1236     if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1237         unsigned max[2];
1238         max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1239
1240         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1241             sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1242         num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1243
1244         if (num_ref_idx_active_override_flag) {
1245             ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1246             if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1247                 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1248             } else
1249                 // full range is spec-ok in this case, even for frames
1250                 ref_count[1] = 1;
1251         }
1252
1253         if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1254             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]);
1255             sl->ref_count[0] = sl->ref_count[1] = 0;
1256             sl->list_count   = 0;
1257             return AVERROR_INVALIDDATA;
1258         }
1259
1260         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1261             list_count = 2;
1262         else
1263             list_count = 1;
1264     } else {
1265         list_count   = 0;
1266         ref_count[0] = ref_count[1] = 0;
1267     }
1268
1269     if (list_count   != sl->list_count   ||
1270         ref_count[0] != sl->ref_count[0] ||
1271         ref_count[1] != sl->ref_count[1]) {
1272         sl->ref_count[0] = ref_count[0];
1273         sl->ref_count[1] = ref_count[1];
1274         sl->list_count   = list_count;
1275         return 1;
1276     }
1277
1278     return 0;
1279 }
1280
1281 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1282
1283 static int get_bit_length(H264Context *h, const uint8_t *buf,
1284                           const uint8_t *ptr, int dst_length,
1285                           int i, int next_avc)
1286 {
1287     if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1288         buf[i]     == 0x00 && buf[i + 1] == 0x00 &&
1289         buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1290         h->workaround_bugs |= FF_BUG_TRUNCATED;
1291
1292     if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1293         while (dst_length > 0 && ptr[dst_length - 1] == 0)
1294             dst_length--;
1295
1296     if (!dst_length)
1297         return 0;
1298
1299     return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1300 }
1301
1302 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1303 {
1304     int next_avc    = h->is_avc ? 0 : buf_size;
1305     int nal_index   = 0;
1306     int buf_index   = 0;
1307     int nals_needed = 0;
1308     int first_slice = 0;
1309
1310     while(1) {
1311         GetBitContext gb;
1312         int nalsize = 0;
1313         int dst_length, bit_length, consumed;
1314         const uint8_t *ptr;
1315
1316         if (buf_index >= next_avc) {
1317             nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1318             if (nalsize < 0)
1319                 break;
1320             next_avc = buf_index + nalsize;
1321         } else {
1322             buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1323             if (buf_index >= buf_size)
1324                 break;
1325             if (buf_index >= next_avc)
1326                 continue;
1327         }
1328
1329         ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1330                                  next_avc - buf_index);
1331
1332         if (!ptr || dst_length < 0)
1333             return AVERROR_INVALIDDATA;
1334
1335         buf_index += consumed;
1336
1337         bit_length = get_bit_length(h, buf, ptr, dst_length,
1338                                     buf_index, next_avc);
1339         nal_index++;
1340
1341         /* packets can sometimes contain multiple PPS/SPS,
1342          * e.g. two PAFF field pictures in one packet, or a demuxer
1343          * which splits NALs strangely if so, when frame threading we
1344          * can't start the next thread until we've read all of them */
1345         switch (h->nal_unit_type) {
1346         case NAL_SPS:
1347         case NAL_PPS:
1348             nals_needed = nal_index;
1349             break;
1350         case NAL_DPA:
1351         case NAL_IDR_SLICE:
1352         case NAL_SLICE:
1353             init_get_bits(&gb, ptr, bit_length);
1354             if (!get_ue_golomb(&gb) ||
1355                 !first_slice ||
1356                 first_slice != h->nal_unit_type)
1357                 nals_needed = nal_index;
1358             if (!first_slice)
1359                 first_slice = h->nal_unit_type;
1360         }
1361     }
1362
1363     return nals_needed;
1364 }
1365
1366 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1367                             int parse_extradata)
1368 {
1369     AVCodecContext *const avctx = h->avctx;
1370     H264SliceContext *sl;
1371     int buf_index;
1372     unsigned context_count;
1373     int next_avc;
1374     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1375     int nal_index;
1376     int idr_cleared=0;
1377     int ret = 0;
1378
1379     h->nal_unit_type= 0;
1380
1381     if(!h->slice_context_count)
1382          h->slice_context_count= 1;
1383     h->max_contexts = h->slice_context_count;
1384     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1385         h->current_slice = 0;
1386         if (!h->first_field)
1387             h->cur_pic_ptr = NULL;
1388         ff_h264_reset_sei(h);
1389     }
1390
1391     if (h->nal_length_size == 4) {
1392         if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1393             h->is_avc = 0;
1394         }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1395             h->is_avc = 1;
1396     }
1397
1398     if (avctx->active_thread_type & FF_THREAD_FRAME)
1399         nals_needed = get_last_needed_nal(h, buf, buf_size);
1400
1401     {
1402         buf_index     = 0;
1403         context_count = 0;
1404         next_avc      = h->is_avc ? 0 : buf_size;
1405         nal_index     = 0;
1406         for (;;) {
1407             int consumed;
1408             int dst_length;
1409             int bit_length;
1410             const uint8_t *ptr;
1411             int nalsize = 0;
1412             int err;
1413
1414             if (buf_index >= next_avc) {
1415                 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1416                 if (nalsize < 0)
1417                     break;
1418                 next_avc = buf_index + nalsize;
1419             } else {
1420                 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1421                 if (buf_index >= buf_size)
1422                     break;
1423                 if (buf_index >= next_avc)
1424                     continue;
1425             }
1426
1427             sl = &h->slice_ctx[context_count];
1428
1429             ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1430                                      &consumed, next_avc - buf_index);
1431             if (!ptr || dst_length < 0) {
1432                 ret = -1;
1433                 goto end;
1434             }
1435
1436             bit_length = get_bit_length(h, buf, ptr, dst_length,
1437                                         buf_index + consumed, next_avc);
1438
1439             if (h->avctx->debug & FF_DEBUG_STARTCODE)
1440                 av_log(h->avctx, AV_LOG_DEBUG,
1441                        "NAL %d/%d at %d/%d length %d\n",
1442                        h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
1443
1444             if (h->is_avc && (nalsize != consumed) && nalsize)
1445                 av_log(h->avctx, AV_LOG_DEBUG,
1446                        "AVC: Consumed only %d bytes instead of %d\n",
1447                        consumed, nalsize);
1448
1449             buf_index += consumed;
1450             nal_index++;
1451
1452             if (avctx->skip_frame >= AVDISCARD_NONREF &&
1453                 h->nal_ref_idc == 0 &&
1454                 h->nal_unit_type != NAL_SEI)
1455                 continue;
1456
1457 again:
1458             /* Ignore per frame NAL unit type during extradata
1459              * parsing. Decoding slices is not possible in codec init
1460              * with frame-mt */
1461             if (parse_extradata) {
1462                 switch (h->nal_unit_type) {
1463                 case NAL_IDR_SLICE:
1464                 case NAL_SLICE:
1465                 case NAL_DPA:
1466                 case NAL_DPB:
1467                 case NAL_DPC:
1468                     av_log(h->avctx, AV_LOG_WARNING,
1469                            "Ignoring NAL %d in global header/extradata\n",
1470                            h->nal_unit_type);
1471                     // fall through to next case
1472                 case NAL_AUXILIARY_SLICE:
1473                     h->nal_unit_type = NAL_FF_IGNORE;
1474                 }
1475             }
1476
1477             err = 0;
1478
1479             switch (h->nal_unit_type) {
1480             case NAL_IDR_SLICE:
1481                 if ((ptr[0] & 0xFC) == 0x98) {
1482                     av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1483                     h->next_outputed_poc = INT_MIN;
1484                     ret = -1;
1485                     goto end;
1486                 }
1487                 if (h->nal_unit_type != NAL_IDR_SLICE) {
1488                     av_log(h->avctx, AV_LOG_ERROR,
1489                            "Invalid mix of idr and non-idr slices\n");
1490                     ret = -1;
1491                     goto end;
1492                 }
1493                 if(!idr_cleared) {
1494                     if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1495                         av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1496                         ret = AVERROR_INVALIDDATA;
1497                         goto end;
1498                     }
1499                     idr(h); // FIXME ensure we don't lose some frames if there is reordering
1500                 }
1501                 idr_cleared = 1;
1502                 h->has_recovery_point = 1;
1503             case NAL_SLICE:
1504                 init_get_bits(&sl->gb, ptr, bit_length);
1505
1506                 if (   nals_needed >= nal_index
1507                     || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1508                     h->au_pps_id = -1;
1509
1510                 if ((err = ff_h264_decode_slice_header(h, sl)))
1511                     break;
1512
1513                 if (h->sei_recovery_frame_cnt >= 0) {
1514                     if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1515                         h->valid_recovery_point = 1;
1516
1517                     if (   h->recovery_frame < 0
1518                         || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1519                         h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1520
1521                         if (!h->valid_recovery_point)
1522                             h->recovery_frame = h->frame_num;
1523                     }
1524                 }
1525
1526                 h->cur_pic_ptr->f->key_frame |=
1527                     (h->nal_unit_type == NAL_IDR_SLICE);
1528
1529                 if (h->nal_unit_type == NAL_IDR_SLICE ||
1530                     h->recovery_frame == h->frame_num) {
1531                     h->recovery_frame         = -1;
1532                     h->cur_pic_ptr->recovered = 1;
1533                 }
1534                 // If we have an IDR, all frames after it in decoded order are
1535                 // "recovered".
1536                 if (h->nal_unit_type == NAL_IDR_SLICE)
1537                     h->frame_recovered |= FRAME_RECOVERED_IDR;
1538                 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1539                 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1540 #if 1
1541                 h->cur_pic_ptr->recovered |= h->frame_recovered;
1542 #else
1543                 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1544 #endif
1545
1546                 if (h->current_slice == 1) {
1547                     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1548                         decode_postinit(h, nal_index >= nals_needed);
1549
1550                     if (h->avctx->hwaccel &&
1551                         (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1552                         goto end;
1553                     if (CONFIG_H264_VDPAU_DECODER &&
1554                         h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1555                         ff_vdpau_h264_picture_start(h);
1556                 }
1557
1558                 if (sl->redundant_pic_count == 0) {
1559                     if (avctx->hwaccel) {
1560                         ret = avctx->hwaccel->decode_slice(avctx,
1561                                                            &buf[buf_index - consumed],
1562                                                            consumed);
1563                         if (ret < 0)
1564                             goto end;
1565                     } else if (CONFIG_H264_VDPAU_DECODER &&
1566                                h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1567                         ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1568                                                 start_code,
1569                                                 sizeof(start_code));
1570                         ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1571                                                 &buf[buf_index - consumed],
1572                                                 consumed);
1573                     } else
1574                         context_count++;
1575                 }
1576                 break;
1577             case NAL_DPA:
1578             case NAL_DPB:
1579             case NAL_DPC:
1580                 avpriv_request_sample(avctx, "data partitioning");
1581                 break;
1582             case NAL_SEI:
1583                 init_get_bits(&h->gb, ptr, bit_length);
1584                 ret = ff_h264_decode_sei(h);
1585                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1586                     goto end;
1587                 break;
1588             case NAL_SPS:
1589                 init_get_bits(&h->gb, ptr, bit_length);
1590                 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1591                     break;
1592                 if (h->is_avc ? nalsize : 1) {
1593                     av_log(h->avctx, AV_LOG_DEBUG,
1594                            "SPS decoding failure, trying again with the complete NAL\n");
1595                     if (h->is_avc)
1596                         av_assert0(next_avc - buf_index + consumed == nalsize);
1597                     if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1598                         break;
1599                     init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1600                                   8*(next_avc - buf_index + consumed - 1));
1601                     if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1602                         break;
1603                 }
1604                 init_get_bits(&h->gb, ptr, bit_length);
1605                 ff_h264_decode_seq_parameter_set(h, 1);
1606
1607                 break;
1608             case NAL_PPS:
1609                 init_get_bits(&h->gb, ptr, bit_length);
1610                 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1611                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1612                     goto end;
1613                 break;
1614             case NAL_AUD:
1615             case NAL_END_SEQUENCE:
1616             case NAL_END_STREAM:
1617             case NAL_FILLER_DATA:
1618             case NAL_SPS_EXT:
1619             case NAL_AUXILIARY_SLICE:
1620                 break;
1621             case NAL_FF_IGNORE:
1622                 break;
1623             default:
1624                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1625                        h->nal_unit_type, bit_length);
1626             }
1627
1628             if (context_count == h->max_contexts) {
1629                 ret = ff_h264_execute_decode_slices(h, context_count);
1630                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1631                     goto end;
1632                 context_count = 0;
1633             }
1634
1635             if (err < 0 || err == SLICE_SKIPED) {
1636                 if (err < 0)
1637                     av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1638                 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1639             } else if (err == SLICE_SINGLETHREAD) {
1640                 if (context_count > 1) {
1641                     ret = ff_h264_execute_decode_slices(h, context_count - 1);
1642                     if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1643                         goto end;
1644                     context_count = 0;
1645                 }
1646                 /* Slice could not be decoded in parallel mode, restart. Note
1647                  * that rbsp_buffer is not transferred, but since we no longer
1648                  * run in parallel mode this should not be an issue. */
1649                 sl               = &h->slice_ctx[0];
1650                 goto again;
1651             }
1652         }
1653     }
1654     if (context_count) {
1655         ret = ff_h264_execute_decode_slices(h, context_count);
1656         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1657             goto end;
1658     }
1659
1660     ret = 0;
1661 end:
1662     /* clean up */
1663     if (h->cur_pic_ptr && !h->droppable) {
1664         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1665                                   h->picture_structure == PICT_BOTTOM_FIELD);
1666     }
1667
1668     return (ret < 0) ? ret : buf_index;
1669 }
1670
1671 /**
1672  * Return the number of bytes consumed for building the current frame.
1673  */
1674 static int get_consumed_bytes(int pos, int buf_size)
1675 {
1676     if (pos == 0)
1677         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
1678     if (pos + 10 > buf_size)
1679         pos = buf_size; // oops ;)
1680
1681     return pos;
1682 }
1683
1684 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1685 {
1686     AVFrame *src = srcp->f;
1687     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1688     int i;
1689     int ret = av_frame_ref(dst, src);
1690     if (ret < 0)
1691         return ret;
1692
1693     av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1694
1695     h->backup_width   = h->avctx->width;
1696     h->backup_height  = h->avctx->height;
1697     h->backup_pix_fmt = h->avctx->pix_fmt;
1698
1699     h->avctx->width   = dst->width;
1700     h->avctx->height  = dst->height;
1701     h->avctx->pix_fmt = dst->format;
1702
1703     if (srcp->sei_recovery_frame_cnt == 0)
1704         dst->key_frame = 1;
1705     if (!srcp->crop)
1706         return 0;
1707
1708     for (i = 0; i < desc->nb_components; i++) {
1709         int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1710         int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1711         int off    = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1712                       (srcp->crop_top  >> vshift) * dst->linesize[i];
1713         dst->data[i] += off;
1714     }
1715     return 0;
1716 }
1717
1718 static int is_extra(const uint8_t *buf, int buf_size)
1719 {
1720     int cnt= buf[5]&0x1f;
1721     const uint8_t *p= buf+6;
1722     while(cnt--){
1723         int nalsize= AV_RB16(p) + 2;
1724         if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1725             return 0;
1726         p += nalsize;
1727     }
1728     cnt = *(p++);
1729     if(!cnt)
1730         return 0;
1731     while(cnt--){
1732         int nalsize= AV_RB16(p) + 2;
1733         if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1734             return 0;
1735         p += nalsize;
1736     }
1737     return 1;
1738 }
1739
1740 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1741                              int *got_frame, AVPacket *avpkt)
1742 {
1743     const uint8_t *buf = avpkt->data;
1744     int buf_size       = avpkt->size;
1745     H264Context *h     = avctx->priv_data;
1746     AVFrame *pict      = data;
1747     int buf_index      = 0;
1748     H264Picture *out;
1749     int i, out_idx;
1750     int ret;
1751
1752     h->flags = avctx->flags;
1753     h->setup_finished = 0;
1754
1755     if (h->backup_width != -1) {
1756         avctx->width    = h->backup_width;
1757         h->backup_width = -1;
1758     }
1759     if (h->backup_height != -1) {
1760         avctx->height    = h->backup_height;
1761         h->backup_height = -1;
1762     }
1763     if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1764         avctx->pix_fmt    = h->backup_pix_fmt;
1765         h->backup_pix_fmt = AV_PIX_FMT_NONE;
1766     }
1767
1768     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1769
1770     /* end of stream, output what is still in the buffers */
1771     if (buf_size == 0) {
1772  out:
1773
1774         h->cur_pic_ptr = NULL;
1775         h->first_field = 0;
1776
1777         // FIXME factorize this with the output code below
1778         out     = h->delayed_pic[0];
1779         out_idx = 0;
1780         for (i = 1;
1781              h->delayed_pic[i] &&
1782              !h->delayed_pic[i]->f->key_frame &&
1783              !h->delayed_pic[i]->mmco_reset;
1784              i++)
1785             if (h->delayed_pic[i]->poc < out->poc) {
1786                 out     = h->delayed_pic[i];
1787                 out_idx = i;
1788             }
1789
1790         for (i = out_idx; h->delayed_pic[i]; i++)
1791             h->delayed_pic[i] = h->delayed_pic[i + 1];
1792
1793         if (out) {
1794             out->reference &= ~DELAYED_PIC_REF;
1795             ret = output_frame(h, pict, out);
1796             if (ret < 0)
1797                 return ret;
1798             *got_frame = 1;
1799         }
1800
1801         return buf_index;
1802     }
1803     if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1804         int side_size;
1805         uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1806         if (is_extra(side, side_size))
1807             ff_h264_decode_extradata(h, side, side_size);
1808     }
1809     if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1810         if (is_extra(buf, buf_size))
1811             return ff_h264_decode_extradata(h, buf, buf_size);
1812     }
1813
1814     buf_index = decode_nal_units(h, buf, buf_size, 0);
1815     if (buf_index < 0)
1816         return AVERROR_INVALIDDATA;
1817
1818     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1819         av_assert0(buf_index <= buf_size);
1820         goto out;
1821     }
1822
1823     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1824         if (avctx->skip_frame >= AVDISCARD_NONREF ||
1825             buf_size >= 4 && !memcmp("Q264", buf, 4))
1826             return buf_size;
1827         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1828         return AVERROR_INVALIDDATA;
1829     }
1830
1831     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1832         (h->mb_y >= h->mb_height && h->mb_height)) {
1833         if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1834             decode_postinit(h, 1);
1835
1836         ff_h264_field_end(h, &h->slice_ctx[0], 0);
1837
1838         /* Wait for second field. */
1839         *got_frame = 0;
1840         if (h->next_output_pic && (
1841                                    h->next_output_pic->recovered)) {
1842             if (!h->next_output_pic->recovered)
1843                 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1844
1845             if (!h->avctx->hwaccel &&
1846                  (h->next_output_pic->field_poc[0] == INT_MAX ||
1847                   h->next_output_pic->field_poc[1] == INT_MAX)
1848             ) {
1849                 int p;
1850                 AVFrame *f = h->next_output_pic->f;
1851                 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1852                 uint8_t *dst_data[4];
1853                 int linesizes[4];
1854                 const uint8_t *src_data[4];
1855
1856                 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1857
1858                 for (p = 0; p<4; p++) {
1859                     dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1860                     src_data[p] = f->data[p] +  field   *f->linesize[p];
1861                     linesizes[p] = 2*f->linesize[p];
1862                 }
1863
1864                 av_image_copy(dst_data, linesizes, src_data, linesizes,
1865                               f->format, f->width, f->height>>1);
1866             }
1867
1868             ret = output_frame(h, pict, h->next_output_pic);
1869             if (ret < 0)
1870                 return ret;
1871             *got_frame = 1;
1872             if (CONFIG_MPEGVIDEO) {
1873                 ff_print_debug_info2(h->avctx, pict, NULL,
1874                                     h->next_output_pic->mb_type,
1875                                     h->next_output_pic->qscale_table,
1876                                     h->next_output_pic->motion_val,
1877                                     &h->low_delay,
1878                                     h->mb_width, h->mb_height, h->mb_stride, 1);
1879             }
1880         }
1881     }
1882
1883     av_assert0(pict->buf[0] || !*got_frame);
1884
1885     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1886
1887     return get_consumed_bytes(buf_index, buf_size);
1888 }
1889
1890 av_cold void ff_h264_free_context(H264Context *h)
1891 {
1892     int i;
1893
1894     ff_h264_free_tables(h);
1895
1896     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1897         ff_h264_unref_picture(h, &h->DPB[i]);
1898         av_frame_free(&h->DPB[i].f);
1899     }
1900     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1901
1902     h->cur_pic_ptr = NULL;
1903
1904     for (i = 0; i < h->nb_slice_ctx; i++)
1905         av_freep(&h->slice_ctx[i].rbsp_buffer);
1906     av_freep(&h->slice_ctx);
1907     h->nb_slice_ctx = 0;
1908
1909     for (i = 0; i < MAX_SPS_COUNT; i++)
1910         av_freep(h->sps_buffers + i);
1911
1912     for (i = 0; i < MAX_PPS_COUNT; i++)
1913         av_freep(h->pps_buffers + i);
1914 }
1915
1916 static av_cold int h264_decode_end(AVCodecContext *avctx)
1917 {
1918     H264Context *h = avctx->priv_data;
1919
1920     ff_h264_remove_all_refs(h);
1921     ff_h264_free_context(h);
1922
1923     ff_h264_unref_picture(h, &h->cur_pic);
1924     av_frame_free(&h->cur_pic.f);
1925     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1926     av_frame_free(&h->last_pic_for_ec.f);
1927
1928     return 0;
1929 }
1930
1931 #define OFFSET(x) offsetof(H264Context, x)
1932 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1933 static const AVOption h264_options[] = {
1934     {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1935     {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1936     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VD },
1937     { NULL },
1938 };
1939
1940 static const AVClass h264_class = {
1941     .class_name = "H264 Decoder",
1942     .item_name  = av_default_item_name,
1943     .option     = h264_options,
1944     .version    = LIBAVUTIL_VERSION_INT,
1945 };
1946
1947 static const AVProfile profiles[] = {
1948     { FF_PROFILE_H264_BASELINE,             "Baseline"              },
1949     { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
1950     { FF_PROFILE_H264_MAIN,                 "Main"                  },
1951     { FF_PROFILE_H264_EXTENDED,             "Extended"              },
1952     { FF_PROFILE_H264_HIGH,                 "High"                  },
1953     { FF_PROFILE_H264_HIGH_10,              "High 10"               },
1954     { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
1955     { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
1956     { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
1957     { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
1958     { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
1959     { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
1960     { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
1961     { FF_PROFILE_UNKNOWN },
1962 };
1963
1964 AVCodec ff_h264_decoder = {
1965     .name                  = "h264",
1966     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1967     .type                  = AVMEDIA_TYPE_VIDEO,
1968     .id                    = AV_CODEC_ID_H264,
1969     .priv_data_size        = sizeof(H264Context),
1970     .init                  = ff_h264_decode_init,
1971     .close                 = h264_decode_end,
1972     .decode                = h264_decode_frame,
1973     .capabilities          = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1974                              CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1975                              CODEC_CAP_FRAME_THREADS,
1976     .flush                 = flush_dpb,
1977     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1978     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1979     .profiles              = NULL_IF_CONFIG_SMALL(profiles),
1980     .priv_class            = &h264_class,
1981 };
1982
1983 #if CONFIG_H264_VDPAU_DECODER
1984 static const AVClass h264_vdpau_class = {
1985     .class_name = "H264 VDPAU Decoder",
1986     .item_name  = av_default_item_name,
1987     .option     = h264_options,
1988     .version    = LIBAVUTIL_VERSION_INT,
1989 };
1990
1991 AVCodec ff_h264_vdpau_decoder = {
1992     .name           = "h264_vdpau",
1993     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1994     .type           = AVMEDIA_TYPE_VIDEO,
1995     .id             = AV_CODEC_ID_H264,
1996     .priv_data_size = sizeof(H264Context),
1997     .init           = ff_h264_decode_init,
1998     .close          = h264_decode_end,
1999     .decode         = h264_decode_frame,
2000     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2001     .flush          = flush_dpb,
2002     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2003                                                      AV_PIX_FMT_NONE},
2004     .profiles       = NULL_IF_CONFIG_SMALL(profiles),
2005     .priv_class     = &h264_vdpau_class,
2006 };
2007 #endif