]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
da7f88f66cbbdf4d80c95a949e75ccba999baff4
[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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/stereo3d.h"
33 #include "libavutil/timer.h"
34 #include "internal.h"
35 #include "bytestream.h"
36 #include "cabac.h"
37 #include "cabac_functions.h"
38 #include "error_resilience.h"
39 #include "avcodec.h"
40 #include "h264.h"
41 #include "h2645_parse.h"
42 #include "h264data.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
45 #include "golomb.h"
46 #include "mathops.h"
47 #include "me_cmp.h"
48 #include "mpegutils.h"
49 #include "profiles.h"
50 #include "rectangle.h"
51 #include "thread.h"
52
53 #include <assert.h>
54
55 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56
57 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
58                               int (*mv)[2][4][2],
59                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
60 {
61     H264Context *h = opaque;
62     H264SliceContext *sl = &h->slice_ctx[0];
63
64     sl->mb_x = mb_x;
65     sl->mb_y = mb_y;
66     sl->mb_xy = mb_x + mb_y * h->mb_stride;
67     memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
68     assert(ref >= 0);
69     /* FIXME: It is possible albeit uncommon that slice references
70      * differ between slices. We take the easy approach and ignore
71      * it for now. If this turns out to have any relevance in
72      * practice then correct remapping should be added. */
73     if (ref >= sl->ref_count[0])
74         ref = 0;
75     fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
76                    2, 2, 2, ref, 1);
77     fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
78     fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
79                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
80     assert(!FRAME_MBAFF(h));
81     ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
82 }
83
84 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
85                              int y, int height)
86 {
87     AVCodecContext *avctx = h->avctx;
88     const AVFrame   *src  = h->cur_pic.f;
89     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
90     int vshift = desc->log2_chroma_h;
91     const int field_pic = h->picture_structure != PICT_FRAME;
92     if (field_pic) {
93         height <<= 1;
94         y      <<= 1;
95     }
96
97     height = FFMIN(height, avctx->height - y);
98
99     if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
100         return;
101
102     if (avctx->draw_horiz_band) {
103         int offset[AV_NUM_DATA_POINTERS];
104         int i;
105
106         offset[0] = y * src->linesize[0];
107         offset[1] =
108         offset[2] = (y >> vshift) * src->linesize[1];
109         for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
110             offset[i] = 0;
111
112         emms_c();
113
114         avctx->draw_horiz_band(avctx, src, offset,
115                                y, h->picture_structure, height);
116     }
117 }
118
119 void ff_h264_free_tables(H264Context *h)
120 {
121     int i;
122
123     av_freep(&h->intra4x4_pred_mode);
124     av_freep(&h->chroma_pred_mode_table);
125     av_freep(&h->cbp_table);
126     av_freep(&h->mvd_table[0]);
127     av_freep(&h->mvd_table[1]);
128     av_freep(&h->direct_table);
129     av_freep(&h->non_zero_count);
130     av_freep(&h->slice_table_base);
131     h->slice_table = NULL;
132     av_freep(&h->list_counts);
133
134     av_freep(&h->mb2b_xy);
135     av_freep(&h->mb2br_xy);
136
137     av_buffer_pool_uninit(&h->qscale_table_pool);
138     av_buffer_pool_uninit(&h->mb_type_pool);
139     av_buffer_pool_uninit(&h->motion_val_pool);
140     av_buffer_pool_uninit(&h->ref_index_pool);
141
142     for (i = 0; i < h->nb_slice_ctx; i++) {
143         H264SliceContext *sl = &h->slice_ctx[i];
144
145         av_freep(&sl->dc_val_base);
146         av_freep(&sl->er.mb_index2xy);
147         av_freep(&sl->er.error_status_table);
148         av_freep(&sl->er.er_temp_buffer);
149
150         av_freep(&sl->bipred_scratchpad);
151         av_freep(&sl->edge_emu_buffer);
152         av_freep(&sl->top_borders[0]);
153         av_freep(&sl->top_borders[1]);
154
155         sl->bipred_scratchpad_allocated = 0;
156         sl->edge_emu_buffer_allocated   = 0;
157         sl->top_borders_allocated[0]    = 0;
158         sl->top_borders_allocated[1]    = 0;
159     }
160 }
161
162 int ff_h264_alloc_tables(H264Context *h)
163 {
164     const int big_mb_num = h->mb_stride * (h->mb_height + 1);
165     const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
166     int x, y;
167
168     FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
169                       row_mb_num * 8 * sizeof(uint8_t), fail)
170     h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
171
172     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
173                       big_mb_num * 48 * sizeof(uint8_t), fail)
174     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
175                       (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
176     FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
177                       big_mb_num * sizeof(uint16_t), fail)
178     FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
179                       big_mb_num * sizeof(uint8_t), fail)
180     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
181                       16 * row_mb_num * sizeof(uint8_t), fail);
182     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
183                       16 * row_mb_num * sizeof(uint8_t), fail);
184     h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
185     h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
186
187     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
188                       4 * big_mb_num * sizeof(uint8_t), fail);
189     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
190                       big_mb_num * sizeof(uint8_t), fail)
191
192     memset(h->slice_table_base, -1,
193            (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
194     h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
195
196     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
197                       big_mb_num * sizeof(uint32_t), fail);
198     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
199                       big_mb_num * sizeof(uint32_t), fail);
200     for (y = 0; y < h->mb_height; y++)
201         for (x = 0; x < h->mb_width; x++) {
202             const int mb_xy = x + y * h->mb_stride;
203             const int b_xy  = 4 * x + 4 * y * h->b_stride;
204
205             h->mb2b_xy[mb_xy]  = b_xy;
206             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
207         }
208
209     if (!h->dequant4_coeff[0])
210         ff_h264_init_dequant_tables(h);
211
212     return 0;
213
214 fail:
215     ff_h264_free_tables(h);
216     return AVERROR(ENOMEM);
217 }
218
219 /**
220  * Init context
221  * Allocate buffers which are not shared amongst multiple threads.
222  */
223 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
224 {
225     ERContext *er = &sl->er;
226     int mb_array_size = h->mb_height * h->mb_stride;
227     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
228     int c_size  = h->mb_stride * (h->mb_height + 1);
229     int yc_size = y_size + 2   * c_size;
230     int x, y, i;
231
232     sl->ref_cache[0][scan8[5]  + 1] =
233     sl->ref_cache[0][scan8[7]  + 1] =
234     sl->ref_cache[0][scan8[13] + 1] =
235     sl->ref_cache[1][scan8[5]  + 1] =
236     sl->ref_cache[1][scan8[7]  + 1] =
237     sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
238
239     if (CONFIG_ERROR_RESILIENCE) {
240         /* init ER */
241         er->avctx          = h->avctx;
242         er->decode_mb      = h264_er_decode_mb;
243         er->opaque         = h;
244         er->quarter_sample = 1;
245
246         er->mb_num      = h->mb_num;
247         er->mb_width    = h->mb_width;
248         er->mb_height   = h->mb_height;
249         er->mb_stride   = h->mb_stride;
250         er->b8_stride   = h->mb_width * 2 + 1;
251
252         // error resilience code looks cleaner with this
253         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
254                           (h->mb_num + 1) * sizeof(int), fail);
255
256         for (y = 0; y < h->mb_height; y++)
257             for (x = 0; x < h->mb_width; x++)
258                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
259
260         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
261                                                       h->mb_stride + h->mb_width;
262
263         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
264                           mb_array_size * sizeof(uint8_t), fail);
265
266         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
267                          h->mb_height * h->mb_stride, fail);
268
269         FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
270                           yc_size * sizeof(int16_t), fail);
271         er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
272         er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
273         er->dc_val[2] = er->dc_val[1] + c_size;
274         for (i = 0; i < yc_size; i++)
275             sl->dc_val_base[i] = 1024;
276     }
277
278     return 0;
279
280 fail:
281     return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
282 }
283
284 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
285                             int parse_extradata);
286
287 /* There are (invalid) samples in the wild with mp4-style extradata, where the
288  * parameter sets are stored unescaped (i.e. as RBSP).
289  * This function catches the parameter set decoding failure and tries again
290  * after escaping it */
291 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
292 {
293     int ret;
294
295     ret = decode_nal_units(h, buf, buf_size, 1);
296     if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
297         GetByteContext gbc;
298         PutByteContext pbc;
299         uint8_t *escaped_buf;
300         int escaped_buf_size;
301
302         av_log(h->avctx, AV_LOG_WARNING,
303                "SPS decoding failure, trying again after escaping the NAL\n");
304
305         if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
306             return AVERROR(ERANGE);
307         escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
308         escaped_buf = av_mallocz(escaped_buf_size);
309         if (!escaped_buf)
310             return AVERROR(ENOMEM);
311
312         bytestream2_init(&gbc, buf, buf_size);
313         bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
314
315         while (bytestream2_get_bytes_left(&gbc)) {
316             if (bytestream2_get_bytes_left(&gbc) >= 3 &&
317                 bytestream2_peek_be24(&gbc) <= 3) {
318                 bytestream2_put_be24(&pbc, 3);
319                 bytestream2_skip(&gbc, 2);
320             } else
321                 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
322         }
323
324         escaped_buf_size = bytestream2_tell_p(&pbc);
325         AV_WB16(escaped_buf, escaped_buf_size - 2);
326
327         ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
328         av_freep(&escaped_buf);
329         if (ret < 0)
330             return ret;
331     }
332
333     return 0;
334 }
335
336 int ff_h264_decode_extradata(H264Context *h)
337 {
338     AVCodecContext *avctx = h->avctx;
339     int ret;
340
341     if (avctx->extradata[0] == 1) {
342         int i, cnt, nalsize;
343         unsigned char *p = avctx->extradata;
344
345         h->is_avc = 1;
346
347         if (avctx->extradata_size < 7) {
348             av_log(avctx, AV_LOG_ERROR,
349                    "avcC %d too short\n", avctx->extradata_size);
350             return AVERROR_INVALIDDATA;
351         }
352         /* sps and pps in the avcC always have length coded with 2 bytes,
353          * so put a fake nal_length_size = 2 while parsing them */
354         h->nal_length_size = 2;
355         // Decode sps from avcC
356         cnt = *(p + 5) & 0x1f; // Number of sps
357         p  += 6;
358         for (i = 0; i < cnt; i++) {
359             nalsize = AV_RB16(p) + 2;
360             if (p - avctx->extradata + nalsize > avctx->extradata_size)
361                 return AVERROR_INVALIDDATA;
362             ret = decode_extradata_ps_mp4(h, p, nalsize);
363             if (ret < 0) {
364                 av_log(avctx, AV_LOG_ERROR,
365                        "Decoding sps %d from avcC failed\n", i);
366                 return ret;
367             }
368             p += nalsize;
369         }
370         // Decode pps from avcC
371         cnt = *(p++); // Number of pps
372         for (i = 0; i < cnt; i++) {
373             nalsize = AV_RB16(p) + 2;
374             if (p - avctx->extradata + nalsize > avctx->extradata_size)
375                 return AVERROR_INVALIDDATA;
376             ret = decode_extradata_ps_mp4(h, p, nalsize);
377             if (ret < 0) {
378                 av_log(avctx, AV_LOG_ERROR,
379                        "Decoding pps %d from avcC failed\n", i);
380                 return ret;
381             }
382             p += nalsize;
383         }
384         // Store right nal length size that will be used to parse all other nals
385         h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
386     } else {
387         h->is_avc = 0;
388         ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
389         if (ret < 0)
390             return ret;
391     }
392     return 0;
393 }
394
395 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
396 {
397     int i;
398
399     h->avctx                 = avctx;
400     h->dequant_coeff_pps     = -1;
401
402     h->picture_structure     = PICT_FRAME;
403     h->slice_context_count   = 1;
404     h->workaround_bugs       = avctx->workaround_bugs;
405     h->flags                 = avctx->flags;
406     h->prev_poc_msb          = 1 << 16;
407     h->x264_build            = -1;
408     h->recovery_frame        = -1;
409     h->frame_recovered       = 0;
410
411     h->next_outputed_poc = INT_MIN;
412     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
413         h->last_pocs[i] = INT_MIN;
414
415     ff_h264_reset_sei(h);
416
417     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
418
419     h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;
420     h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
421     if (!h->slice_ctx) {
422         h->nb_slice_ctx = 0;
423         return AVERROR(ENOMEM);
424     }
425
426     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
427         h->DPB[i].f = av_frame_alloc();
428         if (!h->DPB[i].f)
429             return AVERROR(ENOMEM);
430     }
431
432     h->cur_pic.f = av_frame_alloc();
433     if (!h->cur_pic.f)
434         return AVERROR(ENOMEM);
435
436     for (i = 0; i < h->nb_slice_ctx; i++)
437         h->slice_ctx[i].h264 = h;
438
439     return 0;
440 }
441
442 static AVOnce h264_vlc_init = AV_ONCE_INIT;
443
444 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
445 {
446     H264Context *h = avctx->priv_data;
447     int ret;
448
449     ret = h264_init_context(avctx, h);
450     if (ret < 0)
451         return ret;
452
453     /* set defaults */
454     if (!avctx->has_b_frames)
455         h->low_delay = 1;
456
457     ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
458     if (ret != 0) {
459         av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
460         return AVERROR_UNKNOWN;
461     }
462
463     if (avctx->codec_id == AV_CODEC_ID_H264) {
464         if (avctx->ticks_per_frame == 1)
465             h->avctx->framerate.num *= 2;
466         avctx->ticks_per_frame = 2;
467     }
468
469     if (avctx->extradata_size > 0 && avctx->extradata) {
470        ret = ff_h264_decode_extradata(h);
471        if (ret < 0) {
472            ff_h264_free_context(h);
473            return ret;
474        }
475     }
476
477     if (h->sps.bitstream_restriction_flag &&
478         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
479         h->avctx->has_b_frames = h->sps.num_reorder_frames;
480         h->low_delay           = 0;
481     }
482
483     avctx->internal->allocate_progress = 1;
484
485     if (h->enable_er) {
486         av_log(avctx, AV_LOG_WARNING,
487                "Error resilience is enabled. It is unsafe and unsupported and may crash. "
488                "Use it at your own risk\n");
489     }
490
491     return 0;
492 }
493
494 static int decode_init_thread_copy(AVCodecContext *avctx)
495 {
496     H264Context *h = avctx->priv_data;
497     int ret;
498
499     if (!avctx->internal->is_copy)
500         return 0;
501
502     memset(h, 0, sizeof(*h));
503
504     ret = h264_init_context(avctx, h);
505     if (ret < 0)
506         return ret;
507
508     h->context_initialized = 0;
509
510     return 0;
511 }
512
513 /**
514  * Run setup operations that must be run after slice header decoding.
515  * This includes finding the next displayed frame.
516  *
517  * @param h h264 master context
518  * @param setup_finished enough NALs have been read that we can call
519  * ff_thread_finish_setup()
520  */
521 static void decode_postinit(H264Context *h, int setup_finished)
522 {
523     H264Picture *out = h->cur_pic_ptr;
524     H264Picture *cur = h->cur_pic_ptr;
525     int i, pics, out_of_order, out_idx;
526     int invalid = 0, cnt = 0;
527
528     h->cur_pic_ptr->f->pict_type = h->pict_type;
529
530     if (h->next_output_pic)
531         return;
532
533     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
534         /* FIXME: if we have two PAFF fields in one packet, we can't start
535          * the next thread here. If we have one field per packet, we can.
536          * The check in decode_nal_units() is not good enough to find this
537          * yet, so we assume the worst for now. */
538         // if (setup_finished)
539         //    ff_thread_finish_setup(h->avctx);
540         return;
541     }
542
543     cur->f->interlaced_frame = 0;
544     cur->f->repeat_pict      = 0;
545
546     /* Signal interlacing information externally. */
547     /* Prioritize picture timing SEI information over used
548      * decoding process if it exists. */
549
550     if (h->sps.pic_struct_present_flag) {
551         switch (h->sei_pic_struct) {
552         case SEI_PIC_STRUCT_FRAME:
553             break;
554         case SEI_PIC_STRUCT_TOP_FIELD:
555         case SEI_PIC_STRUCT_BOTTOM_FIELD:
556             cur->f->interlaced_frame = 1;
557             break;
558         case SEI_PIC_STRUCT_TOP_BOTTOM:
559         case SEI_PIC_STRUCT_BOTTOM_TOP:
560             if (FIELD_OR_MBAFF_PICTURE(h))
561                 cur->f->interlaced_frame = 1;
562             else
563                 // try to flag soft telecine progressive
564                 cur->f->interlaced_frame = h->prev_interlaced_frame;
565             break;
566         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
567         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
568             /* Signal the possibility of telecined film externally
569              * (pic_struct 5,6). From these hints, let the applications
570              * decide if they apply deinterlacing. */
571             cur->f->repeat_pict = 1;
572             break;
573         case SEI_PIC_STRUCT_FRAME_DOUBLING:
574             cur->f->repeat_pict = 2;
575             break;
576         case SEI_PIC_STRUCT_FRAME_TRIPLING:
577             cur->f->repeat_pict = 4;
578             break;
579         }
580
581         if ((h->sei_ct_type & 3) &&
582             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
583             cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
584     } else {
585         /* Derive interlacing flag from used decoding process. */
586         cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
587     }
588     h->prev_interlaced_frame = cur->f->interlaced_frame;
589
590     if (cur->field_poc[0] != cur->field_poc[1]) {
591         /* Derive top_field_first from field pocs. */
592         cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
593     } else {
594         if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
595             /* Use picture timing SEI information. Even if it is a
596              * information of a past frame, better than nothing. */
597             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
598                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
599                 cur->f->top_field_first = 1;
600             else
601                 cur->f->top_field_first = 0;
602         } else {
603             /* Most likely progressive */
604             cur->f->top_field_first = 0;
605         }
606     }
607
608     if (h->sei_frame_packing_present &&
609         h->frame_packing_arrangement_type >= 0 &&
610         h->frame_packing_arrangement_type <= 6 &&
611         h->content_interpretation_type > 0 &&
612         h->content_interpretation_type < 3) {
613         AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
614         if (!stereo)
615             return;
616
617         switch (h->frame_packing_arrangement_type) {
618         case 0:
619             stereo->type = AV_STEREO3D_CHECKERBOARD;
620             break;
621         case 1:
622             stereo->type = AV_STEREO3D_COLUMNS;
623             break;
624         case 2:
625             stereo->type = AV_STEREO3D_LINES;
626             break;
627         case 3:
628             if (h->quincunx_subsampling)
629                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
630             else
631                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
632             break;
633         case 4:
634             stereo->type = AV_STEREO3D_TOPBOTTOM;
635             break;
636         case 5:
637             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
638             break;
639         case 6:
640             stereo->type = AV_STEREO3D_2D;
641             break;
642         }
643
644         if (h->content_interpretation_type == 2)
645             stereo->flags = AV_STEREO3D_FLAG_INVERT;
646     }
647
648     if (h->sei_display_orientation_present &&
649         (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
650         double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
651         AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
652                                                            AV_FRAME_DATA_DISPLAYMATRIX,
653                                                            sizeof(int32_t) * 9);
654         if (!rotation)
655             return;
656
657         av_display_rotation_set((int32_t *)rotation->data, angle);
658         av_display_matrix_flip((int32_t *)rotation->data,
659                                h->sei_hflip, h->sei_vflip);
660     }
661
662     if (h->sei_reguserdata_afd_present) {
663         AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
664                                                      sizeof(uint8_t));
665         if (!sd)
666             return;
667
668         *sd->data = h->active_format_description;
669         h->sei_reguserdata_afd_present = 0;
670     }
671
672     if (h->a53_caption) {
673         AVFrameSideData *sd = av_frame_new_side_data(cur->f,
674                                                      AV_FRAME_DATA_A53_CC,
675                                                      h->a53_caption_size);
676         if (!sd)
677             return;
678
679         memcpy(sd->data, h->a53_caption, h->a53_caption_size);
680         av_freep(&h->a53_caption);
681         h->a53_caption_size = 0;
682     }
683
684     // FIXME do something with unavailable reference frames
685
686     /* Sort B-frames into display order */
687     if (h->sps.bitstream_restriction_flag ||
688         h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
689         h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
690     }
691     h->low_delay = !h->avctx->has_b_frames;
692
693     pics = 0;
694     while (h->delayed_pic[pics])
695         pics++;
696
697     assert(pics <= MAX_DELAYED_PIC_COUNT);
698
699     h->delayed_pic[pics++] = cur;
700     if (cur->reference == 0)
701         cur->reference = DELAYED_PIC_REF;
702
703     /* Frame reordering. This code takes pictures from coding order and sorts
704      * them by their incremental POC value into display order. It supports POC
705      * gaps, MMCO reset codes and random resets.
706      * A "display group" can start either with a IDR frame (f.key_frame = 1),
707      * and/or can be closed down with a MMCO reset code. In sequences where
708      * there is no delay, we can't detect that (since the frame was already
709      * output to the user), so we also set h->mmco_reset to detect the MMCO
710      * reset code.
711      * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
712      * we increase the delay between input and output. All frames affected by
713      * the lag (e.g. those that should have been output before another frame
714      * that we already returned to the user) will be dropped. This is a bug
715      * that we will fix later. */
716     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
717         cnt     += out->poc < h->last_pocs[i];
718         invalid += out->poc == INT_MIN;
719     }
720     if (!h->mmco_reset && !cur->f->key_frame &&
721         cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
722         h->mmco_reset = 2;
723         if (pics > 1)
724             h->delayed_pic[pics - 2]->mmco_reset = 2;
725     }
726     if (h->mmco_reset || cur->f->key_frame) {
727         for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
728             h->last_pocs[i] = INT_MIN;
729         cnt     = 0;
730         invalid = MAX_DELAYED_PIC_COUNT;
731     }
732     out     = h->delayed_pic[0];
733     out_idx = 0;
734     for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
735                 h->delayed_pic[i] &&
736                 !h->delayed_pic[i - 1]->mmco_reset &&
737                 !h->delayed_pic[i]->f->key_frame;
738          i++)
739         if (h->delayed_pic[i]->poc < out->poc) {
740             out     = h->delayed_pic[i];
741             out_idx = i;
742         }
743     if (h->avctx->has_b_frames == 0 &&
744         (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
745         h->next_outputed_poc = INT_MIN;
746     out_of_order = !out->f->key_frame && !h->mmco_reset &&
747                    (out->poc < h->next_outputed_poc);
748
749     if (h->sps.bitstream_restriction_flag &&
750         h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
751     } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
752                h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
753         if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
754             h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
755         }
756         h->low_delay = 0;
757     } else if (h->low_delay &&
758                ((h->next_outputed_poc != INT_MIN &&
759                  out->poc > h->next_outputed_poc + 2) ||
760                 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
761         h->low_delay = 0;
762         h->avctx->has_b_frames++;
763     }
764
765     if (pics > h->avctx->has_b_frames) {
766         out->reference &= ~DELAYED_PIC_REF;
767         // for frame threading, the owner must be the second field's thread or
768         // else the first thread can release the picture and reuse it unsafely
769         for (i = out_idx; h->delayed_pic[i]; i++)
770             h->delayed_pic[i] = h->delayed_pic[i + 1];
771     }
772     memmove(h->last_pocs, &h->last_pocs[1],
773             sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
774     h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
775     if (!out_of_order && pics > h->avctx->has_b_frames) {
776         h->next_output_pic = out;
777         if (out->mmco_reset) {
778             if (out_idx > 0) {
779                 h->next_outputed_poc                    = out->poc;
780                 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
781             } else {
782                 h->next_outputed_poc = INT_MIN;
783             }
784         } else {
785             if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
786                 h->next_outputed_poc = INT_MIN;
787             } else {
788                 h->next_outputed_poc = out->poc;
789             }
790         }
791         h->mmco_reset = 0;
792     } else {
793         av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
794     }
795
796     if (h->next_output_pic) {
797         if (h->next_output_pic->recovered) {
798             // We have reached an recovery point and all frames after it in
799             // display order are "recovered".
800             h->frame_recovered |= FRAME_RECOVERED_SEI;
801         }
802         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
803     }
804
805     if (setup_finished && !h->avctx->hwaccel) {
806         ff_thread_finish_setup(h->avctx);
807
808         if (h->avctx->active_thread_type & FF_THREAD_FRAME)
809             h->setup_finished = 1;
810     }
811 }
812
813 /**
814  * instantaneous decoder refresh.
815  */
816 static void idr(H264Context *h)
817 {
818     ff_h264_remove_all_refs(h);
819     h->prev_frame_num        =
820     h->prev_frame_num_offset =
821     h->prev_poc_msb          =
822     h->prev_poc_lsb          = 0;
823 }
824
825 /* forget old pics after a seek */
826 void ff_h264_flush_change(H264Context *h)
827 {
828     int i;
829     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
830         h->last_pocs[i] = INT_MIN;
831     h->next_outputed_poc = INT_MIN;
832     h->prev_interlaced_frame = 1;
833     idr(h);
834     if (h->cur_pic_ptr)
835         h->cur_pic_ptr->reference = 0;
836     h->first_field = 0;
837     ff_h264_reset_sei(h);
838     h->recovery_frame = -1;
839     h->frame_recovered = 0;
840 }
841
842 /* forget old pics after a seek */
843 static void flush_dpb(AVCodecContext *avctx)
844 {
845     H264Context *h = avctx->priv_data;
846     int i;
847
848     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
849
850     ff_h264_flush_change(h);
851
852     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
853         ff_h264_unref_picture(h, &h->DPB[i]);
854     h->cur_pic_ptr = NULL;
855     ff_h264_unref_picture(h, &h->cur_pic);
856
857     h->mb_y = 0;
858
859     ff_h264_free_tables(h);
860     h->context_initialized = 0;
861 }
862
863 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
864 {
865     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
866     int field_poc[2];
867
868     h->frame_num_offset = h->prev_frame_num_offset;
869     if (h->frame_num < h->prev_frame_num)
870         h->frame_num_offset += max_frame_num;
871
872     if (h->sps.poc_type == 0) {
873         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
874
875         if (h->poc_lsb < h->prev_poc_lsb &&
876             h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
877             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
878         else if (h->poc_lsb > h->prev_poc_lsb &&
879                  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
880             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
881         else
882             h->poc_msb = h->prev_poc_msb;
883         field_poc[0] =
884         field_poc[1] = h->poc_msb + h->poc_lsb;
885         if (h->picture_structure == PICT_FRAME)
886             field_poc[1] += h->delta_poc_bottom;
887     } else if (h->sps.poc_type == 1) {
888         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
889         int i;
890
891         if (h->sps.poc_cycle_length != 0)
892             abs_frame_num = h->frame_num_offset + h->frame_num;
893         else
894             abs_frame_num = 0;
895
896         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
897             abs_frame_num--;
898
899         expected_delta_per_poc_cycle = 0;
900         for (i = 0; i < h->sps.poc_cycle_length; i++)
901             // FIXME integrate during sps parse
902             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
903
904         if (abs_frame_num > 0) {
905             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
906             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
907
908             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
909             for (i = 0; i <= frame_num_in_poc_cycle; i++)
910                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
911         } else
912             expectedpoc = 0;
913
914         if (h->nal_ref_idc == 0)
915             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
916
917         field_poc[0] = expectedpoc + h->delta_poc[0];
918         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
919
920         if (h->picture_structure == PICT_FRAME)
921             field_poc[1] += h->delta_poc[1];
922     } else {
923         int poc = 2 * (h->frame_num_offset + h->frame_num);
924
925         if (!h->nal_ref_idc)
926             poc--;
927
928         field_poc[0] = poc;
929         field_poc[1] = poc;
930     }
931
932     if (h->picture_structure != PICT_BOTTOM_FIELD)
933         pic_field_poc[0] = field_poc[0];
934     if (h->picture_structure != PICT_TOP_FIELD)
935         pic_field_poc[1] = field_poc[1];
936     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
937
938     return 0;
939 }
940
941 /**
942  * Compute profile from profile_idc and constraint_set?_flags.
943  *
944  * @param sps SPS
945  *
946  * @return profile as defined by FF_PROFILE_H264_*
947  */
948 int ff_h264_get_profile(SPS *sps)
949 {
950     int profile = sps->profile_idc;
951
952     switch (sps->profile_idc) {
953     case FF_PROFILE_H264_BASELINE:
954         // constraint_set1_flag set to 1
955         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
956         break;
957     case FF_PROFILE_H264_HIGH_10:
958     case FF_PROFILE_H264_HIGH_422:
959     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
960         // constraint_set3_flag set to 1
961         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
962         break;
963     }
964
965     return profile;
966 }
967
968 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
969 {
970     int ref_count[2], list_count;
971     int num_ref_idx_active_override_flag, max_refs;
972
973     // set defaults, might be overridden a few lines later
974     ref_count[0] = h->pps.ref_count[0];
975     ref_count[1] = h->pps.ref_count[1];
976
977     if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
978         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
979             sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
980         num_ref_idx_active_override_flag = get_bits1(&sl->gb);
981
982         if (num_ref_idx_active_override_flag) {
983             ref_count[0] = get_ue_golomb(&sl->gb) + 1;
984             if (ref_count[0] < 1)
985                 return AVERROR_INVALIDDATA;
986             if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
987                 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
988                 if (ref_count[1] < 1)
989                     return AVERROR_INVALIDDATA;
990             }
991         }
992
993         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
994             list_count = 2;
995         else
996             list_count = 1;
997     } else {
998         list_count   = 0;
999         ref_count[0] = ref_count[1] = 0;
1000     }
1001
1002     max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1003
1004     if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1005         av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1006         sl->ref_count[0] = sl->ref_count[1] = 0;
1007         return AVERROR_INVALIDDATA;
1008     }
1009
1010     if (list_count   != sl->list_count   ||
1011         ref_count[0] != sl->ref_count[0] ||
1012         ref_count[1] != sl->ref_count[1]) {
1013         sl->ref_count[0] = ref_count[0];
1014         sl->ref_count[1] = ref_count[1];
1015         sl->list_count   = list_count;
1016         return 1;
1017     }
1018
1019     return 0;
1020 }
1021
1022 static int get_last_needed_nal(H264Context *h)
1023 {
1024     int nals_needed = 0;
1025     int i;
1026
1027     for (i = 0; i < h->pkt.nb_nals; i++) {
1028         H2645NAL *nal = &h->pkt.nals[i];
1029         GetBitContext gb;
1030
1031         /* packets can sometimes contain multiple PPS/SPS,
1032          * e.g. two PAFF field pictures in one packet, or a demuxer
1033          * which splits NALs strangely if so, when frame threading we
1034          * can't start the next thread until we've read all of them */
1035         switch (nal->type) {
1036         case NAL_SPS:
1037         case NAL_PPS:
1038             nals_needed = i;
1039             break;
1040         case NAL_DPA:
1041         case NAL_IDR_SLICE:
1042         case NAL_SLICE:
1043             init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
1044             if (!get_ue_golomb(&gb))
1045                 nals_needed = i;
1046         }
1047     }
1048
1049     return nals_needed;
1050 }
1051
1052 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1053                             int parse_extradata)
1054 {
1055     AVCodecContext *const avctx = h->avctx;
1056     unsigned context_count = 0;
1057     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1058     int i, ret = 0;
1059
1060     h->max_contexts = h->slice_context_count;
1061     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1062         h->current_slice = 0;
1063         if (!h->first_field)
1064             h->cur_pic_ptr = NULL;
1065         ff_h264_reset_sei(h);
1066     }
1067
1068     ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
1069                                 h->nal_length_size, avctx->codec_id);
1070     if (ret < 0) {
1071         av_log(avctx, AV_LOG_ERROR,
1072                "Error splitting the input into NAL units.\n");
1073         return ret;
1074     }
1075
1076     if (avctx->active_thread_type & FF_THREAD_FRAME)
1077         nals_needed = get_last_needed_nal(h);
1078
1079     for (i = 0; i < h->pkt.nb_nals; i++) {
1080         H2645NAL *nal = &h->pkt.nals[i];
1081         H264SliceContext *sl = &h->slice_ctx[context_count];
1082         int err;
1083
1084         if (avctx->skip_frame >= AVDISCARD_NONREF &&
1085             nal->ref_idc == 0 && nal->type != NAL_SEI)
1086             continue;
1087
1088 again:
1089         /* Ignore every NAL unit type except PPS and SPS during extradata
1090          * parsing. Decoding slices is not possible in codec init
1091          * with frame-mt */
1092         if (parse_extradata && HAVE_THREADS &&
1093             (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1094             (nal->type != NAL_PPS && nal->type != NAL_SPS)) {
1095             if (nal->type < NAL_AUD || nal->type > NAL_AUXILIARY_SLICE)
1096                 av_log(avctx, AV_LOG_INFO,
1097                        "Ignoring NAL unit %d during extradata parsing\n",
1098                        nal->type);
1099             nal->type = NAL_FF_IGNORE;
1100         }
1101
1102         // FIXME these should stop being context-global variables
1103         h->nal_ref_idc   = nal->ref_idc;
1104         h->nal_unit_type = nal->type;
1105
1106         err = 0;
1107         switch (nal->type) {
1108         case NAL_IDR_SLICE:
1109             if (nal->type != NAL_IDR_SLICE) {
1110                 av_log(h->avctx, AV_LOG_ERROR,
1111                        "Invalid mix of idr and non-idr slices\n");
1112                 ret = -1;
1113                 goto end;
1114             }
1115             idr(h); // FIXME ensure we don't lose some frames if there is reordering
1116         case NAL_SLICE:
1117             sl->gb = nal->gb;
1118
1119             if ((err = ff_h264_decode_slice_header(h, sl)))
1120                 break;
1121
1122             if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1123                 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1124                                     ((1 << h->sps.log2_max_frame_num) - 1);
1125             }
1126
1127             h->cur_pic_ptr->f->key_frame |=
1128                 (nal->type == NAL_IDR_SLICE) || (h->sei_recovery_frame_cnt >= 0);
1129
1130             if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->frame_num) {
1131                 h->recovery_frame         = -1;
1132                 h->cur_pic_ptr->recovered = 1;
1133             }
1134             // If we have an IDR, all frames after it in decoded order are
1135             // "recovered".
1136             if (nal->type == NAL_IDR_SLICE)
1137                 h->frame_recovered |= FRAME_RECOVERED_IDR;
1138             h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1139
1140             if (h->current_slice == 1) {
1141                 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1142                     decode_postinit(h, i >= nals_needed);
1143
1144                 if (h->avctx->hwaccel &&
1145                     (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1146                     return ret;
1147             }
1148
1149             if (sl->redundant_pic_count == 0 &&
1150                 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1151                 (avctx->skip_frame < AVDISCARD_BIDIR  ||
1152                  sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1153                 (avctx->skip_frame < AVDISCARD_NONKEY ||
1154                  h->cur_pic_ptr->f->key_frame) &&
1155                 avctx->skip_frame < AVDISCARD_ALL) {
1156                 if (avctx->hwaccel) {
1157                     ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
1158                     if (ret < 0)
1159                         return ret;
1160                 } else
1161                     context_count++;
1162             }
1163             break;
1164         case NAL_DPA:
1165         case NAL_DPB:
1166         case NAL_DPC:
1167             avpriv_request_sample(avctx, "data partitioning");
1168             ret = AVERROR(ENOSYS);
1169             goto end;
1170             break;
1171         case NAL_SEI:
1172             h->gb = nal->gb;
1173             ret = ff_h264_decode_sei(h);
1174             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1175                 goto end;
1176             break;
1177         case NAL_SPS:
1178             h->gb = nal->gb;
1179             ret = ff_h264_decode_seq_parameter_set(h);
1180             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1181                 goto end;
1182             break;
1183         case NAL_PPS:
1184             h->gb = nal->gb;
1185             ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
1186             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1187                 goto end;
1188             break;
1189         case NAL_AUD:
1190         case NAL_END_SEQUENCE:
1191         case NAL_END_STREAM:
1192         case NAL_FILLER_DATA:
1193         case NAL_SPS_EXT:
1194         case NAL_AUXILIARY_SLICE:
1195             break;
1196         case NAL_FF_IGNORE:
1197             break;
1198         default:
1199             av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1200                    nal->type, nal->size_bits);
1201         }
1202
1203         if (context_count == h->max_contexts) {
1204             ret = ff_h264_execute_decode_slices(h, context_count);
1205             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1206                 goto end;
1207             context_count = 0;
1208         }
1209
1210         if (err < 0) {
1211             av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1212             sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1213         } else if (err == 1) {
1214             /* Slice could not be decoded in parallel mode, restart. Note
1215              * that rbsp_buffer is not transferred, but since we no longer
1216              * run in parallel mode this should not be an issue. */
1217             sl               = &h->slice_ctx[0];
1218             goto again;
1219         }
1220     }
1221     if (context_count) {
1222         ret = ff_h264_execute_decode_slices(h, context_count);
1223         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1224             goto end;
1225     }
1226
1227     ret = 0;
1228 end:
1229     /* clean up */
1230     if (h->cur_pic_ptr && !h->droppable) {
1231         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1232                                   h->picture_structure == PICT_BOTTOM_FIELD);
1233     }
1234
1235     return (ret < 0) ? ret : buf_size;
1236 }
1237
1238 /**
1239  * Return the number of bytes consumed for building the current frame.
1240  */
1241 static int get_consumed_bytes(int pos, int buf_size)
1242 {
1243     if (pos == 0)
1244         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
1245     if (pos + 10 > buf_size)
1246         pos = buf_size; // oops ;)
1247
1248     return pos;
1249 }
1250
1251 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1252 {
1253     int i;
1254     int ret = av_frame_ref(dst, src);
1255     if (ret < 0)
1256         return ret;
1257
1258     if (!h->sps.crop)
1259         return 0;
1260
1261     for (i = 0; i < 3; i++) {
1262         int hshift = (i > 0) ? h->chroma_x_shift : 0;
1263         int vshift = (i > 0) ? h->chroma_y_shift : 0;
1264         int off    = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1265                      (h->sps.crop_top >> vshift) * dst->linesize[i];
1266         dst->data[i] += off;
1267     }
1268     return 0;
1269 }
1270
1271 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1272                              int *got_frame, AVPacket *avpkt)
1273 {
1274     const uint8_t *buf = avpkt->data;
1275     int buf_size       = avpkt->size;
1276     H264Context *h     = avctx->priv_data;
1277     AVFrame *pict      = data;
1278     int buf_index      = 0;
1279     int ret;
1280
1281     h->flags = avctx->flags;
1282     h->setup_finished = 0;
1283
1284     /* end of stream, output what is still in the buffers */
1285 out:
1286     if (buf_size == 0) {
1287         H264Picture *out;
1288         int i, out_idx;
1289
1290         h->cur_pic_ptr = NULL;
1291
1292         // FIXME factorize this with the output code below
1293         out     = h->delayed_pic[0];
1294         out_idx = 0;
1295         for (i = 1;
1296              h->delayed_pic[i] &&
1297              !h->delayed_pic[i]->f->key_frame &&
1298              !h->delayed_pic[i]->mmco_reset;
1299              i++)
1300             if (h->delayed_pic[i]->poc < out->poc) {
1301                 out     = h->delayed_pic[i];
1302                 out_idx = i;
1303             }
1304
1305         for (i = out_idx; h->delayed_pic[i]; i++)
1306             h->delayed_pic[i] = h->delayed_pic[i + 1];
1307
1308         if (out) {
1309             ret = output_frame(h, pict, out->f);
1310             if (ret < 0)
1311                 return ret;
1312             *got_frame = 1;
1313         }
1314
1315         return buf_index;
1316     }
1317
1318     buf_index = decode_nal_units(h, buf, buf_size, 0);
1319     if (buf_index < 0)
1320         return AVERROR_INVALIDDATA;
1321
1322     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1323         buf_size = 0;
1324         goto out;
1325     }
1326
1327     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1328         if (avctx->skip_frame >= AVDISCARD_NONREF)
1329             return 0;
1330         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1331         return AVERROR_INVALIDDATA;
1332     }
1333
1334     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1335         (h->mb_y >= h->mb_height && h->mb_height)) {
1336         if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1337             decode_postinit(h, 1);
1338
1339         ff_h264_field_end(h, &h->slice_ctx[0], 0);
1340
1341         *got_frame = 0;
1342         if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1343                                    h->next_output_pic->recovered)) {
1344             if (!h->next_output_pic->recovered)
1345                 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1346
1347             ret = output_frame(h, pict, h->next_output_pic->f);
1348             if (ret < 0)
1349                 return ret;
1350             *got_frame = 1;
1351         }
1352     }
1353
1354     assert(pict->buf[0] || !*got_frame);
1355
1356     return get_consumed_bytes(buf_index, buf_size);
1357 }
1358
1359 av_cold void ff_h264_free_context(H264Context *h)
1360 {
1361     int i;
1362
1363     ff_h264_free_tables(h);
1364
1365     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1366         ff_h264_unref_picture(h, &h->DPB[i]);
1367         av_frame_free(&h->DPB[i].f);
1368     }
1369
1370     h->cur_pic_ptr = NULL;
1371
1372     for (i = 0; i < h->nb_slice_ctx; i++)
1373         av_freep(&h->slice_ctx[i].rbsp_buffer);
1374     av_freep(&h->slice_ctx);
1375     h->nb_slice_ctx = 0;
1376
1377     for (i = 0; i < MAX_SPS_COUNT; i++)
1378         av_freep(h->sps_buffers + i);
1379
1380     for (i = 0; i < MAX_PPS_COUNT; i++)
1381         av_freep(h->pps_buffers + i);
1382
1383     ff_h2645_packet_uninit(&h->pkt);
1384 }
1385
1386 static av_cold int h264_decode_end(AVCodecContext *avctx)
1387 {
1388     H264Context *h = avctx->priv_data;
1389
1390     ff_h264_free_context(h);
1391
1392     ff_h264_unref_picture(h, &h->cur_pic);
1393     av_frame_free(&h->cur_pic.f);
1394
1395     return 0;
1396 }
1397
1398 #define OFFSET(x) offsetof(H264Context, x)
1399 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1400 static const AVOption h264_options[] = {
1401     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1402     { NULL },
1403 };
1404
1405 static const AVClass h264_class = {
1406     .class_name = "h264",
1407     .item_name  = av_default_item_name,
1408     .option     = h264_options,
1409     .version    = LIBAVUTIL_VERSION_INT,
1410 };
1411
1412 AVCodec ff_h264_decoder = {
1413     .name                  = "h264",
1414     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1415     .type                  = AVMEDIA_TYPE_VIDEO,
1416     .id                    = AV_CODEC_ID_H264,
1417     .priv_data_size        = sizeof(H264Context),
1418     .init                  = ff_h264_decode_init,
1419     .close                 = h264_decode_end,
1420     .decode                = h264_decode_frame,
1421     .capabilities          = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1422                              AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1423                              AV_CODEC_CAP_FRAME_THREADS,
1424     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE,
1425     .flush                 = flush_dpb,
1426     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1427     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1428     .profiles              = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1429     .priv_class            = &h264_class,
1430 };