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