]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
avcodec/sheervideo: fix prediction for ybyr format
[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
1001 #if FF_API_CAP_VDPAU
1002 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1003 #endif
1004
1005 static int get_last_needed_nal(H264Context *h)
1006 {
1007     int nals_needed = 0;
1008     int first_slice = 0;
1009     int i;
1010     int ret;
1011
1012     for (i = 0; i < h->pkt.nb_nals; i++) {
1013         H2645NAL *nal = &h->pkt.nals[i];
1014         GetBitContext gb;
1015
1016         /* packets can sometimes contain multiple PPS/SPS,
1017          * e.g. two PAFF field pictures in one packet, or a demuxer
1018          * which splits NALs strangely if so, when frame threading we
1019          * can't start the next thread until we've read all of them */
1020         switch (nal->type) {
1021         case NAL_SPS:
1022         case NAL_PPS:
1023             nals_needed = i;
1024             break;
1025         case NAL_DPA:
1026         case NAL_IDR_SLICE:
1027         case NAL_SLICE:
1028             ret = init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
1029             if (ret < 0)
1030                 return ret;
1031             if (!get_ue_golomb_long(&gb) ||  // first_mb_in_slice
1032                 !first_slice ||
1033                 first_slice != nal->type)
1034                 nals_needed = i;
1035             if (!first_slice)
1036                 first_slice = nal->type;
1037         }
1038     }
1039
1040     return nals_needed;
1041 }
1042
1043 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1044                             int parse_extradata)
1045 {
1046     AVCodecContext *const avctx = h->avctx;
1047     unsigned context_count = 0;
1048     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1049     int idr_cleared=0;
1050     int i, ret = 0;
1051
1052     h->nal_unit_type= 0;
1053
1054     if(!h->slice_context_count)
1055          h->slice_context_count= 1;
1056     h->max_contexts = h->slice_context_count;
1057     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1058         h->current_slice = 0;
1059         if (!h->first_field)
1060             h->cur_pic_ptr = NULL;
1061         ff_h264_reset_sei(h);
1062     }
1063
1064     if (h->nal_length_size == 4) {
1065         if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1066             h->is_avc = 0;
1067         }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1068             h->is_avc = 1;
1069     }
1070
1071     ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
1072                                 h->nal_length_size, avctx->codec_id);
1073     if (ret < 0) {
1074         av_log(avctx, AV_LOG_ERROR,
1075                "Error splitting the input into NAL units.\n");
1076         /* don't consider NAL parsing failure a fatal error when parsing extradata, as the stream may work without it */
1077         return parse_extradata ? buf_size : ret;
1078     }
1079
1080     if (avctx->active_thread_type & FF_THREAD_FRAME)
1081         nals_needed = get_last_needed_nal(h);
1082     if (nals_needed < 0)
1083         return nals_needed;
1084
1085     for (i = 0; i < h->pkt.nb_nals; i++) {
1086         H2645NAL *nal = &h->pkt.nals[i];
1087         H264SliceContext *sl = &h->slice_ctx[context_count];
1088         int err;
1089
1090         if (avctx->skip_frame >= AVDISCARD_NONREF &&
1091             nal->ref_idc == 0 && nal->type != NAL_SEI)
1092             continue;
1093
1094 again:
1095         /* Ignore per frame NAL unit type during extradata
1096          * parsing. Decoding slices is not possible in codec init
1097          * with frame-mt */
1098         if (parse_extradata) {
1099             switch (nal->type) {
1100             case NAL_IDR_SLICE:
1101             case NAL_SLICE:
1102             case NAL_DPA:
1103             case NAL_DPB:
1104             case NAL_DPC:
1105                 av_log(h->avctx, AV_LOG_WARNING,
1106                        "Ignoring NAL %d in global header/extradata\n",
1107                        nal->type);
1108                 // fall through to next case
1109             case NAL_AUXILIARY_SLICE:
1110                 nal->type = NAL_FF_IGNORE;
1111             }
1112         }
1113
1114         // FIXME these should stop being context-global variables
1115         h->nal_ref_idc   = nal->ref_idc;
1116         h->nal_unit_type = nal->type;
1117
1118         err = 0;
1119         switch (nal->type) {
1120         case NAL_IDR_SLICE:
1121             if ((nal->data[1] & 0xFC) == 0x98) {
1122                 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1123                 h->next_outputed_poc = INT_MIN;
1124                 ret = -1;
1125                 goto end;
1126             }
1127             if (nal->type != NAL_IDR_SLICE) {
1128                 av_log(h->avctx, AV_LOG_ERROR,
1129                        "Invalid mix of idr and non-idr slices\n");
1130                 ret = -1;
1131                 goto end;
1132             }
1133             if(!idr_cleared) {
1134                 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1135                     av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1136                     ret = AVERROR_INVALIDDATA;
1137                     goto end;
1138                 }
1139                 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1140             }
1141             idr_cleared = 1;
1142             h->has_recovery_point = 1;
1143         case NAL_SLICE:
1144             sl->gb = nal->gb;
1145             if (   nals_needed >= i
1146                 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1147                 h->au_pps_id = -1;
1148
1149             if ((err = ff_h264_decode_slice_header(h, sl)))
1150                 break;
1151
1152             if (h->sei_recovery_frame_cnt >= 0) {
1153                 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1154                     h->valid_recovery_point = 1;
1155
1156                 if (   h->recovery_frame < 0
1157                     || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1158                     h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1159
1160                     if (!h->valid_recovery_point)
1161                         h->recovery_frame = h->frame_num;
1162                 }
1163             }
1164
1165             h->cur_pic_ptr->f->key_frame |= (nal->type == NAL_IDR_SLICE);
1166
1167             if (nal->type == NAL_IDR_SLICE ||
1168                 (h->recovery_frame == h->frame_num && nal->ref_idc)) {
1169                 h->recovery_frame         = -1;
1170                 h->cur_pic_ptr->recovered = 1;
1171             }
1172             // If we have an IDR, all frames after it in decoded order are
1173             // "recovered".
1174             if (nal->type == NAL_IDR_SLICE)
1175                 h->frame_recovered |= FRAME_RECOVERED_IDR;
1176 #if 1
1177             h->cur_pic_ptr->recovered |= h->frame_recovered;
1178 #else
1179             h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1180 #endif
1181
1182             if (h->current_slice == 1) {
1183                 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1184                     decode_postinit(h, i >= nals_needed);
1185
1186                 if (h->avctx->hwaccel &&
1187                     (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1188                     goto end;
1189 #if FF_API_CAP_VDPAU
1190                 if (CONFIG_H264_VDPAU_DECODER &&
1191                     h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
1192                     ff_vdpau_h264_picture_start(h);
1193 #endif
1194             }
1195
1196             if (sl->redundant_pic_count == 0) {
1197                 if (avctx->hwaccel) {
1198                     ret = avctx->hwaccel->decode_slice(avctx,
1199                                                        nal->raw_data,
1200                                                        nal->raw_size);
1201                     if (ret < 0)
1202                         goto end;
1203 #if FF_API_CAP_VDPAU
1204                 } else if (CONFIG_H264_VDPAU_DECODER &&
1205                            h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
1206                     ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1207                                             start_code,
1208                                             sizeof(start_code));
1209                     ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1210                                             nal->raw_data,
1211                                             nal->raw_size);
1212 #endif
1213                 } else
1214                     context_count++;
1215             }
1216             break;
1217         case NAL_DPA:
1218         case NAL_DPB:
1219         case NAL_DPC:
1220             avpriv_request_sample(avctx, "data partitioning");
1221             break;
1222         case NAL_SEI:
1223             h->gb = nal->gb;
1224             ret = ff_h264_decode_sei(h);
1225             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1226                 goto end;
1227             break;
1228         case NAL_SPS:
1229             h->gb = nal->gb;
1230             if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1231                 break;
1232             av_log(h->avctx, AV_LOG_DEBUG,
1233                    "SPS decoding failure, trying again with the complete NAL\n");
1234             init_get_bits8(&h->gb, nal->raw_data + 1, nal->raw_size - 1);
1235             if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1236                 break;
1237             h->gb = nal->gb;
1238             ff_h264_decode_seq_parameter_set(h, 1);
1239
1240             break;
1241         case NAL_PPS:
1242             h->gb = nal->gb;
1243             ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
1244             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1245                 goto end;
1246             break;
1247         case NAL_AUD:
1248         case NAL_END_SEQUENCE:
1249         case NAL_END_STREAM:
1250         case NAL_FILLER_DATA:
1251         case NAL_SPS_EXT:
1252         case NAL_AUXILIARY_SLICE:
1253             break;
1254         case NAL_FF_IGNORE:
1255             break;
1256         default:
1257             av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1258                    nal->type, nal->size_bits);
1259         }
1260
1261         if (context_count == h->max_contexts) {
1262             ret = ff_h264_execute_decode_slices(h, context_count);
1263             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1264                 goto end;
1265             context_count = 0;
1266         }
1267
1268         if (err < 0 || err == SLICE_SKIPED) {
1269             if (err < 0)
1270                 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1271             sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1272         } else if (err == SLICE_SINGLETHREAD) {
1273             if (context_count > 0) {
1274                 ret = ff_h264_execute_decode_slices(h, context_count);
1275                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1276                     goto end;
1277                 context_count = 0;
1278             }
1279             /* Slice could not be decoded in parallel mode, restart. Note
1280              * that rbsp_buffer is not transferred, but since we no longer
1281              * run in parallel mode this should not be an issue. */
1282             sl               = &h->slice_ctx[0];
1283             goto again;
1284         }
1285     }
1286     if (context_count) {
1287         ret = ff_h264_execute_decode_slices(h, context_count);
1288         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1289             goto end;
1290     }
1291
1292     ret = 0;
1293 end:
1294
1295 #if CONFIG_ERROR_RESILIENCE
1296     /*
1297      * FIXME: Error handling code does not seem to support interlaced
1298      * when slices span multiple rows
1299      * The ff_er_add_slice calls don't work right for bottom
1300      * fields; they cause massive erroneous error concealing
1301      * Error marking covers both fields (top and bottom).
1302      * This causes a mismatched s->error_count
1303      * and a bad error table. Further, the error count goes to
1304      * INT_MAX when called for bottom field, because mb_y is
1305      * past end by one (callers fault) and resync_mb_y != 0
1306      * causes problems for the first MB line, too.
1307      */
1308     if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) {
1309         H264SliceContext *sl = h->slice_ctx;
1310         int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
1311
1312         ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
1313
1314         if (use_last_pic) {
1315             ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
1316             sl->ref_list[0][0].parent = &h->last_pic_for_ec;
1317             memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
1318             memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
1319             sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
1320         } else if (sl->ref_count[0]) {
1321             ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
1322         } else
1323             ff_h264_set_erpic(&sl->er.last_pic, NULL);
1324
1325         if (sl->ref_count[1])
1326             ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
1327
1328         sl->er.ref_count = sl->ref_count[0];
1329
1330         ff_er_frame_end(&sl->er);
1331         if (use_last_pic)
1332             memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
1333     }
1334 #endif /* CONFIG_ERROR_RESILIENCE */
1335     /* clean up */
1336     if (h->cur_pic_ptr && !h->droppable) {
1337         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1338                                   h->picture_structure == PICT_BOTTOM_FIELD);
1339     }
1340
1341     return (ret < 0) ? ret : buf_size;
1342 }
1343
1344 /**
1345  * Return the number of bytes consumed for building the current frame.
1346  */
1347 static int get_consumed_bytes(int pos, int buf_size)
1348 {
1349     if (pos == 0)
1350         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
1351     if (pos + 10 > buf_size)
1352         pos = buf_size; // oops ;)
1353
1354     return pos;
1355 }
1356
1357 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1358 {
1359     AVFrame *src = srcp->f;
1360     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1361     int i;
1362     int ret = av_frame_ref(dst, src);
1363     if (ret < 0)
1364         return ret;
1365
1366     av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1367
1368     h->backup_width   = h->avctx->width;
1369     h->backup_height  = h->avctx->height;
1370     h->backup_pix_fmt = h->avctx->pix_fmt;
1371
1372     h->avctx->width   = dst->width;
1373     h->avctx->height  = dst->height;
1374     h->avctx->pix_fmt = dst->format;
1375
1376     if (srcp->sei_recovery_frame_cnt == 0)
1377         dst->key_frame = 1;
1378     if (!srcp->crop)
1379         return 0;
1380
1381     for (i = 0; i < desc->nb_components; i++) {
1382         int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1383         int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1384         int off    = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1385                       (srcp->crop_top  >> vshift) * dst->linesize[i];
1386         dst->data[i] += off;
1387     }
1388     return 0;
1389 }
1390
1391 static int is_extra(const uint8_t *buf, int buf_size)
1392 {
1393     int cnt= buf[5]&0x1f;
1394     const uint8_t *p= buf+6;
1395     while(cnt--){
1396         int nalsize= AV_RB16(p) + 2;
1397         if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
1398             return 0;
1399         p += nalsize;
1400     }
1401     cnt = *(p++);
1402     if(!cnt)
1403         return 0;
1404     while(cnt--){
1405         int nalsize= AV_RB16(p) + 2;
1406         if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
1407             return 0;
1408         p += nalsize;
1409     }
1410     return 1;
1411 }
1412
1413 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1414                              int *got_frame, AVPacket *avpkt)
1415 {
1416     const uint8_t *buf = avpkt->data;
1417     int buf_size       = avpkt->size;
1418     H264Context *h     = avctx->priv_data;
1419     AVFrame *pict      = data;
1420     int buf_index      = 0;
1421     H264Picture *out;
1422     int i, out_idx;
1423     int ret;
1424
1425     h->flags = avctx->flags;
1426     h->setup_finished = 0;
1427
1428     if (h->backup_width != -1) {
1429         avctx->width    = h->backup_width;
1430         h->backup_width = -1;
1431     }
1432     if (h->backup_height != -1) {
1433         avctx->height    = h->backup_height;
1434         h->backup_height = -1;
1435     }
1436     if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1437         avctx->pix_fmt    = h->backup_pix_fmt;
1438         h->backup_pix_fmt = AV_PIX_FMT_NONE;
1439     }
1440
1441     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1442
1443     /* end of stream, output what is still in the buffers */
1444     if (buf_size == 0) {
1445  out:
1446
1447         h->cur_pic_ptr = NULL;
1448         h->first_field = 0;
1449
1450         // FIXME factorize this with the output code below
1451         out     = h->delayed_pic[0];
1452         out_idx = 0;
1453         for (i = 1;
1454              h->delayed_pic[i] &&
1455              !h->delayed_pic[i]->f->key_frame &&
1456              !h->delayed_pic[i]->mmco_reset;
1457              i++)
1458             if (h->delayed_pic[i]->poc < out->poc) {
1459                 out     = h->delayed_pic[i];
1460                 out_idx = i;
1461             }
1462
1463         for (i = out_idx; h->delayed_pic[i]; i++)
1464             h->delayed_pic[i] = h->delayed_pic[i + 1];
1465
1466         if (out) {
1467             out->reference &= ~DELAYED_PIC_REF;
1468             ret = output_frame(h, pict, out);
1469             if (ret < 0)
1470                 return ret;
1471             *got_frame = 1;
1472         }
1473
1474         return buf_index;
1475     }
1476     if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1477         int side_size;
1478         uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1479         if (is_extra(side, side_size))
1480             ff_h264_decode_extradata(h, side, side_size);
1481     }
1482     if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1483         if (is_extra(buf, buf_size))
1484             return ff_h264_decode_extradata(h, buf, buf_size);
1485     }
1486
1487     buf_index = decode_nal_units(h, buf, buf_size, 0);
1488     if (buf_index < 0)
1489         return AVERROR_INVALIDDATA;
1490
1491     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1492         av_assert0(buf_index <= buf_size);
1493         goto out;
1494     }
1495
1496     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1497         if (avctx->skip_frame >= AVDISCARD_NONREF ||
1498             buf_size >= 4 && !memcmp("Q264", buf, 4))
1499             return buf_size;
1500         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1501         return AVERROR_INVALIDDATA;
1502     }
1503
1504     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1505         (h->mb_y >= h->mb_height && h->mb_height)) {
1506         if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1507             decode_postinit(h, 1);
1508
1509         if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1510             return ret;
1511
1512         /* Wait for second field. */
1513         *got_frame = 0;
1514         if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1515                                    (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
1516                                    h->next_output_pic->recovered)) {
1517             if (!h->next_output_pic->recovered)
1518                 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1519
1520             if (!h->avctx->hwaccel &&
1521                  (h->next_output_pic->field_poc[0] == INT_MAX ||
1522                   h->next_output_pic->field_poc[1] == INT_MAX)
1523             ) {
1524                 int p;
1525                 AVFrame *f = h->next_output_pic->f;
1526                 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1527                 uint8_t *dst_data[4];
1528                 int linesizes[4];
1529                 const uint8_t *src_data[4];
1530
1531                 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1532
1533                 for (p = 0; p<4; p++) {
1534                     dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1535                     src_data[p] = f->data[p] +  field   *f->linesize[p];
1536                     linesizes[p] = 2*f->linesize[p];
1537                 }
1538
1539                 av_image_copy(dst_data, linesizes, src_data, linesizes,
1540                               f->format, f->width, f->height>>1);
1541             }
1542
1543             ret = output_frame(h, pict, h->next_output_pic);
1544             if (ret < 0)
1545                 return ret;
1546             *got_frame = 1;
1547             if (CONFIG_MPEGVIDEO) {
1548                 ff_print_debug_info2(h->avctx, pict, NULL,
1549                                     h->next_output_pic->mb_type,
1550                                     h->next_output_pic->qscale_table,
1551                                     h->next_output_pic->motion_val,
1552                                     &h->low_delay,
1553                                     h->mb_width, h->mb_height, h->mb_stride, 1);
1554             }
1555         }
1556     }
1557
1558     av_assert0(pict->buf[0] || !*got_frame);
1559
1560     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1561
1562     return get_consumed_bytes(buf_index, buf_size);
1563 }
1564
1565 av_cold void ff_h264_free_context(H264Context *h)
1566 {
1567     int i;
1568
1569     ff_h264_free_tables(h);
1570
1571     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1572         ff_h264_unref_picture(h, &h->DPB[i]);
1573         av_frame_free(&h->DPB[i].f);
1574     }
1575     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1576
1577     h->cur_pic_ptr = NULL;
1578
1579     for (i = 0; i < h->nb_slice_ctx; i++)
1580         av_freep(&h->slice_ctx[i].rbsp_buffer);
1581     av_freep(&h->slice_ctx);
1582     h->nb_slice_ctx = 0;
1583
1584     h->a53_caption_size = 0;
1585     av_freep(&h->a53_caption);
1586
1587     for (i = 0; i < MAX_SPS_COUNT; i++)
1588         av_freep(h->sps_buffers + i);
1589
1590     for (i = 0; i < MAX_PPS_COUNT; i++)
1591         av_freep(h->pps_buffers + i);
1592
1593     ff_h2645_packet_uninit(&h->pkt);
1594 }
1595
1596 static av_cold int h264_decode_end(AVCodecContext *avctx)
1597 {
1598     H264Context *h = avctx->priv_data;
1599
1600     ff_h264_remove_all_refs(h);
1601     ff_h264_free_context(h);
1602
1603     ff_h264_unref_picture(h, &h->cur_pic);
1604     av_frame_free(&h->cur_pic.f);
1605     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1606     av_frame_free(&h->last_pic_for_ec.f);
1607
1608     return 0;
1609 }
1610
1611 #define OFFSET(x) offsetof(H264Context, x)
1612 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1613 static const AVOption h264_options[] = {
1614     {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
1615     {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1616     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
1617     { NULL },
1618 };
1619
1620 static const AVClass h264_class = {
1621     .class_name = "H264 Decoder",
1622     .item_name  = av_default_item_name,
1623     .option     = h264_options,
1624     .version    = LIBAVUTIL_VERSION_INT,
1625 };
1626
1627 AVCodec ff_h264_decoder = {
1628     .name                  = "h264",
1629     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1630     .type                  = AVMEDIA_TYPE_VIDEO,
1631     .id                    = AV_CODEC_ID_H264,
1632     .priv_data_size        = sizeof(H264Context),
1633     .init                  = ff_h264_decode_init,
1634     .close                 = h264_decode_end,
1635     .decode                = h264_decode_frame,
1636     .capabilities          = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1637                              AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1638                              AV_CODEC_CAP_FRAME_THREADS,
1639     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE,
1640     .flush                 = flush_dpb,
1641     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1642     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1643     .profiles              = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1644     .priv_class            = &h264_class,
1645 };
1646
1647 #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
1648 static const AVClass h264_vdpau_class = {
1649     .class_name = "H264 VDPAU Decoder",
1650     .item_name  = av_default_item_name,
1651     .option     = h264_options,
1652     .version    = LIBAVUTIL_VERSION_INT,
1653 };
1654
1655 AVCodec ff_h264_vdpau_decoder = {
1656     .name           = "h264_vdpau",
1657     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1658     .type           = AVMEDIA_TYPE_VIDEO,
1659     .id             = AV_CODEC_ID_H264,
1660     .priv_data_size = sizeof(H264Context),
1661     .init           = ff_h264_decode_init,
1662     .close          = h264_decode_end,
1663     .decode         = h264_decode_frame,
1664     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
1665     .flush          = flush_dpb,
1666     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
1667                                                      AV_PIX_FMT_NONE},
1668     .profiles       = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1669     .priv_class     = &h264_vdpau_class,
1670 };
1671 #endif