]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
lavu/mem: add av_dynarray_add_nofree function
[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 decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1319                             int parse_extradata)
1320 {
1321     AVCodecContext *const avctx = h->avctx;
1322     H264Context *hx; ///< thread context
1323     int buf_index;
1324     unsigned context_count;
1325     int next_avc;
1326     int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
1327     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1328     int nal_index;
1329     int idr_cleared=0;
1330     int first_slice = 0;
1331     int ret = 0;
1332
1333     h->nal_unit_type= 0;
1334
1335     if(!h->slice_context_count)
1336          h->slice_context_count= 1;
1337     h->max_contexts = h->slice_context_count;
1338     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1339         h->current_slice = 0;
1340         if (!h->first_field)
1341             h->cur_pic_ptr = NULL;
1342         ff_h264_reset_sei(h);
1343     }
1344
1345     if (h->nal_length_size == 4) {
1346         if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1347             h->is_avc = 0;
1348         }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1349             h->is_avc = 1;
1350     }
1351
1352     for (; pass <= 1; pass++) {
1353         buf_index     = 0;
1354         context_count = 0;
1355         next_avc      = h->is_avc ? 0 : buf_size;
1356         nal_index     = 0;
1357         for (;;) {
1358             int consumed;
1359             int dst_length;
1360             int bit_length;
1361             const uint8_t *ptr;
1362             int i, nalsize = 0;
1363             int err;
1364
1365             if (buf_index >= next_avc) {
1366                 if (buf_index >= buf_size - h->nal_length_size)
1367                     break;
1368                 nalsize = 0;
1369                 for (i = 0; i < h->nal_length_size; i++)
1370                     nalsize = (nalsize << 8) | buf[buf_index++];
1371                 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
1372                     av_log(h->avctx, AV_LOG_ERROR,
1373                            "AVC: nal size %d\n", nalsize);
1374                     break;
1375                 }
1376                 next_avc = buf_index + nalsize;
1377             } else {
1378                 // start code prefix search
1379                 for (; buf_index + 3 < next_avc; buf_index++)
1380                     // This should always succeed in the first iteration.
1381                     if (buf[buf_index]     == 0 &&
1382                         buf[buf_index + 1] == 0 &&
1383                         buf[buf_index + 2] == 1)
1384                         break;
1385
1386                 if (buf_index + 3 >= buf_size) {
1387                     buf_index = buf_size;
1388                     break;
1389                 }
1390
1391                 buf_index += 3;
1392                 if (buf_index >= next_avc)
1393                     continue;
1394             }
1395
1396             hx = h->thread_context[context_count];
1397
1398             ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1399                                      &consumed, next_avc - buf_index);
1400             if (ptr == NULL || dst_length < 0) {
1401                 ret = -1;
1402                 goto end;
1403             }
1404             i = buf_index + consumed;
1405             if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1406                 buf[i]     == 0x00 && buf[i + 1] == 0x00 &&
1407                 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1408                 h->workaround_bugs |= FF_BUG_TRUNCATED;
1409
1410             if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1411                 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1412                     dst_length--;
1413             bit_length = !dst_length ? 0
1414                                      : (8 * dst_length -
1415                                         decode_rbsp_trailing(h, ptr + dst_length - 1));
1416
1417             if (h->avctx->debug & FF_DEBUG_STARTCODE)
1418                 av_log(h->avctx, AV_LOG_DEBUG,
1419                        "NAL %d/%d at %d/%d length %d pass %d\n",
1420                        hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
1421
1422             if (h->is_avc && (nalsize != consumed) && nalsize)
1423                 av_log(h->avctx, AV_LOG_DEBUG,
1424                        "AVC: Consumed only %d bytes instead of %d\n",
1425                        consumed, nalsize);
1426
1427             buf_index += consumed;
1428             nal_index++;
1429
1430             if (pass == 0) {
1431                 /* packets can sometimes contain multiple PPS/SPS,
1432                  * e.g. two PAFF field pictures in one packet, or a demuxer
1433                  * which splits NALs strangely if so, when frame threading we
1434                  * can't start the next thread until we've read all of them */
1435                 switch (hx->nal_unit_type) {
1436                 case NAL_SPS:
1437                 case NAL_PPS:
1438                     nals_needed = nal_index;
1439                     break;
1440                 case NAL_DPA:
1441                 case NAL_IDR_SLICE:
1442                 case NAL_SLICE:
1443                     init_get_bits(&hx->gb, ptr, bit_length);
1444                     if (!get_ue_golomb(&hx->gb) ||
1445                         !first_slice ||
1446                         first_slice != hx->nal_unit_type)
1447                         nals_needed = nal_index;
1448                     if (!first_slice)
1449                         first_slice = hx->nal_unit_type;
1450                 }
1451                 continue;
1452             }
1453
1454             if (!first_slice)
1455                 switch (hx->nal_unit_type) {
1456                 case NAL_DPA:
1457                 case NAL_IDR_SLICE:
1458                 case NAL_SLICE:
1459                     first_slice = hx->nal_unit_type;
1460                 }
1461
1462             if (avctx->skip_frame >= AVDISCARD_NONREF &&
1463                 h->nal_ref_idc == 0 &&
1464                 h->nal_unit_type != NAL_SEI)
1465                 continue;
1466
1467 again:
1468             if (   !(avctx->active_thread_type & FF_THREAD_FRAME)
1469                 || nals_needed >= nal_index)
1470                 h->au_pps_id = -1;
1471             /* Ignore per frame NAL unit type during extradata
1472              * parsing. Decoding slices is not possible in codec init
1473              * with frame-mt */
1474             if (parse_extradata) {
1475                 switch (hx->nal_unit_type) {
1476                 case NAL_IDR_SLICE:
1477                 case NAL_SLICE:
1478                 case NAL_DPA:
1479                 case NAL_DPB:
1480                 case NAL_DPC:
1481                     av_log(h->avctx, AV_LOG_WARNING,
1482                            "Ignoring NAL %d in global header/extradata\n",
1483                            hx->nal_unit_type);
1484                     // fall through to next case
1485                 case NAL_AUXILIARY_SLICE:
1486                     hx->nal_unit_type = NAL_FF_IGNORE;
1487                 }
1488             }
1489
1490             err = 0;
1491
1492             switch (hx->nal_unit_type) {
1493             case NAL_IDR_SLICE:
1494                 if (h->nal_unit_type != NAL_IDR_SLICE) {
1495                     av_log(h->avctx, AV_LOG_ERROR,
1496                            "Invalid mix of idr and non-idr slices\n");
1497                     ret = -1;
1498                     goto end;
1499                 }
1500                 if(!idr_cleared)
1501                     idr(h); // FIXME ensure we don't lose some frames if there is reordering
1502                 idr_cleared = 1;
1503             case NAL_SLICE:
1504                 init_get_bits(&hx->gb, ptr, bit_length);
1505                 hx->intra_gb_ptr      =
1506                 hx->inter_gb_ptr      = &hx->gb;
1507                 hx->data_partitioning = 0;
1508
1509                 if ((err = ff_h264_decode_slice_header(hx, h)))
1510                     break;
1511
1512                 if (h->sei_recovery_frame_cnt >= 0) {
1513                     if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
1514                         h->valid_recovery_point = 1;
1515
1516                     if (   h->recovery_frame < 0
1517                         || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
1518                         h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1519                                             ((1 << h->sps.log2_max_frame_num) - 1);
1520
1521                         if (!h->valid_recovery_point)
1522                             h->recovery_frame = h->frame_num;
1523                     }
1524                 }
1525
1526                 h->cur_pic_ptr->f.key_frame |=
1527                     (hx->nal_unit_type == NAL_IDR_SLICE);
1528
1529                 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1530                     h->recovery_frame == h->frame_num) {
1531                     h->recovery_frame         = -1;
1532                     h->cur_pic_ptr->recovered = 1;
1533                 }
1534                 // If we have an IDR, all frames after it in decoded order are
1535                 // "recovered".
1536                 if (hx->nal_unit_type == NAL_IDR_SLICE)
1537                     h->frame_recovered |= FRAME_RECOVERED_IDR;
1538                 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1539                 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1540 #if 1
1541                 h->cur_pic_ptr->recovered |= h->frame_recovered;
1542 #else
1543                 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1544 #endif
1545
1546                 if (h->current_slice == 1) {
1547                     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1548                         decode_postinit(h, nal_index >= nals_needed);
1549
1550                     if (h->avctx->hwaccel &&
1551                         (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1552                         return ret;
1553                     if (CONFIG_H264_VDPAU_DECODER &&
1554                         h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1555                         ff_vdpau_h264_picture_start(h);
1556                 }
1557
1558                 if (hx->redundant_pic_count == 0 &&
1559                     (avctx->skip_frame < AVDISCARD_NONREF ||
1560                      hx->nal_ref_idc) &&
1561                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
1562                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1563                     (avctx->skip_frame < AVDISCARD_NONKEY ||
1564                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1565                     avctx->skip_frame < AVDISCARD_ALL) {
1566                     if (avctx->hwaccel) {
1567                         ret = avctx->hwaccel->decode_slice(avctx,
1568                                                            &buf[buf_index - consumed],
1569                                                            consumed);
1570                         if (ret < 0)
1571                             return ret;
1572                     } else if (CONFIG_H264_VDPAU_DECODER &&
1573                                h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1574                         ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1575                                                 start_code,
1576                                                 sizeof(start_code));
1577                         ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1578                                                 &buf[buf_index - consumed],
1579                                                 consumed);
1580                     } else
1581                         context_count++;
1582                 }
1583                 break;
1584             case NAL_DPA:
1585                 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
1586                     av_log(h->avctx, AV_LOG_ERROR,
1587                            "Decoding in chunks is not supported for "
1588                            "partitioned slices.\n");
1589                     return AVERROR(ENOSYS);
1590                 }
1591
1592                 init_get_bits(&hx->gb, ptr, bit_length);
1593                 hx->intra_gb_ptr =
1594                 hx->inter_gb_ptr = NULL;
1595
1596                 if ((err = ff_h264_decode_slice_header(hx, h)) < 0) {
1597                     /* make sure data_partitioning is cleared if it was set
1598                      * before, so we don't try decoding a slice without a valid
1599                      * slice header later */
1600                     h->data_partitioning = 0;
1601                     break;
1602                 }
1603
1604                 hx->data_partitioning = 1;
1605                 break;
1606             case NAL_DPB:
1607                 init_get_bits(&hx->intra_gb, ptr, bit_length);
1608                 hx->intra_gb_ptr = &hx->intra_gb;
1609                 break;
1610             case NAL_DPC:
1611                 init_get_bits(&hx->inter_gb, ptr, bit_length);
1612                 hx->inter_gb_ptr = &hx->inter_gb;
1613
1614                 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
1615                 break;
1616
1617                 if (hx->redundant_pic_count == 0 &&
1618                     hx->intra_gb_ptr &&
1619                     hx->data_partitioning &&
1620                     h->cur_pic_ptr && h->context_initialized &&
1621                     (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
1622                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
1623                      hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1624                     (avctx->skip_frame < AVDISCARD_NONKEY ||
1625                      hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1626                     avctx->skip_frame < AVDISCARD_ALL)
1627                     context_count++;
1628                 break;
1629             case NAL_SEI:
1630                 init_get_bits(&h->gb, ptr, bit_length);
1631                 ff_h264_decode_sei(h);
1632                 break;
1633             case NAL_SPS:
1634                 init_get_bits(&h->gb, ptr, bit_length);
1635                 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
1636                     av_log(h->avctx, AV_LOG_DEBUG,
1637                            "SPS decoding failure, trying again with the complete NAL\n");
1638                     if (h->is_avc)
1639                         av_assert0(next_avc - buf_index + consumed == nalsize);
1640                     if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1641                         break;
1642                     init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1643                                   8*(next_avc - buf_index + consumed - 1));
1644                     ff_h264_decode_seq_parameter_set(h);
1645                 }
1646
1647                 break;
1648             case NAL_PPS:
1649                 init_get_bits(&h->gb, ptr, bit_length);
1650                 ff_h264_decode_picture_parameter_set(h, bit_length);
1651                 break;
1652             case NAL_AUD:
1653             case NAL_END_SEQUENCE:
1654             case NAL_END_STREAM:
1655             case NAL_FILLER_DATA:
1656             case NAL_SPS_EXT:
1657             case NAL_AUXILIARY_SLICE:
1658                 break;
1659             case NAL_FF_IGNORE:
1660                 break;
1661             default:
1662                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1663                        hx->nal_unit_type, bit_length);
1664             }
1665
1666             if (context_count == h->max_contexts) {
1667                 ff_h264_execute_decode_slices(h, context_count);
1668                 context_count = 0;
1669             }
1670
1671             if (err < 0) {
1672                 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1673                 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1674             } else if (err == 1) {
1675                 /* Slice could not be decoded in parallel mode, copy down
1676                  * NAL unit stuff to context 0 and restart. Note that
1677                  * rbsp_buffer is not transferred, but since we no longer
1678                  * run in parallel mode this should not be an issue. */
1679                 h->nal_unit_type = hx->nal_unit_type;
1680                 h->nal_ref_idc   = hx->nal_ref_idc;
1681                 hx               = h;
1682                 goto again;
1683             }
1684         }
1685     }
1686     if (context_count)
1687         ff_h264_execute_decode_slices(h, context_count);
1688
1689 end:
1690     /* clean up */
1691     if (h->cur_pic_ptr && !h->droppable) {
1692         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1693                                   h->picture_structure == PICT_BOTTOM_FIELD);
1694     }
1695
1696     return (ret < 0) ? ret : buf_index;
1697 }
1698
1699 /**
1700  * Return the number of bytes consumed for building the current frame.
1701  */
1702 static int get_consumed_bytes(int pos, int buf_size)
1703 {
1704     if (pos == 0)
1705         pos = 1;          // avoid infinite loops (i doubt that is needed but ...)
1706     if (pos + 10 > buf_size)
1707         pos = buf_size;                   // oops ;)
1708
1709     return pos;
1710 }
1711
1712 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1713 {
1714     AVFrame *src = &srcp->f;
1715     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1716     int i;
1717     int ret = av_frame_ref(dst, src);
1718     if (ret < 0)
1719         return ret;
1720
1721     av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1722
1723     if (!srcp->crop)
1724         return 0;
1725
1726     for (i = 0; i < desc->nb_components; i++) {
1727         int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1728         int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1729         int off    = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1730                       (srcp->crop_top  >> vshift) * dst->linesize[i];
1731         dst->data[i] += off;
1732     }
1733     return 0;
1734 }
1735
1736 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1737                              int *got_frame, AVPacket *avpkt)
1738 {
1739     const uint8_t *buf = avpkt->data;
1740     int buf_size       = avpkt->size;
1741     H264Context *h     = avctx->priv_data;
1742     AVFrame *pict      = data;
1743     int buf_index      = 0;
1744     H264Picture *out;
1745     int i, out_idx;
1746     int ret;
1747
1748     h->flags = avctx->flags;
1749     /* reset data partitioning here, to ensure GetBitContexts from previous
1750      * packets do not get used. */
1751     h->data_partitioning = 0;
1752
1753     /* end of stream, output what is still in the buffers */
1754     if (buf_size == 0) {
1755  out:
1756
1757         h->cur_pic_ptr = NULL;
1758         h->first_field = 0;
1759
1760         // FIXME factorize this with the output code below
1761         out     = h->delayed_pic[0];
1762         out_idx = 0;
1763         for (i = 1;
1764              h->delayed_pic[i] &&
1765              !h->delayed_pic[i]->f.key_frame &&
1766              !h->delayed_pic[i]->mmco_reset;
1767              i++)
1768             if (h->delayed_pic[i]->poc < out->poc) {
1769                 out     = h->delayed_pic[i];
1770                 out_idx = i;
1771             }
1772
1773         for (i = out_idx; h->delayed_pic[i]; i++)
1774             h->delayed_pic[i] = h->delayed_pic[i + 1];
1775
1776         if (out) {
1777             out->reference &= ~DELAYED_PIC_REF;
1778             ret = output_frame(h, pict, out);
1779             if (ret < 0)
1780                 return ret;
1781             *got_frame = 1;
1782         }
1783
1784         return buf_index;
1785     }
1786     if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1787         int cnt= buf[5]&0x1f;
1788         const uint8_t *p= buf+6;
1789         while(cnt--){
1790             int nalsize= AV_RB16(p) + 2;
1791             if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1792                 goto not_extra;
1793             p += nalsize;
1794         }
1795         cnt = *(p++);
1796         if(!cnt)
1797             goto not_extra;
1798         while(cnt--){
1799             int nalsize= AV_RB16(p) + 2;
1800             if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1801                 goto not_extra;
1802             p += nalsize;
1803         }
1804
1805         return ff_h264_decode_extradata(h, buf, buf_size);
1806     }
1807 not_extra:
1808
1809     buf_index = decode_nal_units(h, buf, buf_size, 0);
1810     if (buf_index < 0)
1811         return AVERROR_INVALIDDATA;
1812
1813     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1814         av_assert0(buf_index <= buf_size);
1815         goto out;
1816     }
1817
1818     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1819         if (avctx->skip_frame >= AVDISCARD_NONREF ||
1820             buf_size >= 4 && !memcmp("Q264", buf, 4))
1821             return buf_size;
1822         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1823         return AVERROR_INVALIDDATA;
1824     }
1825
1826     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1827         (h->mb_y >= h->mb_height && h->mb_height)) {
1828         if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1829             decode_postinit(h, 1);
1830
1831         ff_h264_field_end(h, 0);
1832
1833         /* Wait for second field. */
1834         *got_frame = 0;
1835         if (h->next_output_pic && (
1836                                    h->next_output_pic->recovered)) {
1837             if (!h->next_output_pic->recovered)
1838                 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1839
1840             ret = output_frame(h, pict, h->next_output_pic);
1841             if (ret < 0)
1842                 return ret;
1843             *got_frame = 1;
1844             if (CONFIG_MPEGVIDEO) {
1845                 ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
1846                                     h->next_output_pic->mb_type,
1847                                     h->next_output_pic->qscale_table,
1848                                     h->next_output_pic->motion_val,
1849                                     &h->low_delay,
1850                                     h->mb_width, h->mb_height, h->mb_stride, 1);
1851             }
1852         }
1853     }
1854
1855     assert(pict->buf[0] || !*got_frame);
1856
1857     return get_consumed_bytes(buf_index, buf_size);
1858 }
1859
1860 av_cold void ff_h264_free_context(H264Context *h)
1861 {
1862     int i;
1863
1864     ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1865
1866     for (i = 0; i < MAX_SPS_COUNT; i++)
1867         av_freep(h->sps_buffers + i);
1868
1869     for (i = 0; i < MAX_PPS_COUNT; i++)
1870         av_freep(h->pps_buffers + i);
1871 }
1872
1873 static av_cold int h264_decode_end(AVCodecContext *avctx)
1874 {
1875     H264Context *h = avctx->priv_data;
1876
1877     ff_h264_remove_all_refs(h);
1878     ff_h264_free_context(h);
1879
1880     ff_h264_unref_picture(h, &h->cur_pic);
1881
1882     return 0;
1883 }
1884
1885 static const AVProfile profiles[] = {
1886     { FF_PROFILE_H264_BASELINE,             "Baseline"              },
1887     { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
1888     { FF_PROFILE_H264_MAIN,                 "Main"                  },
1889     { FF_PROFILE_H264_EXTENDED,             "Extended"              },
1890     { FF_PROFILE_H264_HIGH,                 "High"                  },
1891     { FF_PROFILE_H264_HIGH_10,              "High 10"               },
1892     { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
1893     { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
1894     { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
1895     { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
1896     { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
1897     { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
1898     { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
1899     { FF_PROFILE_UNKNOWN },
1900 };
1901
1902 static const AVOption h264_options[] = {
1903     {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1904     {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1905     {NULL}
1906 };
1907
1908 static const AVClass h264_class = {
1909     .class_name = "H264 Decoder",
1910     .item_name  = av_default_item_name,
1911     .option     = h264_options,
1912     .version    = LIBAVUTIL_VERSION_INT,
1913 };
1914
1915 static const AVClass h264_vdpau_class = {
1916     .class_name = "H264 VDPAU Decoder",
1917     .item_name  = av_default_item_name,
1918     .option     = h264_options,
1919     .version    = LIBAVUTIL_VERSION_INT,
1920 };
1921
1922 AVCodec ff_h264_decoder = {
1923     .name                  = "h264",
1924     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1925     .type                  = AVMEDIA_TYPE_VIDEO,
1926     .id                    = AV_CODEC_ID_H264,
1927     .priv_data_size        = sizeof(H264Context),
1928     .init                  = ff_h264_decode_init,
1929     .close                 = h264_decode_end,
1930     .decode                = h264_decode_frame,
1931     .capabilities          = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1932                              CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1933                              CODEC_CAP_FRAME_THREADS,
1934     .flush                 = flush_dpb,
1935     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1936     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1937     .profiles              = NULL_IF_CONFIG_SMALL(profiles),
1938     .priv_class            = &h264_class,
1939 };
1940
1941 #if CONFIG_H264_VDPAU_DECODER
1942 AVCodec ff_h264_vdpau_decoder = {
1943     .name           = "h264_vdpau",
1944     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1945     .type           = AVMEDIA_TYPE_VIDEO,
1946     .id             = AV_CODEC_ID_H264,
1947     .priv_data_size = sizeof(H264Context),
1948     .init           = ff_h264_decode_init,
1949     .close          = h264_decode_end,
1950     .decode         = h264_decode_frame,
1951     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
1952     .flush          = flush_dpb,
1953     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
1954                                                      AV_PIX_FMT_NONE},
1955     .profiles       = NULL_IF_CONFIG_SMALL(profiles),
1956     .priv_class     = &h264_vdpau_class,
1957 };
1958 #endif