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