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