]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
Merge commit '69a638019fc0db4c2b75b36ef45d0acb6d2e9628'
[ffmpeg] / libavcodec / h264.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... decoder
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * H.264 / AVC / MPEG4 part10 codec.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #define UNCHECKED_BITSTREAM_READER 1
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/display.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/stereo3d.h"
35 #include "libavutil/timer.h"
36 #include "internal.h"
37 #include "bytestream.h"
38 #include "cabac.h"
39 #include "cabac_functions.h"
40 #include "error_resilience.h"
41 #include "avcodec.h"
42 #include "h264.h"
43 #include "h2645_parse.h"
44 #include "h264data.h"
45 #include "h264chroma.h"
46 #include "h264_mvpred.h"
47 #include "golomb.h"
48 #include "mathops.h"
49 #include "me_cmp.h"
50 #include "mpegutils.h"
51 #include "profiles.h"
52 #include "rectangle.h"
53 #include "thread.h"
54 #include "vdpau_compat.h"
55
56 static int h264_decode_end(AVCodecContext *avctx);
57
58 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
59
60 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
61 {
62     H264Context *h = avctx->priv_data;
63     return h ? h->sps.num_reorder_frames : 0;
64 }
65
66 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
67                               int (*mv)[2][4][2],
68                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
69 {
70     H264Context *h = opaque;
71     H264SliceContext *sl = &h->slice_ctx[0];
72
73     sl->mb_x = mb_x;
74     sl->mb_y = mb_y;
75     sl->mb_xy = mb_x + mb_y * h->mb_stride;
76     memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
77     av_assert1(ref >= 0);
78     /* FIXME: It is possible albeit uncommon that slice references
79      * differ between slices. We take the easy approach and ignore
80      * it for now. If this turns out to have any relevance in
81      * practice then correct remapping should be added. */
82     if (ref >= sl->ref_count[0])
83         ref = 0;
84     if (!sl->ref_list[0][ref].data[0]) {
85         av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
86         ref = 0;
87     }
88     if ((sl->ref_list[0][ref].reference&3) != 3) {
89         av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
90         return;
91     }
92     fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
93                    2, 2, 2, ref, 1);
94     fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
95     fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
96                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
97     sl->mb_mbaff =
98     sl->mb_field_decoding_flag = 0;
99     ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
100 }
101
102 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
103                              int y, int height)
104 {
105     AVCodecContext *avctx = h->avctx;
106     const AVFrame   *src  = h->cur_pic.f;
107     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
108     int vshift = desc->log2_chroma_h;
109     const int field_pic = h->picture_structure != PICT_FRAME;
110     if (field_pic) {
111         height <<= 1;
112         y      <<= 1;
113     }
114
115     height = FFMIN(height, avctx->height - y);
116
117     if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
118         return;
119
120     if (avctx->draw_horiz_band) {
121         int offset[AV_NUM_DATA_POINTERS];
122         int i;
123
124         offset[0] = y * src->linesize[0];
125         offset[1] =
126         offset[2] = (y >> vshift) * src->linesize[1];
127         for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
128             offset[i] = 0;
129
130         emms_c();
131
132         avctx->draw_horiz_band(avctx, src, offset,
133                                y, h->picture_structure, height);
134     }
135 }
136
137 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
138                                   const uint8_t *src,
139                                   int *dst_length, int *consumed, int length)
140 {
141     int i, si, di;
142     uint8_t *dst;
143
144     // src[0]&0x80; // forbidden bit
145     h->nal_ref_idc   = src[0] >> 5;
146     h->nal_unit_type = src[0] & 0x1F;
147
148     src++;
149     length--;
150
151 #define STARTCODE_TEST                                                  \
152     if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {         \
153         if (src[i + 2] != 3 && src[i + 2] != 0) {                       \
154             /* startcode, so we must be past the end */                 \
155             length = i;                                                 \
156         }                                                               \
157         break;                                                          \
158     }
159
160 #if HAVE_FAST_UNALIGNED
161 #define FIND_FIRST_ZERO                                                 \
162     if (i > 0 && !src[i])                                               \
163         i--;                                                            \
164     while (src[i])                                                      \
165         i++
166
167 #if HAVE_FAST_64BIT
168     for (i = 0; i + 1 < length; i += 9) {
169         if (!((~AV_RN64A(src + i) &
170                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
171               0x8000800080008080ULL))
172             continue;
173         FIND_FIRST_ZERO;
174         STARTCODE_TEST;
175         i -= 7;
176     }
177 #else
178     for (i = 0; i + 1 < length; i += 5) {
179         if (!((~AV_RN32A(src + i) &
180                (AV_RN32A(src + i) - 0x01000101U)) &
181               0x80008080U))
182             continue;
183         FIND_FIRST_ZERO;
184         STARTCODE_TEST;
185         i -= 3;
186     }
187 #endif
188 #else
189     for (i = 0; i + 1 < length; i += 2) {
190         if (src[i])
191             continue;
192         if (i > 0 && src[i - 1] == 0)
193             i--;
194         STARTCODE_TEST;
195     }
196 #endif
197
198     av_fast_padded_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size, length+MAX_MBPAIR_SIZE);
199     dst = sl->rbsp_buffer;
200
201     if (!dst)
202         return NULL;
203
204     if(i>=length-1){ //no escaped 0
205         *dst_length= length;
206         *consumed= length+1; //+1 for the header
207         if(h->avctx->flags2 & AV_CODEC_FLAG2_FAST){
208             return src;
209         }else{
210             memcpy(dst, src, length);
211             return dst;
212         }
213     }
214
215     memcpy(dst, src, i);
216     si = di = i;
217     while (si + 2 < length) {
218         // remove escapes (very rare 1:2^22)
219         if (src[si + 2] > 3) {
220             dst[di++] = src[si++];
221             dst[di++] = src[si++];
222         } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
223             if (src[si + 2] == 3) { // escape
224                 dst[di++]  = 0;
225                 dst[di++]  = 0;
226                 si        += 3;
227                 continue;
228             } else // next start code
229                 goto nsc;
230         }
231
232         dst[di++] = src[si++];
233     }
234     while (si < length)
235         dst[di++] = src[si++];
236
237 nsc:
238     memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
239
240     *dst_length = di;
241     *consumed   = si + 1; // +1 for the header
242     /* FIXME store exact number of bits in the getbitcontext
243      * (it is needed for decoding) */
244     return dst;
245 }
246
247 void ff_h264_free_tables(H264Context *h)
248 {
249     int i;
250
251     av_freep(&h->intra4x4_pred_mode);
252     av_freep(&h->chroma_pred_mode_table);
253     av_freep(&h->cbp_table);
254     av_freep(&h->mvd_table[0]);
255     av_freep(&h->mvd_table[1]);
256     av_freep(&h->direct_table);
257     av_freep(&h->non_zero_count);
258     av_freep(&h->slice_table_base);
259     h->slice_table = NULL;
260     av_freep(&h->list_counts);
261
262     av_freep(&h->mb2b_xy);
263     av_freep(&h->mb2br_xy);
264
265     av_buffer_pool_uninit(&h->qscale_table_pool);
266     av_buffer_pool_uninit(&h->mb_type_pool);
267     av_buffer_pool_uninit(&h->motion_val_pool);
268     av_buffer_pool_uninit(&h->ref_index_pool);
269
270     for (i = 0; i < h->nb_slice_ctx; i++) {
271         H264SliceContext *sl = &h->slice_ctx[i];
272
273         av_freep(&sl->dc_val_base);
274         av_freep(&sl->er.mb_index2xy);
275         av_freep(&sl->er.error_status_table);
276         av_freep(&sl->er.er_temp_buffer);
277
278         av_freep(&sl->bipred_scratchpad);
279         av_freep(&sl->edge_emu_buffer);
280         av_freep(&sl->top_borders[0]);
281         av_freep(&sl->top_borders[1]);
282
283         sl->bipred_scratchpad_allocated = 0;
284         sl->edge_emu_buffer_allocated   = 0;
285         sl->top_borders_allocated[0]    = 0;
286         sl->top_borders_allocated[1]    = 0;
287     }
288 }
289
290 int ff_h264_alloc_tables(H264Context *h)
291 {
292     const int big_mb_num = h->mb_stride * (h->mb_height + 1);
293     const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
294     int x, y;
295
296     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
297                       row_mb_num, 8 * sizeof(uint8_t), fail)
298     h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
299
300     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
301                       big_mb_num * 48 * sizeof(uint8_t), fail)
302     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
303                       (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
304     FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
305                       big_mb_num * sizeof(uint16_t), fail)
306     FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
307                       big_mb_num * sizeof(uint8_t), fail)
308     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
309                       row_mb_num, 16 * sizeof(uint8_t), fail);
310     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
311                       row_mb_num, 16 * sizeof(uint8_t), fail);
312     h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
313     h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
314
315     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
316                       4 * big_mb_num * sizeof(uint8_t), fail);
317     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
318                       big_mb_num * sizeof(uint8_t), fail)
319
320     memset(h->slice_table_base, -1,
321            (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
322     h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
323
324     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
325                       big_mb_num * sizeof(uint32_t), fail);
326     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
327                       big_mb_num * sizeof(uint32_t), fail);
328     for (y = 0; y < h->mb_height; y++)
329         for (x = 0; x < h->mb_width; x++) {
330             const int mb_xy = x + y * h->mb_stride;
331             const int b_xy  = 4 * x + 4 * y * h->b_stride;
332
333             h->mb2b_xy[mb_xy]  = b_xy;
334             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
335         }
336
337     if (!h->dequant4_coeff[0])
338         ff_h264_init_dequant_tables(h);
339
340     return 0;
341
342 fail:
343     ff_h264_free_tables(h);
344     return AVERROR(ENOMEM);
345 }
346
347 /**
348  * Init context
349  * Allocate buffers which are not shared amongst multiple threads.
350  */
351 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
352 {
353     ERContext *er = &sl->er;
354     int mb_array_size = h->mb_height * h->mb_stride;
355     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
356     int c_size  = h->mb_stride * (h->mb_height + 1);
357     int yc_size = y_size + 2   * c_size;
358     int x, y, i;
359
360     sl->ref_cache[0][scan8[5]  + 1] =
361     sl->ref_cache[0][scan8[7]  + 1] =
362     sl->ref_cache[0][scan8[13] + 1] =
363     sl->ref_cache[1][scan8[5]  + 1] =
364     sl->ref_cache[1][scan8[7]  + 1] =
365     sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
366
367     if (sl != h->slice_ctx) {
368         memset(er, 0, sizeof(*er));
369     } else
370     if (CONFIG_ERROR_RESILIENCE) {
371
372         /* init ER */
373         er->avctx          = h->avctx;
374         er->decode_mb      = h264_er_decode_mb;
375         er->opaque         = h;
376         er->quarter_sample = 1;
377
378         er->mb_num      = h->mb_num;
379         er->mb_width    = h->mb_width;
380         er->mb_height   = h->mb_height;
381         er->mb_stride   = h->mb_stride;
382         er->b8_stride   = h->mb_width * 2 + 1;
383
384         // error resilience code looks cleaner with this
385         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
386                           (h->mb_num + 1) * sizeof(int), fail);
387
388         for (y = 0; y < h->mb_height; y++)
389             for (x = 0; x < h->mb_width; x++)
390                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
391
392         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
393                                                       h->mb_stride + h->mb_width;
394
395         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
396                           mb_array_size * sizeof(uint8_t), fail);
397
398         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
399                          h->mb_height * h->mb_stride, fail);
400
401         FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
402                           yc_size * sizeof(int16_t), fail);
403         er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
404         er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
405         er->dc_val[2] = er->dc_val[1] + c_size;
406         for (i = 0; i < yc_size; i++)
407             sl->dc_val_base[i] = 1024;
408     }
409
410     return 0;
411
412 fail:
413     return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
414 }
415
416 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
417                             int parse_extradata);
418
419 /* There are (invalid) samples in the wild with mp4-style extradata, where the
420  * parameter sets are stored unescaped (i.e. as RBSP).
421  * This function catches the parameter set decoding failure and tries again
422  * after escaping it */
423 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
424 {
425     int ret;
426
427     ret = decode_nal_units(h, buf, buf_size, 1);
428     if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
429         GetByteContext gbc;
430         PutByteContext pbc;
431         uint8_t *escaped_buf;
432         int escaped_buf_size;
433
434         av_log(h->avctx, AV_LOG_WARNING,
435                "SPS decoding failure, trying again after escaping the NAL\n");
436
437         if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
438             return AVERROR(ERANGE);
439         escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
440         escaped_buf = av_mallocz(escaped_buf_size);
441         if (!escaped_buf)
442             return AVERROR(ENOMEM);
443
444         bytestream2_init(&gbc, buf, buf_size);
445         bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
446
447         while (bytestream2_get_bytes_left(&gbc)) {
448             if (bytestream2_get_bytes_left(&gbc) >= 3 &&
449                 bytestream2_peek_be24(&gbc) <= 3) {
450                 bytestream2_put_be24(&pbc, 3);
451                 bytestream2_skip(&gbc, 2);
452             } else
453                 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
454         }
455
456         escaped_buf_size = bytestream2_tell_p(&pbc);
457         AV_WB16(escaped_buf, escaped_buf_size - 2);
458
459         ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
460         av_freep(&escaped_buf);
461         if (ret < 0)
462             return ret;
463     }
464
465     return 0;
466 }
467
468 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
469 {
470     AVCodecContext *avctx = h->avctx;
471     int ret;
472
473     if (!buf || size <= 0)
474         return -1;
475
476     if (buf[0] == 1) {
477         int i, cnt, nalsize;
478         const unsigned char *p = buf;
479
480         h->is_avc = 1;
481
482         if (size < 7) {
483             av_log(avctx, AV_LOG_ERROR,
484                    "avcC %d too short\n", size);
485             return AVERROR_INVALIDDATA;
486         }
487         /* sps and pps in the avcC always have length coded with 2 bytes,
488          * so put a fake nal_length_size = 2 while parsing them */
489         h->nal_length_size = 2;
490         // Decode sps from avcC
491         cnt = *(p + 5) & 0x1f; // Number of sps
492         p  += 6;
493         for (i = 0; i < cnt; i++) {
494             nalsize = AV_RB16(p) + 2;
495             if(nalsize > size - (p-buf))
496                 return AVERROR_INVALIDDATA;
497             ret = decode_extradata_ps_mp4(h, p, nalsize);
498             if (ret < 0) {
499                 av_log(avctx, AV_LOG_ERROR,
500                        "Decoding sps %d from avcC failed\n", i);
501                 return ret;
502             }
503             p += nalsize;
504         }
505         // Decode pps from avcC
506         cnt = *(p++); // Number of pps
507         for (i = 0; i < cnt; i++) {
508             nalsize = AV_RB16(p) + 2;
509             if(nalsize > size - (p-buf))
510                 return AVERROR_INVALIDDATA;
511             ret = decode_extradata_ps_mp4(h, p, nalsize);
512             if (ret < 0) {
513                 av_log(avctx, AV_LOG_ERROR,
514                        "Decoding pps %d from avcC failed\n", i);
515                 return ret;
516             }
517             p += nalsize;
518         }
519         // Store right nal length size that will be used to parse all other nals
520         h->nal_length_size = (buf[4] & 0x03) + 1;
521     } else {
522         h->is_avc = 0;
523         ret = decode_nal_units(h, buf, size, 1);
524         if (ret < 0)
525             return ret;
526     }
527     return size;
528 }
529
530 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
531 {
532     int i;
533
534     h->avctx                 = avctx;
535     h->backup_width          = -1;
536     h->backup_height         = -1;
537     h->backup_pix_fmt        = AV_PIX_FMT_NONE;
538     h->dequant_coeff_pps     = -1;
539     h->current_sps_id        = -1;
540     h->cur_chroma_format_idc = -1;
541
542     h->picture_structure     = PICT_FRAME;
543     h->slice_context_count   = 1;
544     h->workaround_bugs       = avctx->workaround_bugs;
545     h->flags                 = avctx->flags;
546     h->prev_poc_msb          = 1 << 16;
547     h->x264_build            = -1;
548     h->recovery_frame        = -1;
549     h->frame_recovered       = 0;
550     h->prev_frame_num        = -1;
551     h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
552
553     h->next_outputed_poc = INT_MIN;
554     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
555         h->last_pocs[i] = INT_MIN;
556
557     ff_h264_reset_sei(h);
558
559     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
560
561     h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;
562     h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
563     if (!h->slice_ctx) {
564         h->nb_slice_ctx = 0;
565         return AVERROR(ENOMEM);
566     }
567
568     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
569         h->DPB[i].f = av_frame_alloc();
570         if (!h->DPB[i].f)
571             return AVERROR(ENOMEM);
572     }
573
574     h->cur_pic.f = av_frame_alloc();
575     if (!h->cur_pic.f)
576         return AVERROR(ENOMEM);
577
578     h->last_pic_for_ec.f = av_frame_alloc();
579     if (!h->last_pic_for_ec.f)
580         return AVERROR(ENOMEM);
581
582     for (i = 0; i < h->nb_slice_ctx; i++)
583         h->slice_ctx[i].h264 = h;
584
585     return 0;
586 }
587
588 static AVOnce h264_vlc_init = AV_ONCE_INIT;
589
590 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
591 {
592     H264Context *h = avctx->priv_data;
593     int ret;
594
595     ret = h264_init_context(avctx, h);
596     if (ret < 0)
597         return ret;
598
599     /* set defaults */
600     if (!avctx->has_b_frames)
601         h->low_delay = 1;
602
603     ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
604     if (ret != 0) {
605         av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
606         return AVERROR_UNKNOWN;
607     }
608
609     if (avctx->codec_id == AV_CODEC_ID_H264) {
610         if (avctx->ticks_per_frame == 1) {
611             if(h->avctx->time_base.den < INT_MAX/2) {
612                 h->avctx->time_base.den *= 2;
613             } else
614                 h->avctx->time_base.num /= 2;
615         }
616         avctx->ticks_per_frame = 2;
617     }
618
619     if (avctx->extradata_size > 0 && avctx->extradata) {
620         ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
621         if (ret < 0) {
622             h264_decode_end(avctx);
623             return ret;
624         }
625     }
626
627     if (h->sps.bitstream_restriction_flag &&
628         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
629         h->avctx->has_b_frames = h->sps.num_reorder_frames;
630         h->low_delay           = 0;
631     }
632
633     avctx->internal->allocate_progress = 1;
634
635     ff_h264_flush_change(h);
636
637     if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
638         h->enable_er = 0;
639
640     if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
641         av_log(avctx, AV_LOG_WARNING,
642                "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
643                "Use it at your own risk\n");
644     }
645
646     return 0;
647 }
648
649 #if HAVE_THREADS
650 static int decode_init_thread_copy(AVCodecContext *avctx)
651 {
652     H264Context *h = avctx->priv_data;
653     int ret;
654
655     if (!avctx->internal->is_copy)
656         return 0;
657
658     memset(h, 0, sizeof(*h));
659
660     ret = h264_init_context(avctx, h);
661     if (ret < 0)
662         return ret;
663
664     h->context_initialized = 0;
665
666     return 0;
667 }
668 #endif
669
670 /**
671  * Run setup operations that must be run after slice header decoding.
672  * This includes finding the next displayed frame.
673  *
674  * @param h h264 master context
675  * @param setup_finished enough NALs have been read that we can call
676  * ff_thread_finish_setup()
677  */
678 static void decode_postinit(H264Context *h, int setup_finished)
679 {
680     H264Picture *out = h->cur_pic_ptr;
681     H264Picture *cur = h->cur_pic_ptr;
682     int i, pics, out_of_order, out_idx;
683
684     h->cur_pic_ptr->f->pict_type = h->pict_type;
685
686     if (h->next_output_pic)
687         return;
688
689     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
690         /* FIXME: if we have two PAFF fields in one packet, we can't start
691          * the next thread here. If we have one field per packet, we can.
692          * The check in decode_nal_units() is not good enough to find this
693          * yet, so we assume the worst for now. */
694         // if (setup_finished)
695         //    ff_thread_finish_setup(h->avctx);
696         if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
697             return;
698         if (h->avctx->hwaccel || h->missing_fields <=1)
699             return;
700     }
701
702     cur->f->interlaced_frame = 0;
703     cur->f->repeat_pict      = 0;
704
705     /* Signal interlacing information externally. */
706     /* Prioritize picture timing SEI information over used
707      * decoding process if it exists. */
708
709     if (h->sps.pic_struct_present_flag) {
710         switch (h->sei_pic_struct) {
711         case SEI_PIC_STRUCT_FRAME:
712             break;
713         case SEI_PIC_STRUCT_TOP_FIELD:
714         case SEI_PIC_STRUCT_BOTTOM_FIELD:
715             cur->f->interlaced_frame = 1;
716             break;
717         case SEI_PIC_STRUCT_TOP_BOTTOM:
718         case SEI_PIC_STRUCT_BOTTOM_TOP:
719             if (FIELD_OR_MBAFF_PICTURE(h))
720                 cur->f->interlaced_frame = 1;
721             else
722                 // try to flag soft telecine progressive
723                 cur->f->interlaced_frame = h->prev_interlaced_frame;
724             break;
725         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
726         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
727             /* Signal the possibility of telecined film externally
728              * (pic_struct 5,6). From these hints, let the applications
729              * decide if they apply deinterlacing. */
730             cur->f->repeat_pict = 1;
731             break;
732         case SEI_PIC_STRUCT_FRAME_DOUBLING:
733             cur->f->repeat_pict = 2;
734             break;
735         case SEI_PIC_STRUCT_FRAME_TRIPLING:
736             cur->f->repeat_pict = 4;
737             break;
738         }
739
740         if ((h->sei_ct_type & 3) &&
741             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
742             cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
743     } else {
744         /* Derive interlacing flag from used decoding process. */
745         cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
746     }
747     h->prev_interlaced_frame = cur->f->interlaced_frame;
748
749     if (cur->field_poc[0] != cur->field_poc[1]) {
750         /* Derive top_field_first from field pocs. */
751         cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
752     } else {
753         if (h->sps.pic_struct_present_flag) {
754             /* Use picture timing SEI information. Even if it is a
755              * information of a past frame, better than nothing. */
756             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
757                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
758                 cur->f->top_field_first = 1;
759             else
760                 cur->f->top_field_first = 0;
761         } else if (cur->f->interlaced_frame) {
762             /* Default to top field first when pic_struct_present_flag
763              * is not set but interlaced frame detected */
764             cur->f->top_field_first = 1;
765         } else {
766             /* Most likely progressive */
767             cur->f->top_field_first = 0;
768         }
769     }
770
771     if (h->sei_frame_packing_present &&
772         h->frame_packing_arrangement_type >= 0 &&
773         h->frame_packing_arrangement_type <= 6 &&
774         h->content_interpretation_type > 0 &&
775         h->content_interpretation_type < 3) {
776         AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
777         if (stereo) {
778         switch (h->frame_packing_arrangement_type) {
779         case 0:
780             stereo->type = AV_STEREO3D_CHECKERBOARD;
781             break;
782         case 1:
783             stereo->type = AV_STEREO3D_COLUMNS;
784             break;
785         case 2:
786             stereo->type = AV_STEREO3D_LINES;
787             break;
788         case 3:
789             if (h->quincunx_subsampling)
790                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
791             else
792                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
793             break;
794         case 4:
795             stereo->type = AV_STEREO3D_TOPBOTTOM;
796             break;
797         case 5:
798             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
799             break;
800         case 6:
801             stereo->type = AV_STEREO3D_2D;
802             break;
803         }
804
805         if (h->content_interpretation_type == 2)
806             stereo->flags = AV_STEREO3D_FLAG_INVERT;
807         }
808     }
809
810     if (h->sei_display_orientation_present &&
811         (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
812         double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
813         AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
814                                                            AV_FRAME_DATA_DISPLAYMATRIX,
815                                                            sizeof(int32_t) * 9);
816         if (rotation) {
817             av_display_rotation_set((int32_t *)rotation->data, angle);
818             av_display_matrix_flip((int32_t *)rotation->data,
819                                    h->sei_hflip, h->sei_vflip);
820         }
821     }
822
823     if (h->sei_reguserdata_afd_present) {
824         AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
825                                                      sizeof(uint8_t));
826
827         if (sd) {
828             *sd->data = h->active_format_description;
829             h->sei_reguserdata_afd_present = 0;
830         }
831     }
832
833     if (h->a53_caption) {
834         AVFrameSideData *sd = av_frame_new_side_data(cur->f,
835                                                      AV_FRAME_DATA_A53_CC,
836                                                      h->a53_caption_size);
837         if (sd)
838             memcpy(sd->data, h->a53_caption, h->a53_caption_size);
839         av_freep(&h->a53_caption);
840         h->a53_caption_size = 0;
841         h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
842     }
843
844     cur->mmco_reset = h->mmco_reset;
845     h->mmco_reset = 0;
846
847     // FIXME do something with unavailable reference frames
848
849     /* Sort B-frames into display order */
850     if (h->sps.bitstream_restriction_flag ||
851         h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
852         h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
853     }
854     h->low_delay = !h->avctx->has_b_frames;
855
856     for (i = 0; 1; i++) {
857         if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
858             if(i)
859                 h->last_pocs[i-1] = cur->poc;
860             break;
861         } else if(i) {
862             h->last_pocs[i-1]= h->last_pocs[i];
863         }
864     }
865     out_of_order = MAX_DELAYED_PIC_COUNT - i;
866     if(   cur->f->pict_type == AV_PICTURE_TYPE_B
867        || (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))
868         out_of_order = FFMAX(out_of_order, 1);
869     if (out_of_order == MAX_DELAYED_PIC_COUNT) {
870         av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
871         for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
872             h->last_pocs[i] = INT_MIN;
873         h->last_pocs[0] = cur->poc;
874         cur->mmco_reset = 1;
875     } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
876         av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
877         h->avctx->has_b_frames = out_of_order;
878         h->low_delay = 0;
879     }
880
881     pics = 0;
882     while (h->delayed_pic[pics])
883         pics++;
884
885     av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
886
887     h->delayed_pic[pics++] = cur;
888     if (cur->reference == 0)
889         cur->reference = DELAYED_PIC_REF;
890
891     out     = h->delayed_pic[0];
892     out_idx = 0;
893     for (i = 1; h->delayed_pic[i] &&
894                 !h->delayed_pic[i]->f->key_frame &&
895                 !h->delayed_pic[i]->mmco_reset;
896          i++)
897         if (h->delayed_pic[i]->poc < out->poc) {
898             out     = h->delayed_pic[i];
899             out_idx = i;
900         }
901     if (h->avctx->has_b_frames == 0 &&
902         (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
903         h->next_outputed_poc = INT_MIN;
904     out_of_order = out->poc < h->next_outputed_poc;
905
906     if (out_of_order || pics > h->avctx->has_b_frames) {
907         out->reference &= ~DELAYED_PIC_REF;
908         // for frame threading, the owner must be the second field's thread or
909         // else the first thread can release the picture and reuse it unsafely
910         for (i = out_idx; h->delayed_pic[i]; i++)
911             h->delayed_pic[i] = h->delayed_pic[i + 1];
912     }
913     if (!out_of_order && pics > h->avctx->has_b_frames) {
914         h->next_output_pic = out;
915         if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
916             h->next_outputed_poc = INT_MIN;
917         } else
918             h->next_outputed_poc = out->poc;
919     } else {
920         av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
921     }
922
923     if (h->next_output_pic) {
924         if (h->next_output_pic->recovered) {
925             // We have reached an recovery point and all frames after it in
926             // display order are "recovered".
927             h->frame_recovered |= FRAME_RECOVERED_SEI;
928         }
929         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
930     }
931
932     if (setup_finished && !h->avctx->hwaccel) {
933         ff_thread_finish_setup(h->avctx);
934
935         if (h->avctx->active_thread_type & FF_THREAD_FRAME)
936             h->setup_finished = 1;
937     }
938 }
939
940 /**
941  * instantaneous decoder refresh.
942  */
943 static void idr(H264Context *h)
944 {
945     int i;
946     ff_h264_remove_all_refs(h);
947     h->prev_frame_num        =
948     h->prev_frame_num_offset = 0;
949     h->prev_poc_msb          = 1<<16;
950     h->prev_poc_lsb          = 0;
951     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
952         h->last_pocs[i] = INT_MIN;
953 }
954
955 /* forget old pics after a seek */
956 void ff_h264_flush_change(H264Context *h)
957 {
958     int i, j;
959
960     h->next_outputed_poc = INT_MIN;
961     h->prev_interlaced_frame = 1;
962     idr(h);
963
964     h->prev_frame_num = -1;
965     if (h->cur_pic_ptr) {
966         h->cur_pic_ptr->reference = 0;
967         for (j=i=0; h->delayed_pic[i]; i++)
968             if (h->delayed_pic[i] != h->cur_pic_ptr)
969                 h->delayed_pic[j++] = h->delayed_pic[i];
970         h->delayed_pic[j] = NULL;
971     }
972     ff_h264_unref_picture(h, &h->last_pic_for_ec);
973
974     h->first_field = 0;
975     ff_h264_reset_sei(h);
976     h->recovery_frame = -1;
977     h->frame_recovered = 0;
978     h->current_slice = 0;
979     h->mmco_reset = 1;
980     for (i = 0; i < h->nb_slice_ctx; i++)
981         h->slice_ctx[i].list_count = 0;
982 }
983
984 /* forget old pics after a seek */
985 static void flush_dpb(AVCodecContext *avctx)
986 {
987     H264Context *h = avctx->priv_data;
988     int i;
989
990     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
991
992     ff_h264_flush_change(h);
993
994     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
995         ff_h264_unref_picture(h, &h->DPB[i]);
996     h->cur_pic_ptr = NULL;
997     ff_h264_unref_picture(h, &h->cur_pic);
998
999     h->mb_y = 0;
1000
1001     ff_h264_free_tables(h);
1002     h->context_initialized = 0;
1003 }
1004
1005 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1006 {
1007     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1008     int field_poc[2];
1009
1010     h->frame_num_offset = h->prev_frame_num_offset;
1011     if (h->frame_num < h->prev_frame_num)
1012         h->frame_num_offset += max_frame_num;
1013
1014     if (h->sps.poc_type == 0) {
1015         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1016
1017         if (h->poc_lsb < h->prev_poc_lsb &&
1018             h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1019             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1020         else if (h->poc_lsb > h->prev_poc_lsb &&
1021                  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1022             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1023         else
1024             h->poc_msb = h->prev_poc_msb;
1025         field_poc[0] =
1026         field_poc[1] = h->poc_msb + h->poc_lsb;
1027         if (h->picture_structure == PICT_FRAME)
1028             field_poc[1] += h->delta_poc_bottom;
1029     } else if (h->sps.poc_type == 1) {
1030         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1031         int i;
1032
1033         if (h->sps.poc_cycle_length != 0)
1034             abs_frame_num = h->frame_num_offset + h->frame_num;
1035         else
1036             abs_frame_num = 0;
1037
1038         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1039             abs_frame_num--;
1040
1041         expected_delta_per_poc_cycle = 0;
1042         for (i = 0; i < h->sps.poc_cycle_length; i++)
1043             // FIXME integrate during sps parse
1044             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1045
1046         if (abs_frame_num > 0) {
1047             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1048             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1049
1050             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1051             for (i = 0; i <= frame_num_in_poc_cycle; i++)
1052                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1053         } else
1054             expectedpoc = 0;
1055
1056         if (h->nal_ref_idc == 0)
1057             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1058
1059         field_poc[0] = expectedpoc + h->delta_poc[0];
1060         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1061
1062         if (h->picture_structure == PICT_FRAME)
1063             field_poc[1] += h->delta_poc[1];
1064     } else {
1065         int poc = 2 * (h->frame_num_offset + h->frame_num);
1066
1067         if (!h->nal_ref_idc)
1068             poc--;
1069
1070         field_poc[0] = poc;
1071         field_poc[1] = poc;
1072     }
1073
1074     if (h->picture_structure != PICT_BOTTOM_FIELD)
1075         pic_field_poc[0] = field_poc[0];
1076     if (h->picture_structure != PICT_TOP_FIELD)
1077         pic_field_poc[1] = field_poc[1];
1078     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1079
1080     return 0;
1081 }
1082
1083 /**
1084  * Compute profile from profile_idc and constraint_set?_flags.
1085  *
1086  * @param sps SPS
1087  *
1088  * @return profile as defined by FF_PROFILE_H264_*
1089  */
1090 int ff_h264_get_profile(SPS *sps)
1091 {
1092     int profile = sps->profile_idc;
1093
1094     switch (sps->profile_idc) {
1095     case FF_PROFILE_H264_BASELINE:
1096         // constraint_set1_flag set to 1
1097         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1098         break;
1099     case FF_PROFILE_H264_HIGH_10:
1100     case FF_PROFILE_H264_HIGH_422:
1101     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1102         // constraint_set3_flag set to 1
1103         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1104         break;
1105     }
1106
1107     return profile;
1108 }
1109
1110 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1111 {
1112     int ref_count[2], list_count;
1113     int num_ref_idx_active_override_flag;
1114
1115     // set defaults, might be overridden a few lines later
1116     ref_count[0] = h->pps.ref_count[0];
1117     ref_count[1] = h->pps.ref_count[1];
1118
1119     if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1120         unsigned max[2];
1121         max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1122
1123         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1124             sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1125         num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1126
1127         if (num_ref_idx_active_override_flag) {
1128             ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1129             if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1130                 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1131             } else
1132                 // full range is spec-ok in this case, even for frames
1133                 ref_count[1] = 1;
1134         }
1135
1136         if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1137             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]);
1138             sl->ref_count[0] = sl->ref_count[1] = 0;
1139             sl->list_count   = 0;
1140             return AVERROR_INVALIDDATA;
1141         }
1142
1143         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1144             list_count = 2;
1145         else
1146             list_count = 1;
1147     } else {
1148         list_count   = 0;
1149         ref_count[0] = ref_count[1] = 0;
1150     }
1151
1152     if (list_count   != sl->list_count   ||
1153         ref_count[0] != sl->ref_count[0] ||
1154         ref_count[1] != sl->ref_count[1]) {
1155         sl->ref_count[0] = ref_count[0];
1156         sl->ref_count[1] = ref_count[1];
1157         sl->list_count   = list_count;
1158         return 1;
1159     }
1160
1161     return 0;
1162 }
1163
1164 #if FF_API_CAP_VDPAU
1165 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1166 #endif
1167
1168 static int get_last_needed_nal(H264Context *h)
1169 {
1170     int nals_needed = 0;
1171     int first_slice = 0;
1172     int i;
1173
1174     for (i = 0; i < h->pkt.nb_nals; i++) {
1175         H2645NAL *nal = &h->pkt.nals[i];
1176         GetBitContext gb;
1177
1178         /* packets can sometimes contain multiple PPS/SPS,
1179          * e.g. two PAFF field pictures in one packet, or a demuxer
1180          * which splits NALs strangely if so, when frame threading we
1181          * can't start the next thread until we've read all of them */
1182         switch (nal->type) {
1183         case NAL_SPS:
1184         case NAL_PPS:
1185             nals_needed = i;
1186             break;
1187         case NAL_DPA:
1188         case NAL_IDR_SLICE:
1189         case NAL_SLICE:
1190             init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
1191             if (!get_ue_golomb_long(&gb) ||  // first_mb_in_slice
1192                 !first_slice ||
1193                 first_slice != nal->type)
1194                 nals_needed = i;
1195             if (!first_slice)
1196                 first_slice = nal->type;
1197         }
1198     }
1199
1200     return nals_needed;
1201 }
1202
1203 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1204                             int parse_extradata)
1205 {
1206     AVCodecContext *const avctx = h->avctx;
1207     unsigned context_count = 0;
1208     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1209     int idr_cleared=0;
1210     int i, ret = 0;
1211
1212     h->nal_unit_type= 0;
1213
1214     if(!h->slice_context_count)
1215          h->slice_context_count= 1;
1216     h->max_contexts = h->slice_context_count;
1217     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1218         h->current_slice = 0;
1219         if (!h->first_field)
1220             h->cur_pic_ptr = NULL;
1221         ff_h264_reset_sei(h);
1222     }
1223
1224     if (h->nal_length_size == 4) {
1225         if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1226             h->is_avc = 0;
1227         }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1228             h->is_avc = 1;
1229     }
1230
1231     ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
1232                                 h->nal_length_size, avctx->codec_id);
1233     if (ret < 0) {
1234         av_log(avctx, AV_LOG_ERROR,
1235                "Error splitting the input into NAL units.\n");
1236         /* don't consider NAL parsing failure a fatal error when parsing extradata, as the stream may work without it */
1237         return parse_extradata ? buf_size : ret;
1238     }
1239
1240     if (avctx->active_thread_type & FF_THREAD_FRAME)
1241         nals_needed = get_last_needed_nal(h);
1242
1243     for (i = 0; i < h->pkt.nb_nals; i++) {
1244         H2645NAL *nal = &h->pkt.nals[i];
1245         H264SliceContext *sl = &h->slice_ctx[context_count];
1246         int err;
1247
1248         if (avctx->skip_frame >= AVDISCARD_NONREF &&
1249             nal->ref_idc == 0 && nal->type != NAL_SEI)
1250             continue;
1251
1252 again:
1253         /* Ignore per frame NAL unit type during extradata
1254          * parsing. Decoding slices is not possible in codec init
1255          * with frame-mt */
1256         if (parse_extradata) {
1257             switch (nal->type) {
1258             case NAL_IDR_SLICE:
1259             case NAL_SLICE:
1260             case NAL_DPA:
1261             case NAL_DPB:
1262             case NAL_DPC:
1263                 av_log(h->avctx, AV_LOG_WARNING,
1264                        "Ignoring NAL %d in global header/extradata\n",
1265                        nal->type);
1266                 // fall through to next case
1267             case NAL_AUXILIARY_SLICE:
1268                 nal->type = NAL_FF_IGNORE;
1269             }
1270         }
1271
1272         // FIXME these should stop being context-global variables
1273         h->nal_ref_idc   = nal->ref_idc;
1274         h->nal_unit_type = nal->type;
1275
1276         err = 0;
1277         switch (nal->type) {
1278         case NAL_IDR_SLICE:
1279             if ((nal->data[1] & 0xFC) == 0x98) {
1280                 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1281                 h->next_outputed_poc = INT_MIN;
1282                 ret = -1;
1283                 goto end;
1284             }
1285             if (nal->type != NAL_IDR_SLICE) {
1286                 av_log(h->avctx, AV_LOG_ERROR,
1287                        "Invalid mix of idr and non-idr slices\n");
1288                 ret = -1;
1289                 goto end;
1290             }
1291             if(!idr_cleared) {
1292                 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1293                     av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1294                     ret = AVERROR_INVALIDDATA;
1295                     goto end;
1296                 }
1297                 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1298             }
1299             idr_cleared = 1;
1300             h->has_recovery_point = 1;
1301         case NAL_SLICE:
1302             sl->gb = nal->gb;
1303             if (   nals_needed >= i
1304                 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1305                 h->au_pps_id = -1;
1306
1307             if ((err = ff_h264_decode_slice_header(h, sl)))
1308                 break;
1309
1310             if (h->sei_recovery_frame_cnt >= 0) {
1311                 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1312                     h->valid_recovery_point = 1;
1313
1314                 if (   h->recovery_frame < 0
1315                     || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1316                     h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1317
1318                     if (!h->valid_recovery_point)
1319                         h->recovery_frame = h->frame_num;
1320                 }
1321             }
1322
1323             h->cur_pic_ptr->f->key_frame |= (nal->type == NAL_IDR_SLICE);
1324
1325             if (nal->type == NAL_IDR_SLICE ||
1326                 (h->recovery_frame == h->frame_num && nal->ref_idc)) {
1327                 h->recovery_frame         = -1;
1328                 h->cur_pic_ptr->recovered = 1;
1329             }
1330             // If we have an IDR, all frames after it in decoded order are
1331             // "recovered".
1332             if (nal->type == NAL_IDR_SLICE)
1333                 h->frame_recovered |= FRAME_RECOVERED_IDR;
1334 #if 1
1335             h->cur_pic_ptr->recovered |= h->frame_recovered;
1336 #else
1337             h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1338 #endif
1339
1340             if (h->current_slice == 1) {
1341                 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1342                     decode_postinit(h, i >= nals_needed);
1343
1344                 if (h->avctx->hwaccel &&
1345                     (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1346                     goto end;
1347 #if FF_API_CAP_VDPAU
1348                 if (CONFIG_H264_VDPAU_DECODER &&
1349                     h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
1350                     ff_vdpau_h264_picture_start(h);
1351 #endif
1352             }
1353
1354             if (sl->redundant_pic_count == 0) {
1355                 if (avctx->hwaccel) {
1356                     ret = avctx->hwaccel->decode_slice(avctx,
1357                                                        nal->raw_data,
1358                                                        nal->raw_size);
1359                     if (ret < 0)
1360                         goto end;
1361 #if FF_API_CAP_VDPAU
1362                 } else if (CONFIG_H264_VDPAU_DECODER &&
1363                            h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
1364                     ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1365                                             start_code,
1366                                             sizeof(start_code));
1367                     ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1368                                             nal->raw_data,
1369                                             nal->raw_size);
1370 #endif
1371                 } else
1372                     context_count++;
1373             }
1374             break;
1375         case NAL_DPA:
1376         case NAL_DPB:
1377         case NAL_DPC:
1378             avpriv_request_sample(avctx, "data partitioning");
1379             break;
1380         case NAL_SEI:
1381             h->gb = nal->gb;
1382             ret = ff_h264_decode_sei(h);
1383             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1384                 goto end;
1385             break;
1386         case NAL_SPS:
1387             h->gb = nal->gb;
1388             if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1389                 break;
1390             av_log(h->avctx, AV_LOG_DEBUG,
1391                    "SPS decoding failure, trying again with the complete NAL\n");
1392             init_get_bits8(&h->gb, nal->raw_data + 1, nal->raw_size - 1);
1393             if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1394                 break;
1395             h->gb = nal->gb;
1396             ff_h264_decode_seq_parameter_set(h, 1);
1397
1398             break;
1399         case NAL_PPS:
1400             h->gb = nal->gb;
1401             ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
1402             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1403                 goto end;
1404             break;
1405         case NAL_AUD:
1406         case NAL_END_SEQUENCE:
1407         case NAL_END_STREAM:
1408         case NAL_FILLER_DATA:
1409         case NAL_SPS_EXT:
1410         case NAL_AUXILIARY_SLICE:
1411             break;
1412         case NAL_FF_IGNORE:
1413             break;
1414         default:
1415             av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1416                    nal->type, nal->size_bits);
1417         }
1418
1419         if (context_count == h->max_contexts) {
1420             ret = ff_h264_execute_decode_slices(h, context_count);
1421             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1422                 goto end;
1423             context_count = 0;
1424         }
1425
1426         if (err < 0 || err == SLICE_SKIPED) {
1427             if (err < 0)
1428                 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1429             sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1430         } else if (err == SLICE_SINGLETHREAD) {
1431             if (context_count > 1) {
1432                 ret = ff_h264_execute_decode_slices(h, context_count - 1);
1433                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1434                     goto end;
1435                 context_count = 0;
1436             }
1437             /* Slice could not be decoded in parallel mode, restart. Note
1438              * that rbsp_buffer is not transferred, but since we no longer
1439              * run in parallel mode this should not be an issue. */
1440             sl               = &h->slice_ctx[0];
1441             goto again;
1442         }
1443     }
1444     if (context_count) {
1445         ret = ff_h264_execute_decode_slices(h, context_count);
1446         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1447             goto end;
1448     }
1449
1450     ret = 0;
1451 end:
1452
1453 #if CONFIG_ERROR_RESILIENCE
1454     /*
1455      * FIXME: Error handling code does not seem to support interlaced
1456      * when slices span multiple rows
1457      * The ff_er_add_slice calls don't work right for bottom
1458      * fields; they cause massive erroneous error concealing
1459      * Error marking covers both fields (top and bottom).
1460      * This causes a mismatched s->error_count
1461      * and a bad error table. Further, the error count goes to
1462      * INT_MAX when called for bottom field, because mb_y is
1463      * past end by one (callers fault) and resync_mb_y != 0
1464      * causes problems for the first MB line, too.
1465      */
1466     if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) {
1467         H264SliceContext *sl = h->slice_ctx;
1468         int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
1469
1470         ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
1471
1472         if (use_last_pic) {
1473             ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
1474             sl->ref_list[0][0].parent = &h->last_pic_for_ec;
1475             memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
1476             memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
1477             sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
1478         } else if (sl->ref_count[0]) {
1479             ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
1480         } else
1481             ff_h264_set_erpic(&sl->er.last_pic, NULL);
1482
1483         if (sl->ref_count[1])
1484             ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
1485
1486         sl->er.ref_count = sl->ref_count[0];
1487
1488         ff_er_frame_end(&sl->er);
1489         if (use_last_pic)
1490             memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
1491     }
1492 #endif /* CONFIG_ERROR_RESILIENCE */
1493     /* clean up */
1494     if (h->cur_pic_ptr && !h->droppable) {
1495         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1496                                   h->picture_structure == PICT_BOTTOM_FIELD);
1497     }
1498
1499     return (ret < 0) ? ret : buf_size;
1500 }
1501
1502 /**
1503  * Return the number of bytes consumed for building the current frame.
1504  */
1505 static int get_consumed_bytes(int pos, int buf_size)
1506 {
1507     if (pos == 0)
1508         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
1509     if (pos + 10 > buf_size)
1510         pos = buf_size; // oops ;)
1511
1512     return pos;
1513 }
1514
1515 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1516 {
1517     AVFrame *src = srcp->f;
1518     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1519     int i;
1520     int ret = av_frame_ref(dst, src);
1521     if (ret < 0)
1522         return ret;
1523
1524     av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1525
1526     h->backup_width   = h->avctx->width;
1527     h->backup_height  = h->avctx->height;
1528     h->backup_pix_fmt = h->avctx->pix_fmt;
1529
1530     h->avctx->width   = dst->width;
1531     h->avctx->height  = dst->height;
1532     h->avctx->pix_fmt = dst->format;
1533
1534     if (srcp->sei_recovery_frame_cnt == 0)
1535         dst->key_frame = 1;
1536     if (!srcp->crop)
1537         return 0;
1538
1539     for (i = 0; i < desc->nb_components; i++) {
1540         int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1541         int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1542         int off    = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1543                       (srcp->crop_top  >> vshift) * dst->linesize[i];
1544         dst->data[i] += off;
1545     }
1546     return 0;
1547 }
1548
1549 static int is_extra(const uint8_t *buf, int buf_size)
1550 {
1551     int cnt= buf[5]&0x1f;
1552     const uint8_t *p= buf+6;
1553     while(cnt--){
1554         int nalsize= AV_RB16(p) + 2;
1555         if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
1556             return 0;
1557         p += nalsize;
1558     }
1559     cnt = *(p++);
1560     if(!cnt)
1561         return 0;
1562     while(cnt--){
1563         int nalsize= AV_RB16(p) + 2;
1564         if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
1565             return 0;
1566         p += nalsize;
1567     }
1568     return 1;
1569 }
1570
1571 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1572                              int *got_frame, AVPacket *avpkt)
1573 {
1574     const uint8_t *buf = avpkt->data;
1575     int buf_size       = avpkt->size;
1576     H264Context *h     = avctx->priv_data;
1577     AVFrame *pict      = data;
1578     int buf_index      = 0;
1579     H264Picture *out;
1580     int i, out_idx;
1581     int ret;
1582
1583     h->flags = avctx->flags;
1584     h->setup_finished = 0;
1585
1586     if (h->backup_width != -1) {
1587         avctx->width    = h->backup_width;
1588         h->backup_width = -1;
1589     }
1590     if (h->backup_height != -1) {
1591         avctx->height    = h->backup_height;
1592         h->backup_height = -1;
1593     }
1594     if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1595         avctx->pix_fmt    = h->backup_pix_fmt;
1596         h->backup_pix_fmt = AV_PIX_FMT_NONE;
1597     }
1598
1599     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1600
1601     /* end of stream, output what is still in the buffers */
1602     if (buf_size == 0) {
1603  out:
1604
1605         h->cur_pic_ptr = NULL;
1606         h->first_field = 0;
1607
1608         // FIXME factorize this with the output code below
1609         out     = h->delayed_pic[0];
1610         out_idx = 0;
1611         for (i = 1;
1612              h->delayed_pic[i] &&
1613              !h->delayed_pic[i]->f->key_frame &&
1614              !h->delayed_pic[i]->mmco_reset;
1615              i++)
1616             if (h->delayed_pic[i]->poc < out->poc) {
1617                 out     = h->delayed_pic[i];
1618                 out_idx = i;
1619             }
1620
1621         for (i = out_idx; h->delayed_pic[i]; i++)
1622             h->delayed_pic[i] = h->delayed_pic[i + 1];
1623
1624         if (out) {
1625             out->reference &= ~DELAYED_PIC_REF;
1626             ret = output_frame(h, pict, out);
1627             if (ret < 0)
1628                 return ret;
1629             *got_frame = 1;
1630         }
1631
1632         return buf_index;
1633     }
1634     if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1635         int side_size;
1636         uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1637         if (is_extra(side, side_size))
1638             ff_h264_decode_extradata(h, side, side_size);
1639     }
1640     if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1641         if (is_extra(buf, buf_size))
1642             return ff_h264_decode_extradata(h, buf, buf_size);
1643     }
1644
1645     buf_index = decode_nal_units(h, buf, buf_size, 0);
1646     if (buf_index < 0)
1647         return AVERROR_INVALIDDATA;
1648
1649     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1650         av_assert0(buf_index <= buf_size);
1651         goto out;
1652     }
1653
1654     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1655         if (avctx->skip_frame >= AVDISCARD_NONREF ||
1656             buf_size >= 4 && !memcmp("Q264", buf, 4))
1657             return buf_size;
1658         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1659         return AVERROR_INVALIDDATA;
1660     }
1661
1662     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1663         (h->mb_y >= h->mb_height && h->mb_height)) {
1664         if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1665             decode_postinit(h, 1);
1666
1667         if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1668             return ret;
1669
1670         /* Wait for second field. */
1671         *got_frame = 0;
1672         if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1673                                    (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
1674                                    h->next_output_pic->recovered)) {
1675             if (!h->next_output_pic->recovered)
1676                 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1677
1678             if (!h->avctx->hwaccel &&
1679                  (h->next_output_pic->field_poc[0] == INT_MAX ||
1680                   h->next_output_pic->field_poc[1] == INT_MAX)
1681             ) {
1682                 int p;
1683                 AVFrame *f = h->next_output_pic->f;
1684                 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1685                 uint8_t *dst_data[4];
1686                 int linesizes[4];
1687                 const uint8_t *src_data[4];
1688
1689                 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1690
1691                 for (p = 0; p<4; p++) {
1692                     dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1693                     src_data[p] = f->data[p] +  field   *f->linesize[p];
1694                     linesizes[p] = 2*f->linesize[p];
1695                 }
1696
1697                 av_image_copy(dst_data, linesizes, src_data, linesizes,
1698                               f->format, f->width, f->height>>1);
1699             }
1700
1701             ret = output_frame(h, pict, h->next_output_pic);
1702             if (ret < 0)
1703                 return ret;
1704             *got_frame = 1;
1705             if (CONFIG_MPEGVIDEO) {
1706                 ff_print_debug_info2(h->avctx, pict, NULL,
1707                                     h->next_output_pic->mb_type,
1708                                     h->next_output_pic->qscale_table,
1709                                     h->next_output_pic->motion_val,
1710                                     &h->low_delay,
1711                                     h->mb_width, h->mb_height, h->mb_stride, 1);
1712             }
1713         }
1714     }
1715
1716     av_assert0(pict->buf[0] || !*got_frame);
1717
1718     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1719
1720     return get_consumed_bytes(buf_index, buf_size);
1721 }
1722
1723 av_cold void ff_h264_free_context(H264Context *h)
1724 {
1725     int i;
1726
1727     ff_h264_free_tables(h);
1728
1729     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1730         ff_h264_unref_picture(h, &h->DPB[i]);
1731         av_frame_free(&h->DPB[i].f);
1732     }
1733     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1734
1735     h->cur_pic_ptr = NULL;
1736
1737     for (i = 0; i < h->nb_slice_ctx; i++)
1738         av_freep(&h->slice_ctx[i].rbsp_buffer);
1739     av_freep(&h->slice_ctx);
1740     h->nb_slice_ctx = 0;
1741
1742     h->a53_caption_size = 0;
1743     av_freep(&h->a53_caption);
1744
1745     for (i = 0; i < MAX_SPS_COUNT; i++)
1746         av_freep(h->sps_buffers + i);
1747
1748     for (i = 0; i < MAX_PPS_COUNT; i++)
1749         av_freep(h->pps_buffers + i);
1750
1751     ff_h2645_packet_uninit(&h->pkt);
1752 }
1753
1754 static av_cold int h264_decode_end(AVCodecContext *avctx)
1755 {
1756     H264Context *h = avctx->priv_data;
1757
1758     ff_h264_remove_all_refs(h);
1759     ff_h264_free_context(h);
1760
1761     ff_h264_unref_picture(h, &h->cur_pic);
1762     av_frame_free(&h->cur_pic.f);
1763     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1764     av_frame_free(&h->last_pic_for_ec.f);
1765
1766     return 0;
1767 }
1768
1769 #define OFFSET(x) offsetof(H264Context, x)
1770 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1771 static const AVOption h264_options[] = {
1772     {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
1773     {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1774     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
1775     { NULL },
1776 };
1777
1778 static const AVClass h264_class = {
1779     .class_name = "H264 Decoder",
1780     .item_name  = av_default_item_name,
1781     .option     = h264_options,
1782     .version    = LIBAVUTIL_VERSION_INT,
1783 };
1784
1785 AVCodec ff_h264_decoder = {
1786     .name                  = "h264",
1787     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1788     .type                  = AVMEDIA_TYPE_VIDEO,
1789     .id                    = AV_CODEC_ID_H264,
1790     .priv_data_size        = sizeof(H264Context),
1791     .init                  = ff_h264_decode_init,
1792     .close                 = h264_decode_end,
1793     .decode                = h264_decode_frame,
1794     .capabilities          = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1795                              AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1796                              AV_CODEC_CAP_FRAME_THREADS,
1797     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE,
1798     .flush                 = flush_dpb,
1799     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1800     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1801     .profiles              = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1802     .priv_class            = &h264_class,
1803 };
1804
1805 #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
1806 static const AVClass h264_vdpau_class = {
1807     .class_name = "H264 VDPAU Decoder",
1808     .item_name  = av_default_item_name,
1809     .option     = h264_options,
1810     .version    = LIBAVUTIL_VERSION_INT,
1811 };
1812
1813 AVCodec ff_h264_vdpau_decoder = {
1814     .name           = "h264_vdpau",
1815     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1816     .type           = AVMEDIA_TYPE_VIDEO,
1817     .id             = AV_CODEC_ID_H264,
1818     .priv_data_size = sizeof(H264Context),
1819     .init           = ff_h264_decode_init,
1820     .close          = h264_decode_end,
1821     .decode         = h264_decode_frame,
1822     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
1823     .flush          = flush_dpb,
1824     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
1825                                                      AV_PIX_FMT_NONE},
1826     .profiles       = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1827     .priv_class     = &h264_vdpau_class,
1828 };
1829 #endif