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