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