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