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