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