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