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