]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
h264: decouple extradata parsing from the decoder
[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     return 0;
210
211 fail:
212     ff_h264_free_tables(h);
213     return AVERROR(ENOMEM);
214 }
215
216 /**
217  * Init context
218  * Allocate buffers which are not shared amongst multiple threads.
219  */
220 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
221 {
222     ERContext *er = &sl->er;
223     int mb_array_size = h->mb_height * h->mb_stride;
224     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
225     int c_size  = h->mb_stride * (h->mb_height + 1);
226     int yc_size = y_size + 2   * c_size;
227     int x, y, i;
228
229     sl->ref_cache[0][scan8[5]  + 1] =
230     sl->ref_cache[0][scan8[7]  + 1] =
231     sl->ref_cache[0][scan8[13] + 1] =
232     sl->ref_cache[1][scan8[5]  + 1] =
233     sl->ref_cache[1][scan8[7]  + 1] =
234     sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
235
236     if (CONFIG_ERROR_RESILIENCE) {
237         /* init ER */
238         er->avctx          = h->avctx;
239         er->decode_mb      = h264_er_decode_mb;
240         er->opaque         = h;
241         er->quarter_sample = 1;
242
243         er->mb_num      = h->mb_num;
244         er->mb_width    = h->mb_width;
245         er->mb_height   = h->mb_height;
246         er->mb_stride   = h->mb_stride;
247         er->b8_stride   = h->mb_width * 2 + 1;
248
249         // error resilience code looks cleaner with this
250         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
251                           (h->mb_num + 1) * sizeof(int), fail);
252
253         for (y = 0; y < h->mb_height; y++)
254             for (x = 0; x < h->mb_width; x++)
255                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
256
257         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
258                                                       h->mb_stride + h->mb_width;
259
260         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
261                           mb_array_size * sizeof(uint8_t), fail);
262
263         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
264                          h->mb_height * h->mb_stride, fail);
265
266         FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
267                           yc_size * sizeof(int16_t), fail);
268         er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
269         er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
270         er->dc_val[2] = er->dc_val[1] + c_size;
271         for (i = 0; i < yc_size; i++)
272             sl->dc_val_base[i] = 1024;
273     }
274
275     return 0;
276
277 fail:
278     return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
279 }
280
281 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
282 {
283     int i;
284
285     h->avctx                 = avctx;
286
287     h->picture_structure     = PICT_FRAME;
288     h->slice_context_count   = 1;
289     h->workaround_bugs       = avctx->workaround_bugs;
290     h->flags                 = avctx->flags;
291     h->poc.prev_poc_msb      = 1 << 16;
292     h->recovery_frame        = -1;
293     h->frame_recovered       = 0;
294
295     h->next_outputed_poc = INT_MIN;
296     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
297         h->last_pocs[i] = INT_MIN;
298
299     ff_h264_sei_uninit(&h->sei);
300
301     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
302
303     h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;
304     h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
305     if (!h->slice_ctx) {
306         h->nb_slice_ctx = 0;
307         return AVERROR(ENOMEM);
308     }
309
310     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
311         h->DPB[i].f = av_frame_alloc();
312         if (!h->DPB[i].f)
313             return AVERROR(ENOMEM);
314     }
315
316     h->cur_pic.f = av_frame_alloc();
317     if (!h->cur_pic.f)
318         return AVERROR(ENOMEM);
319
320     for (i = 0; i < h->nb_slice_ctx; i++)
321         h->slice_ctx[i].h264 = h;
322
323     return 0;
324 }
325
326 static AVOnce h264_vlc_init = AV_ONCE_INIT;
327
328 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
329 {
330     H264Context *h = avctx->priv_data;
331     int ret;
332
333     ret = h264_init_context(avctx, h);
334     if (ret < 0)
335         return ret;
336
337     /* set defaults */
338     if (!avctx->has_b_frames)
339         h->low_delay = 1;
340
341     ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
342     if (ret != 0) {
343         av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
344         return AVERROR_UNKNOWN;
345     }
346
347     if (avctx->codec_id == AV_CODEC_ID_H264) {
348         if (avctx->ticks_per_frame == 1)
349             h->avctx->framerate.num *= 2;
350         avctx->ticks_per_frame = 2;
351     }
352
353     if (avctx->extradata_size > 0 && avctx->extradata) {
354        ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
355                                       &h->ps, &h->is_avc, &h->nal_length_size,
356                                       avctx->err_recognition, avctx);
357        if (ret < 0) {
358            ff_h264_free_context(h);
359            return ret;
360        }
361     }
362
363     if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
364         h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
365         h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
366         h->low_delay           = 0;
367     }
368
369     avctx->internal->allocate_progress = 1;
370
371     if (h->enable_er) {
372         av_log(avctx, AV_LOG_WARNING,
373                "Error resilience is enabled. It is unsafe and unsupported and may crash. "
374                "Use it at your own risk\n");
375     }
376
377     return 0;
378 }
379
380 static int decode_init_thread_copy(AVCodecContext *avctx)
381 {
382     H264Context *h = avctx->priv_data;
383     int ret;
384
385     if (!avctx->internal->is_copy)
386         return 0;
387
388     memset(h, 0, sizeof(*h));
389
390     ret = h264_init_context(avctx, h);
391     if (ret < 0)
392         return ret;
393
394     h->context_initialized = 0;
395
396     return 0;
397 }
398
399 /**
400  * Run setup operations that must be run after slice header decoding.
401  * This includes finding the next displayed frame.
402  *
403  * @param h h264 master context
404  * @param setup_finished enough NALs have been read that we can call
405  * ff_thread_finish_setup()
406  */
407 static void decode_postinit(H264Context *h, int setup_finished)
408 {
409     const SPS *sps = h->ps.sps;
410     H264Picture *out = h->cur_pic_ptr;
411     H264Picture *cur = h->cur_pic_ptr;
412     int i, pics, out_of_order, out_idx;
413     int invalid = 0, cnt = 0;
414
415     h->cur_pic_ptr->f->pict_type = h->pict_type;
416
417     if (h->next_output_pic)
418         return;
419
420     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
421         /* FIXME: if we have two PAFF fields in one packet, we can't start
422          * the next thread here. If we have one field per packet, we can.
423          * The check in decode_nal_units() is not good enough to find this
424          * yet, so we assume the worst for now. */
425         // if (setup_finished)
426         //    ff_thread_finish_setup(h->avctx);
427         return;
428     }
429
430     cur->f->interlaced_frame = 0;
431     cur->f->repeat_pict      = 0;
432
433     /* Signal interlacing information externally. */
434     /* Prioritize picture timing SEI information over used
435      * decoding process if it exists. */
436
437     if (sps->pic_struct_present_flag) {
438         H264SEIPictureTiming *pt = &h->sei.picture_timing;
439         switch (pt->pic_struct) {
440         case SEI_PIC_STRUCT_FRAME:
441             break;
442         case SEI_PIC_STRUCT_TOP_FIELD:
443         case SEI_PIC_STRUCT_BOTTOM_FIELD:
444             cur->f->interlaced_frame = 1;
445             break;
446         case SEI_PIC_STRUCT_TOP_BOTTOM:
447         case SEI_PIC_STRUCT_BOTTOM_TOP:
448             if (FIELD_OR_MBAFF_PICTURE(h))
449                 cur->f->interlaced_frame = 1;
450             else
451                 // try to flag soft telecine progressive
452                 cur->f->interlaced_frame = h->prev_interlaced_frame;
453             break;
454         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
455         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
456             /* Signal the possibility of telecined film externally
457              * (pic_struct 5,6). From these hints, let the applications
458              * decide if they apply deinterlacing. */
459             cur->f->repeat_pict = 1;
460             break;
461         case SEI_PIC_STRUCT_FRAME_DOUBLING:
462             cur->f->repeat_pict = 2;
463             break;
464         case SEI_PIC_STRUCT_FRAME_TRIPLING:
465             cur->f->repeat_pict = 4;
466             break;
467         }
468
469         if ((pt->ct_type & 3) &&
470             pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
471             cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
472     } else {
473         /* Derive interlacing flag from used decoding process. */
474         cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
475     }
476     h->prev_interlaced_frame = cur->f->interlaced_frame;
477
478     if (cur->field_poc[0] != cur->field_poc[1]) {
479         /* Derive top_field_first from field pocs. */
480         cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
481     } else {
482         if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
483             /* Use picture timing SEI information. Even if it is a
484              * information of a past frame, better than nothing. */
485             if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
486                 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
487                 cur->f->top_field_first = 1;
488             else
489                 cur->f->top_field_first = 0;
490         } else {
491             /* Most likely progressive */
492             cur->f->top_field_first = 0;
493         }
494     }
495
496     if (h->sei.frame_packing.present &&
497         h->sei.frame_packing.arrangement_type >= 0 &&
498         h->sei.frame_packing.arrangement_type <= 6 &&
499         h->sei.frame_packing.content_interpretation_type > 0 &&
500         h->sei.frame_packing.content_interpretation_type < 3) {
501         H264SEIFramePacking *fp = &h->sei.frame_packing;
502         AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
503         if (!stereo)
504             return;
505
506         switch (fp->arrangement_type) {
507         case 0:
508             stereo->type = AV_STEREO3D_CHECKERBOARD;
509             break;
510         case 1:
511             stereo->type = AV_STEREO3D_COLUMNS;
512             break;
513         case 2:
514             stereo->type = AV_STEREO3D_LINES;
515             break;
516         case 3:
517             if (fp->quincunx_subsampling)
518                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
519             else
520                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
521             break;
522         case 4:
523             stereo->type = AV_STEREO3D_TOPBOTTOM;
524             break;
525         case 5:
526             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
527             break;
528         case 6:
529             stereo->type = AV_STEREO3D_2D;
530             break;
531         }
532
533         if (fp->content_interpretation_type == 2)
534             stereo->flags = AV_STEREO3D_FLAG_INVERT;
535     }
536
537     if (h->sei.display_orientation.present &&
538         (h->sei.display_orientation.anticlockwise_rotation ||
539          h->sei.display_orientation.hflip ||
540          h->sei.display_orientation.vflip)) {
541         H264SEIDisplayOrientation *o = &h->sei.display_orientation;
542         double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
543         AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
544                                                            AV_FRAME_DATA_DISPLAYMATRIX,
545                                                            sizeof(int32_t) * 9);
546         if (!rotation)
547             return;
548
549         av_display_rotation_set((int32_t *)rotation->data, angle);
550         av_display_matrix_flip((int32_t *)rotation->data,
551                                o->hflip, o->vflip);
552     }
553
554     if (h->sei.afd.present) {
555         AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
556                                                      sizeof(uint8_t));
557         if (!sd)
558             return;
559
560         *sd->data = h->sei.afd.active_format_description;
561         h->sei.afd.present = 0;
562     }
563
564     if (h->sei.a53_caption.a53_caption) {
565         H264SEIA53Caption *a53 = &h->sei.a53_caption;
566         AVFrameSideData *sd = av_frame_new_side_data(cur->f,
567                                                      AV_FRAME_DATA_A53_CC,
568                                                      a53->a53_caption_size);
569         if (!sd)
570             return;
571
572         memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
573         av_freep(&a53->a53_caption);
574         a53->a53_caption_size = 0;
575     }
576
577     // FIXME do something with unavailable reference frames
578
579     /* Sort B-frames into display order */
580     if (sps->bitstream_restriction_flag ||
581         h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
582         h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
583     }
584     h->low_delay = !h->avctx->has_b_frames;
585
586     pics = 0;
587     while (h->delayed_pic[pics])
588         pics++;
589
590     assert(pics <= MAX_DELAYED_PIC_COUNT);
591
592     h->delayed_pic[pics++] = cur;
593     if (cur->reference == 0)
594         cur->reference = DELAYED_PIC_REF;
595
596     /* Frame reordering. This code takes pictures from coding order and sorts
597      * them by their incremental POC value into display order. It supports POC
598      * gaps, MMCO reset codes and random resets.
599      * A "display group" can start either with a IDR frame (f.key_frame = 1),
600      * and/or can be closed down with a MMCO reset code. In sequences where
601      * there is no delay, we can't detect that (since the frame was already
602      * output to the user), so we also set h->mmco_reset to detect the MMCO
603      * reset code.
604      * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
605      * we increase the delay between input and output. All frames affected by
606      * the lag (e.g. those that should have been output before another frame
607      * that we already returned to the user) will be dropped. This is a bug
608      * that we will fix later. */
609     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
610         cnt     += out->poc < h->last_pocs[i];
611         invalid += out->poc == INT_MIN;
612     }
613     if (!h->mmco_reset && !cur->f->key_frame &&
614         cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
615         h->mmco_reset = 2;
616         if (pics > 1)
617             h->delayed_pic[pics - 2]->mmco_reset = 2;
618     }
619     if (h->mmco_reset || cur->f->key_frame) {
620         for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
621             h->last_pocs[i] = INT_MIN;
622         cnt     = 0;
623         invalid = MAX_DELAYED_PIC_COUNT;
624     }
625     out     = h->delayed_pic[0];
626     out_idx = 0;
627     for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
628                 h->delayed_pic[i] &&
629                 !h->delayed_pic[i - 1]->mmco_reset &&
630                 !h->delayed_pic[i]->f->key_frame;
631          i++)
632         if (h->delayed_pic[i]->poc < out->poc) {
633             out     = h->delayed_pic[i];
634             out_idx = i;
635         }
636     if (h->avctx->has_b_frames == 0 &&
637         (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
638         h->next_outputed_poc = INT_MIN;
639     out_of_order = !out->f->key_frame && !h->mmco_reset &&
640                    (out->poc < h->next_outputed_poc);
641
642     if (sps->bitstream_restriction_flag &&
643         h->avctx->has_b_frames >= sps->num_reorder_frames) {
644     } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
645                h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
646         if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
647             h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
648         }
649         h->low_delay = 0;
650     } else if (h->low_delay &&
651                ((h->next_outputed_poc != INT_MIN &&
652                  out->poc > h->next_outputed_poc + 2) ||
653                 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
654         h->low_delay = 0;
655         h->avctx->has_b_frames++;
656     }
657
658     if (pics > h->avctx->has_b_frames) {
659         out->reference &= ~DELAYED_PIC_REF;
660         // for frame threading, the owner must be the second field's thread or
661         // else the first thread can release the picture and reuse it unsafely
662         for (i = out_idx; h->delayed_pic[i]; i++)
663             h->delayed_pic[i] = h->delayed_pic[i + 1];
664     }
665     memmove(h->last_pocs, &h->last_pocs[1],
666             sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
667     h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
668     if (!out_of_order && pics > h->avctx->has_b_frames) {
669         h->next_output_pic = out;
670         if (out->mmco_reset) {
671             if (out_idx > 0) {
672                 h->next_outputed_poc                    = out->poc;
673                 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
674             } else {
675                 h->next_outputed_poc = INT_MIN;
676             }
677         } else {
678             if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
679                 h->next_outputed_poc = INT_MIN;
680             } else {
681                 h->next_outputed_poc = out->poc;
682             }
683         }
684         h->mmco_reset = 0;
685     } else {
686         av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
687     }
688
689     if (h->next_output_pic) {
690         if (h->next_output_pic->recovered) {
691             // We have reached an recovery point and all frames after it in
692             // display order are "recovered".
693             h->frame_recovered |= FRAME_RECOVERED_SEI;
694         }
695         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
696     }
697
698     if (setup_finished && !h->avctx->hwaccel) {
699         ff_thread_finish_setup(h->avctx);
700
701         if (h->avctx->active_thread_type & FF_THREAD_FRAME)
702             h->setup_finished = 1;
703     }
704 }
705
706 /**
707  * instantaneous decoder refresh.
708  */
709 static void idr(H264Context *h)
710 {
711     ff_h264_remove_all_refs(h);
712     h->poc.prev_frame_num        =
713     h->poc.prev_frame_num_offset =
714     h->poc.prev_poc_msb          =
715     h->poc.prev_poc_lsb          = 0;
716 }
717
718 /* forget old pics after a seek */
719 void ff_h264_flush_change(H264Context *h)
720 {
721     int i;
722     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
723         h->last_pocs[i] = INT_MIN;
724     h->next_outputed_poc = INT_MIN;
725     h->prev_interlaced_frame = 1;
726     idr(h);
727     if (h->cur_pic_ptr)
728         h->cur_pic_ptr->reference = 0;
729     h->first_field = 0;
730     ff_h264_sei_uninit(&h->sei);
731     h->recovery_frame = -1;
732     h->frame_recovered = 0;
733 }
734
735 /* forget old pics after a seek */
736 static void flush_dpb(AVCodecContext *avctx)
737 {
738     H264Context *h = avctx->priv_data;
739     int i;
740
741     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
742
743     ff_h264_flush_change(h);
744
745     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
746         ff_h264_unref_picture(h, &h->DPB[i]);
747     h->cur_pic_ptr = NULL;
748     ff_h264_unref_picture(h, &h->cur_pic);
749
750     h->mb_y = 0;
751
752     ff_h264_free_tables(h);
753     h->context_initialized = 0;
754 }
755
756 /**
757  * Compute profile from profile_idc and constraint_set?_flags.
758  *
759  * @param sps SPS
760  *
761  * @return profile as defined by FF_PROFILE_H264_*
762  */
763 int ff_h264_get_profile(const SPS *sps)
764 {
765     int profile = sps->profile_idc;
766
767     switch (sps->profile_idc) {
768     case FF_PROFILE_H264_BASELINE:
769         // constraint_set1_flag set to 1
770         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
771         break;
772     case FF_PROFILE_H264_HIGH_10:
773     case FF_PROFILE_H264_HIGH_422:
774     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
775         // constraint_set3_flag set to 1
776         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
777         break;
778     }
779
780     return profile;
781 }
782
783 static int get_last_needed_nal(H264Context *h)
784 {
785     int nals_needed = 0;
786     int i;
787
788     for (i = 0; i < h->pkt.nb_nals; i++) {
789         H2645NAL *nal = &h->pkt.nals[i];
790         GetBitContext gb;
791
792         /* packets can sometimes contain multiple PPS/SPS,
793          * e.g. two PAFF field pictures in one packet, or a demuxer
794          * which splits NALs strangely if so, when frame threading we
795          * can't start the next thread until we've read all of them */
796         switch (nal->type) {
797         case NAL_SPS:
798         case NAL_PPS:
799             nals_needed = i;
800             break;
801         case NAL_DPA:
802         case NAL_IDR_SLICE:
803         case NAL_SLICE:
804             init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
805             if (!get_ue_golomb(&gb))
806                 nals_needed = i;
807         }
808     }
809
810     return nals_needed;
811 }
812
813 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
814 {
815     AVCodecContext *const avctx = h->avctx;
816     unsigned context_count = 0;
817     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
818     int i, ret = 0;
819
820     h->max_contexts = h->slice_context_count;
821     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
822         h->current_slice = 0;
823         if (!h->first_field)
824             h->cur_pic_ptr = NULL;
825         ff_h264_sei_uninit(&h->sei);
826     }
827
828     ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
829                                 h->nal_length_size, avctx->codec_id);
830     if (ret < 0) {
831         av_log(avctx, AV_LOG_ERROR,
832                "Error splitting the input into NAL units.\n");
833         return ret;
834     }
835
836     if (avctx->active_thread_type & FF_THREAD_FRAME)
837         nals_needed = get_last_needed_nal(h);
838
839     for (i = 0; i < h->pkt.nb_nals; i++) {
840         H2645NAL *nal = &h->pkt.nals[i];
841         H264SliceContext *sl = &h->slice_ctx[context_count];
842         int err;
843
844         if (avctx->skip_frame >= AVDISCARD_NONREF &&
845             nal->ref_idc == 0 && nal->type != NAL_SEI)
846             continue;
847
848 again:
849         // FIXME these should stop being context-global variables
850         h->nal_ref_idc   = nal->ref_idc;
851         h->nal_unit_type = nal->type;
852
853         err = 0;
854         switch (nal->type) {
855         case NAL_IDR_SLICE:
856             if (nal->type != NAL_IDR_SLICE) {
857                 av_log(h->avctx, AV_LOG_ERROR,
858                        "Invalid mix of idr and non-idr slices\n");
859                 ret = -1;
860                 goto end;
861             }
862             idr(h); // FIXME ensure we don't lose some frames if there is reordering
863         case NAL_SLICE:
864             sl->gb = nal->gb;
865
866             if ((err = ff_h264_decode_slice_header(h, sl)))
867                 break;
868
869             if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
870                 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
871                                     ((1 << h->ps.sps->log2_max_frame_num) - 1);
872             }
873
874             h->cur_pic_ptr->f->key_frame |=
875                 (nal->type == NAL_IDR_SLICE) || (h->sei.recovery_point.recovery_frame_cnt >= 0);
876
877             if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
878                 h->recovery_frame         = -1;
879                 h->cur_pic_ptr->recovered = 1;
880             }
881             // If we have an IDR, all frames after it in decoded order are
882             // "recovered".
883             if (nal->type == NAL_IDR_SLICE)
884                 h->frame_recovered |= FRAME_RECOVERED_IDR;
885             h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
886
887             if (h->current_slice == 1) {
888                 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
889                     decode_postinit(h, i >= nals_needed);
890
891                 if (h->avctx->hwaccel &&
892                     (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
893                     return ret;
894             }
895
896             if (sl->redundant_pic_count == 0 &&
897                 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
898                 (avctx->skip_frame < AVDISCARD_BIDIR  ||
899                  sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
900                 (avctx->skip_frame < AVDISCARD_NONKEY ||
901                  h->cur_pic_ptr->f->key_frame) &&
902                 avctx->skip_frame < AVDISCARD_ALL) {
903                 if (avctx->hwaccel) {
904                     ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
905                     if (ret < 0)
906                         return ret;
907                 } else
908                     context_count++;
909             }
910             break;
911         case NAL_DPA:
912         case NAL_DPB:
913         case NAL_DPC:
914             avpriv_request_sample(avctx, "data partitioning");
915             ret = AVERROR(ENOSYS);
916             goto end;
917             break;
918         case NAL_SEI:
919             ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
920             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
921                 goto end;
922             break;
923         case NAL_SPS:
924             ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
925             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
926                 goto end;
927             break;
928         case NAL_PPS:
929             ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
930                                                        nal->size_bits);
931             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
932                 goto end;
933             break;
934         case NAL_AUD:
935         case NAL_END_SEQUENCE:
936         case NAL_END_STREAM:
937         case NAL_FILLER_DATA:
938         case NAL_SPS_EXT:
939         case NAL_AUXILIARY_SLICE:
940             break;
941         case NAL_FF_IGNORE:
942             break;
943         default:
944             av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
945                    nal->type, nal->size_bits);
946         }
947
948         if (context_count == h->max_contexts) {
949             ret = ff_h264_execute_decode_slices(h, context_count);
950             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
951                 goto end;
952             context_count = 0;
953         }
954
955         if (err < 0) {
956             av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
957             sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
958         } else if (err == 1) {
959             /* Slice could not be decoded in parallel mode, restart. Note
960              * that rbsp_buffer is not transferred, but since we no longer
961              * run in parallel mode this should not be an issue. */
962             sl               = &h->slice_ctx[0];
963             goto again;
964         }
965     }
966     if (context_count) {
967         ret = ff_h264_execute_decode_slices(h, context_count);
968         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
969             goto end;
970     }
971
972     ret = 0;
973 end:
974     /* clean up */
975     if (h->cur_pic_ptr && !h->droppable) {
976         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
977                                   h->picture_structure == PICT_BOTTOM_FIELD);
978     }
979
980     return (ret < 0) ? ret : buf_size;
981 }
982
983 /**
984  * Return the number of bytes consumed for building the current frame.
985  */
986 static int get_consumed_bytes(int pos, int buf_size)
987 {
988     if (pos == 0)
989         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
990     if (pos + 10 > buf_size)
991         pos = buf_size; // oops ;)
992
993     return pos;
994 }
995
996 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
997 {
998     int i;
999     int ret = av_frame_ref(dst, src);
1000     if (ret < 0)
1001         return ret;
1002
1003     if (!h->ps.sps || !h->ps.sps->crop)
1004         return 0;
1005
1006     for (i = 0; i < 3; i++) {
1007         int hshift = (i > 0) ? h->chroma_x_shift : 0;
1008         int vshift = (i > 0) ? h->chroma_y_shift : 0;
1009         int off    = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
1010                      (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
1011         dst->data[i] += off;
1012     }
1013     return 0;
1014 }
1015
1016 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1017                              int *got_frame, AVPacket *avpkt)
1018 {
1019     const uint8_t *buf = avpkt->data;
1020     int buf_size       = avpkt->size;
1021     H264Context *h     = avctx->priv_data;
1022     AVFrame *pict      = data;
1023     int buf_index      = 0;
1024     int ret;
1025
1026     h->flags = avctx->flags;
1027     h->setup_finished = 0;
1028
1029     /* end of stream, output what is still in the buffers */
1030 out:
1031     if (buf_size == 0) {
1032         H264Picture *out;
1033         int i, out_idx;
1034
1035         h->cur_pic_ptr = NULL;
1036
1037         // FIXME factorize this with the output code below
1038         out     = h->delayed_pic[0];
1039         out_idx = 0;
1040         for (i = 1;
1041              h->delayed_pic[i] &&
1042              !h->delayed_pic[i]->f->key_frame &&
1043              !h->delayed_pic[i]->mmco_reset;
1044              i++)
1045             if (h->delayed_pic[i]->poc < out->poc) {
1046                 out     = h->delayed_pic[i];
1047                 out_idx = i;
1048             }
1049
1050         for (i = out_idx; h->delayed_pic[i]; i++)
1051             h->delayed_pic[i] = h->delayed_pic[i + 1];
1052
1053         if (out) {
1054             ret = output_frame(h, pict, out->f);
1055             if (ret < 0)
1056                 return ret;
1057             *got_frame = 1;
1058         }
1059
1060         return buf_index;
1061     }
1062
1063     buf_index = decode_nal_units(h, buf, buf_size);
1064     if (buf_index < 0)
1065         return AVERROR_INVALIDDATA;
1066
1067     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1068         buf_size = 0;
1069         goto out;
1070     }
1071
1072     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1073         if (avctx->skip_frame >= AVDISCARD_NONREF)
1074             return 0;
1075         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1076         return AVERROR_INVALIDDATA;
1077     }
1078
1079     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1080         (h->mb_y >= h->mb_height && h->mb_height)) {
1081         if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1082             decode_postinit(h, 1);
1083
1084         ff_h264_field_end(h, &h->slice_ctx[0], 0);
1085
1086         *got_frame = 0;
1087         if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1088                                    h->next_output_pic->recovered)) {
1089             if (!h->next_output_pic->recovered)
1090                 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1091
1092             ret = output_frame(h, pict, h->next_output_pic->f);
1093             if (ret < 0)
1094                 return ret;
1095             *got_frame = 1;
1096         }
1097     }
1098
1099     assert(pict->buf[0] || !*got_frame);
1100
1101     return get_consumed_bytes(buf_index, buf_size);
1102 }
1103
1104 av_cold void ff_h264_free_context(H264Context *h)
1105 {
1106     int i;
1107
1108     ff_h264_free_tables(h);
1109
1110     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1111         ff_h264_unref_picture(h, &h->DPB[i]);
1112         av_frame_free(&h->DPB[i].f);
1113     }
1114
1115     h->cur_pic_ptr = NULL;
1116
1117     for (i = 0; i < h->nb_slice_ctx; i++)
1118         av_freep(&h->slice_ctx[i].rbsp_buffer);
1119     av_freep(&h->slice_ctx);
1120     h->nb_slice_ctx = 0;
1121
1122     for (i = 0; i < MAX_SPS_COUNT; i++)
1123         av_buffer_unref(&h->ps.sps_list[i]);
1124
1125     for (i = 0; i < MAX_PPS_COUNT; i++)
1126         av_buffer_unref(&h->ps.pps_list[i]);
1127
1128     ff_h2645_packet_uninit(&h->pkt);
1129 }
1130
1131 static av_cold int h264_decode_end(AVCodecContext *avctx)
1132 {
1133     H264Context *h = avctx->priv_data;
1134
1135     ff_h264_free_context(h);
1136
1137     ff_h264_unref_picture(h, &h->cur_pic);
1138     av_frame_free(&h->cur_pic.f);
1139
1140     return 0;
1141 }
1142
1143 #define OFFSET(x) offsetof(H264Context, x)
1144 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1145 static const AVOption h264_options[] = {
1146     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1147     { NULL },
1148 };
1149
1150 static const AVClass h264_class = {
1151     .class_name = "h264",
1152     .item_name  = av_default_item_name,
1153     .option     = h264_options,
1154     .version    = LIBAVUTIL_VERSION_INT,
1155 };
1156
1157 AVCodec ff_h264_decoder = {
1158     .name                  = "h264",
1159     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1160     .type                  = AVMEDIA_TYPE_VIDEO,
1161     .id                    = AV_CODEC_ID_H264,
1162     .priv_data_size        = sizeof(H264Context),
1163     .init                  = ff_h264_decode_init,
1164     .close                 = h264_decode_end,
1165     .decode                = h264_decode_frame,
1166     .capabilities          = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1167                              AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1168                              AV_CODEC_CAP_FRAME_THREADS,
1169     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE,
1170     .flush                 = flush_dpb,
1171     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1172     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1173     .profiles              = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1174     .priv_class            = &h264_class,
1175 };