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