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