]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264dec.c
Merge commit '45d7be7f930cf707ead07416e10e2d0e061e99ce'
[ffmpeg] / libavcodec / h264dec.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... decoder
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * H.264 / AVC / MPEG-4 part10 codec.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #define UNCHECKED_BITSTREAM_READER 1
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/display.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/stereo3d.h"
35 #include "libavutil/timer.h"
36 #include "internal.h"
37 #include "bytestream.h"
38 #include "cabac.h"
39 #include "cabac_functions.h"
40 #include "error_resilience.h"
41 #include "avcodec.h"
42 #include "h264.h"
43 #include "h264dec.h"
44 #include "h2645_parse.h"
45 #include "h264data.h"
46 #include "h264chroma.h"
47 #include "h264_mvpred.h"
48 #include "h264_ps.h"
49 #include "golomb.h"
50 #include "hwaccel.h"
51 #include "mathops.h"
52 #include "me_cmp.h"
53 #include "mpegutils.h"
54 #include "mpeg4video.h"
55 #include "profiles.h"
56 #include "rectangle.h"
57 #include "thread.h"
58
59 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
60
61 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
62 {
63     H264Context *h = avctx->priv_data;
64     return h && h->ps.sps ? h->ps.sps->num_reorder_frames : 0;
65 }
66
67 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
68                               int (*mv)[2][4][2],
69                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
70 {
71     H264Context *h = opaque;
72     H264SliceContext *sl = &h->slice_ctx[0];
73
74     sl->mb_x = mb_x;
75     sl->mb_y = mb_y;
76     sl->mb_xy = mb_x + mb_y * h->mb_stride;
77     memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
78     av_assert1(ref >= 0);
79     /* FIXME: It is possible albeit uncommon that slice references
80      * differ between slices. We take the easy approach and ignore
81      * it for now. If this turns out to have any relevance in
82      * practice then correct remapping should be added. */
83     if (ref >= sl->ref_count[0])
84         ref = 0;
85     if (!sl->ref_list[0][ref].data[0]) {
86         av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
87         ref = 0;
88     }
89     if ((sl->ref_list[0][ref].reference&3) != 3) {
90         av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
91         return;
92     }
93     fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
94                    2, 2, 2, ref, 1);
95     fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
96     fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
97                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
98     sl->mb_mbaff =
99     sl->mb_field_decoding_flag = 0;
100     ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
101 }
102
103 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
104                              int y, int height)
105 {
106     AVCodecContext *avctx = h->avctx;
107     const AVFrame   *src  = h->cur_pic.f;
108     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
109     int vshift = desc->log2_chroma_h;
110     const int field_pic = h->picture_structure != PICT_FRAME;
111     if (field_pic) {
112         height <<= 1;
113         y      <<= 1;
114     }
115
116     height = FFMIN(height, avctx->height - y);
117
118     if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
119         return;
120
121     if (avctx->draw_horiz_band) {
122         int offset[AV_NUM_DATA_POINTERS];
123         int i;
124
125         offset[0] = y * src->linesize[0];
126         offset[1] =
127         offset[2] = (y >> vshift) * src->linesize[1];
128         for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
129             offset[i] = 0;
130
131         emms_c();
132
133         avctx->draw_horiz_band(avctx, src, offset,
134                                y, h->picture_structure, height);
135     }
136 }
137
138 void ff_h264_free_tables(H264Context *h)
139 {
140     int i;
141
142     av_freep(&h->intra4x4_pred_mode);
143     av_freep(&h->chroma_pred_mode_table);
144     av_freep(&h->cbp_table);
145     av_freep(&h->mvd_table[0]);
146     av_freep(&h->mvd_table[1]);
147     av_freep(&h->direct_table);
148     av_freep(&h->non_zero_count);
149     av_freep(&h->slice_table_base);
150     h->slice_table = NULL;
151     av_freep(&h->list_counts);
152
153     av_freep(&h->mb2b_xy);
154     av_freep(&h->mb2br_xy);
155
156     av_buffer_pool_uninit(&h->qscale_table_pool);
157     av_buffer_pool_uninit(&h->mb_type_pool);
158     av_buffer_pool_uninit(&h->motion_val_pool);
159     av_buffer_pool_uninit(&h->ref_index_pool);
160
161     for (i = 0; i < h->nb_slice_ctx; i++) {
162         H264SliceContext *sl = &h->slice_ctx[i];
163
164         av_freep(&sl->dc_val_base);
165         av_freep(&sl->er.mb_index2xy);
166         av_freep(&sl->er.error_status_table);
167         av_freep(&sl->er.er_temp_buffer);
168
169         av_freep(&sl->bipred_scratchpad);
170         av_freep(&sl->edge_emu_buffer);
171         av_freep(&sl->top_borders[0]);
172         av_freep(&sl->top_borders[1]);
173
174         sl->bipred_scratchpad_allocated = 0;
175         sl->edge_emu_buffer_allocated   = 0;
176         sl->top_borders_allocated[0]    = 0;
177         sl->top_borders_allocated[1]    = 0;
178     }
179 }
180
181 int ff_h264_alloc_tables(H264Context *h)
182 {
183     const int big_mb_num = h->mb_stride * (h->mb_height + 1);
184     const int row_mb_num = 2*h->mb_stride*FFMAX(h->nb_slice_ctx, 1);
185     int x, y;
186
187     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
188                       row_mb_num, 8 * sizeof(uint8_t), fail)
189     h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
190
191     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
192                       big_mb_num * 48 * sizeof(uint8_t), fail)
193     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
194                       (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
195     FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
196                       big_mb_num * sizeof(uint16_t), fail)
197     FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
198                       big_mb_num * sizeof(uint8_t), fail)
199     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
200                       row_mb_num, 16 * sizeof(uint8_t), fail);
201     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
202                       row_mb_num, 16 * sizeof(uint8_t), fail);
203     h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
204     h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
205
206     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
207                       4 * big_mb_num * sizeof(uint8_t), fail);
208     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
209                       big_mb_num * sizeof(uint8_t), fail)
210
211     memset(h->slice_table_base, -1,
212            (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
213     h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
214
215     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
216                       big_mb_num * sizeof(uint32_t), fail);
217     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
218                       big_mb_num * sizeof(uint32_t), fail);
219     for (y = 0; y < h->mb_height; y++)
220         for (x = 0; x < h->mb_width; x++) {
221             const int mb_xy = x + y * h->mb_stride;
222             const int b_xy  = 4 * x + 4 * y * h->b_stride;
223
224             h->mb2b_xy[mb_xy]  = b_xy;
225             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
226         }
227
228     return 0;
229
230 fail:
231     ff_h264_free_tables(h);
232     return AVERROR(ENOMEM);
233 }
234
235 /**
236  * Init context
237  * Allocate buffers which are not shared amongst multiple threads.
238  */
239 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
240 {
241     ERContext *er = &sl->er;
242     int mb_array_size = h->mb_height * h->mb_stride;
243     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
244     int c_size  = h->mb_stride * (h->mb_height + 1);
245     int yc_size = y_size + 2   * c_size;
246     int x, y, i;
247
248     sl->ref_cache[0][scan8[5]  + 1] =
249     sl->ref_cache[0][scan8[7]  + 1] =
250     sl->ref_cache[0][scan8[13] + 1] =
251     sl->ref_cache[1][scan8[5]  + 1] =
252     sl->ref_cache[1][scan8[7]  + 1] =
253     sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
254
255     if (sl != h->slice_ctx) {
256         memset(er, 0, sizeof(*er));
257     } else
258     if (CONFIG_ERROR_RESILIENCE) {
259
260         /* init ER */
261         er->avctx          = h->avctx;
262         er->decode_mb      = h264_er_decode_mb;
263         er->opaque         = h;
264         er->quarter_sample = 1;
265
266         er->mb_num      = h->mb_num;
267         er->mb_width    = h->mb_width;
268         er->mb_height   = h->mb_height;
269         er->mb_stride   = h->mb_stride;
270         er->b8_stride   = h->mb_width * 2 + 1;
271
272         // error resilience code looks cleaner with this
273         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
274                           (h->mb_num + 1) * sizeof(int), fail);
275
276         for (y = 0; y < h->mb_height; y++)
277             for (x = 0; x < h->mb_width; x++)
278                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
279
280         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
281                                                       h->mb_stride + h->mb_width;
282
283         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
284                           mb_array_size * sizeof(uint8_t), fail);
285
286         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
287                          h->mb_height * h->mb_stride * (4*sizeof(int) + 1), fail);
288
289         FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
290                           yc_size * sizeof(int16_t), fail);
291         er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
292         er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
293         er->dc_val[2] = er->dc_val[1] + c_size;
294         for (i = 0; i < yc_size; i++)
295             sl->dc_val_base[i] = 1024;
296     }
297
298     return 0;
299
300 fail:
301     return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
302 }
303
304 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
305 {
306     int i;
307
308     h->avctx                 = avctx;
309     h->cur_chroma_format_idc = -1;
310
311     h->width_from_caller     = avctx->width;
312     h->height_from_caller    = avctx->height;
313
314     h->picture_structure     = PICT_FRAME;
315     h->workaround_bugs       = avctx->workaround_bugs;
316     h->flags                 = avctx->flags;
317     h->poc.prev_poc_msb      = 1 << 16;
318     h->recovery_frame        = -1;
319     h->x264_build            = -1;
320     h->frame_recovered       = 0;
321     h->poc.prev_frame_num    = -1;
322     h->sei.frame_packing.frame_packing_arrangement_cancel_flag = -1;
323     h->sei.unregistered.x264_build = -1;
324
325     h->next_outputed_poc = INT_MIN;
326     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
327         h->last_pocs[i] = INT_MIN;
328
329     ff_h264_sei_uninit(&h->sei);
330
331     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
332
333     h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
334     h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
335     if (!h->slice_ctx) {
336         h->nb_slice_ctx = 0;
337         return AVERROR(ENOMEM);
338     }
339
340     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
341         h->DPB[i].f = av_frame_alloc();
342         if (!h->DPB[i].f)
343             return AVERROR(ENOMEM);
344     }
345
346     h->cur_pic.f = av_frame_alloc();
347     if (!h->cur_pic.f)
348         return AVERROR(ENOMEM);
349
350     h->last_pic_for_ec.f = av_frame_alloc();
351     if (!h->last_pic_for_ec.f)
352         return AVERROR(ENOMEM);
353
354     for (i = 0; i < h->nb_slice_ctx; i++)
355         h->slice_ctx[i].h264 = h;
356
357     return 0;
358 }
359
360 static av_cold int h264_decode_end(AVCodecContext *avctx)
361 {
362     H264Context *h = avctx->priv_data;
363     int i;
364
365     ff_h264_remove_all_refs(h);
366     ff_h264_free_tables(h);
367
368     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
369         ff_h264_unref_picture(h, &h->DPB[i]);
370         av_frame_free(&h->DPB[i].f);
371     }
372     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
373
374     h->cur_pic_ptr = NULL;
375
376     av_freep(&h->slice_ctx);
377     h->nb_slice_ctx = 0;
378
379     ff_h264_sei_uninit(&h->sei);
380     ff_h264_ps_uninit(&h->ps);
381
382     ff_h2645_packet_uninit(&h->pkt);
383
384     ff_h264_unref_picture(h, &h->cur_pic);
385     av_frame_free(&h->cur_pic.f);
386     ff_h264_unref_picture(h, &h->last_pic_for_ec);
387     av_frame_free(&h->last_pic_for_ec.f);
388
389     return 0;
390 }
391
392 static AVOnce h264_vlc_init = AV_ONCE_INIT;
393
394 static av_cold int h264_decode_init(AVCodecContext *avctx)
395 {
396     H264Context *h = avctx->priv_data;
397     int ret;
398
399     ret = h264_init_context(avctx, h);
400     if (ret < 0)
401         return ret;
402
403     ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
404     if (ret != 0) {
405         av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
406         return AVERROR_UNKNOWN;
407     }
408
409     if (avctx->ticks_per_frame == 1) {
410         if(h->avctx->time_base.den < INT_MAX/2) {
411             h->avctx->time_base.den *= 2;
412         } else
413             h->avctx->time_base.num /= 2;
414     }
415     avctx->ticks_per_frame = 2;
416
417     if (avctx->extradata_size > 0 && avctx->extradata) {
418         ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
419                                        &h->ps, &h->is_avc, &h->nal_length_size,
420                                        avctx->err_recognition, avctx);
421         if (ret < 0) {
422             h264_decode_end(avctx);
423             return ret;
424         }
425     }
426
427     if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
428         h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
429         h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
430     }
431
432     avctx->internal->allocate_progress = 1;
433
434     ff_h264_flush_change(h);
435
436     if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
437         h->enable_er = 0;
438
439     if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
440         av_log(avctx, AV_LOG_WARNING,
441                "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
442                "Use it at your own risk\n");
443     }
444
445     return 0;
446 }
447
448 #if HAVE_THREADS
449 static int decode_init_thread_copy(AVCodecContext *avctx)
450 {
451     H264Context *h = avctx->priv_data;
452     int ret;
453
454     if (!avctx->internal->is_copy)
455         return 0;
456
457     memset(h, 0, sizeof(*h));
458
459     ret = h264_init_context(avctx, h);
460     if (ret < 0)
461         return ret;
462
463     h->context_initialized = 0;
464
465     return 0;
466 }
467 #endif
468
469 /**
470  * instantaneous decoder refresh.
471  */
472 static void idr(H264Context *h)
473 {
474     int i;
475     ff_h264_remove_all_refs(h);
476     h->poc.prev_frame_num        =
477     h->poc.prev_frame_num_offset = 0;
478     h->poc.prev_poc_msb          = 1<<16;
479     h->poc.prev_poc_lsb          = 0;
480     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
481         h->last_pocs[i] = INT_MIN;
482 }
483
484 /* forget old pics after a seek */
485 void ff_h264_flush_change(H264Context *h)
486 {
487     int i, j;
488
489     h->next_outputed_poc = INT_MIN;
490     h->prev_interlaced_frame = 1;
491     idr(h);
492
493     h->poc.prev_frame_num = -1;
494     if (h->cur_pic_ptr) {
495         h->cur_pic_ptr->reference = 0;
496         for (j=i=0; h->delayed_pic[i]; i++)
497             if (h->delayed_pic[i] != h->cur_pic_ptr)
498                 h->delayed_pic[j++] = h->delayed_pic[i];
499         h->delayed_pic[j] = NULL;
500     }
501     ff_h264_unref_picture(h, &h->last_pic_for_ec);
502
503     h->first_field = 0;
504     h->recovery_frame = -1;
505     h->frame_recovered = 0;
506     h->current_slice = 0;
507     h->mmco_reset = 1;
508 }
509
510 /* forget old pics after a seek */
511 static void flush_dpb(AVCodecContext *avctx)
512 {
513     H264Context *h = avctx->priv_data;
514     int i;
515
516     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
517
518     ff_h264_flush_change(h);
519     ff_h264_sei_uninit(&h->sei);
520
521     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
522         ff_h264_unref_picture(h, &h->DPB[i]);
523     h->cur_pic_ptr = NULL;
524     ff_h264_unref_picture(h, &h->cur_pic);
525
526     h->mb_y = 0;
527
528     ff_h264_free_tables(h);
529     h->context_initialized = 0;
530 }
531
532 static int get_last_needed_nal(H264Context *h)
533 {
534     int nals_needed = 0;
535     int first_slice = 0;
536     int i, ret;
537
538     for (i = 0; i < h->pkt.nb_nals; i++) {
539         H2645NAL *nal = &h->pkt.nals[i];
540         GetBitContext gb;
541
542         /* packets can sometimes contain multiple PPS/SPS,
543          * e.g. two PAFF field pictures in one packet, or a demuxer
544          * which splits NALs strangely if so, when frame threading we
545          * can't start the next thread until we've read all of them */
546         switch (nal->type) {
547         case H264_NAL_SPS:
548         case H264_NAL_PPS:
549             nals_needed = i;
550             break;
551         case H264_NAL_DPA:
552         case H264_NAL_IDR_SLICE:
553         case H264_NAL_SLICE:
554             ret = init_get_bits8(&gb, nal->data + 1, nal->size - 1);
555             if (ret < 0) {
556                 av_log(h->avctx, AV_LOG_ERROR, "Invalid zero-sized VCL NAL unit\n");
557                 if (h->avctx->err_recognition & AV_EF_EXPLODE)
558                     return ret;
559
560                 break;
561             }
562             if (!get_ue_golomb_long(&gb) ||  // first_mb_in_slice
563                 !first_slice ||
564                 first_slice != nal->type)
565                 nals_needed = i;
566             if (!first_slice)
567                 first_slice = nal->type;
568         }
569     }
570
571     return nals_needed;
572 }
573
574 static void debug_green_metadata(const H264SEIGreenMetaData *gm, void *logctx)
575 {
576     av_log(logctx, AV_LOG_DEBUG, "Green Metadata Info SEI message\n");
577     av_log(logctx, AV_LOG_DEBUG, "  green_metadata_type: %d\n", gm->green_metadata_type);
578
579     if (gm->green_metadata_type == 0) {
580         av_log(logctx, AV_LOG_DEBUG, "  green_metadata_period_type: %d\n", gm->period_type);
581
582         if (gm->period_type == 2)
583             av_log(logctx, AV_LOG_DEBUG, "  green_metadata_num_seconds: %d\n", gm->num_seconds);
584         else if (gm->period_type == 3)
585             av_log(logctx, AV_LOG_DEBUG, "  green_metadata_num_pictures: %d\n", gm->num_pictures);
586
587         av_log(logctx, AV_LOG_DEBUG, "  SEI GREEN Complexity Metrics: %f %f %f %f\n",
588                (float)gm->percent_non_zero_macroblocks/255,
589                (float)gm->percent_intra_coded_macroblocks/255,
590                (float)gm->percent_six_tap_filtering/255,
591                (float)gm->percent_alpha_point_deblocking_instance/255);
592
593     } else if (gm->green_metadata_type == 1) {
594         av_log(logctx, AV_LOG_DEBUG, "  xsd_metric_type: %d\n", gm->xsd_metric_type);
595
596         if (gm->xsd_metric_type == 0)
597             av_log(logctx, AV_LOG_DEBUG, "  xsd_metric_value: %f\n",
598                    (float)gm->xsd_metric_value/100);
599     }
600 }
601
602 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
603 {
604     AVCodecContext *const avctx = h->avctx;
605     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
606     int idr_cleared=0;
607     int i, ret = 0;
608
609     h->has_slice = 0;
610     h->nal_unit_type= 0;
611
612     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
613         h->current_slice = 0;
614         if (!h->first_field)
615             h->cur_pic_ptr = NULL;
616         ff_h264_sei_uninit(&h->sei);
617     }
618
619     if (h->nal_length_size == 4) {
620         if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
621             h->is_avc = 0;
622         }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
623             h->is_avc = 1;
624     }
625
626     ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
627                                 h->nal_length_size, avctx->codec_id, avctx->flags2 & AV_CODEC_FLAG2_FAST);
628     if (ret < 0) {
629         av_log(avctx, AV_LOG_ERROR,
630                "Error splitting the input into NAL units.\n");
631         return ret;
632     }
633
634     if (avctx->active_thread_type & FF_THREAD_FRAME)
635         nals_needed = get_last_needed_nal(h);
636     if (nals_needed < 0)
637         return nals_needed;
638
639     for (i = 0; i < h->pkt.nb_nals; i++) {
640         H2645NAL *nal = &h->pkt.nals[i];
641         int max_slice_ctx, err;
642
643         if (avctx->skip_frame >= AVDISCARD_NONREF &&
644             nal->ref_idc == 0 && nal->type != H264_NAL_SEI)
645             continue;
646
647         // FIXME these should stop being context-global variables
648         h->nal_ref_idc   = nal->ref_idc;
649         h->nal_unit_type = nal->type;
650
651         err = 0;
652         switch (nal->type) {
653         case H264_NAL_IDR_SLICE:
654             if ((nal->data[1] & 0xFC) == 0x98) {
655                 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
656                 h->next_outputed_poc = INT_MIN;
657                 ret = -1;
658                 goto end;
659             }
660             if(!idr_cleared) {
661                 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
662                     av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
663                     ret = AVERROR_INVALIDDATA;
664                     goto end;
665                 }
666                 idr(h); // FIXME ensure we don't lose some frames if there is reordering
667             }
668             idr_cleared = 1;
669             h->has_recovery_point = 1;
670         case H264_NAL_SLICE:
671             h->has_slice = 1;
672
673             if ((err = ff_h264_queue_decode_slice(h, nal))) {
674                 H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
675                 sl->ref_count[0] = sl->ref_count[1] = 0;
676                 break;
677             }
678
679             if (h->current_slice == 1) {
680                 if (avctx->active_thread_type & FF_THREAD_FRAME &&
681                     i >= nals_needed && !h->setup_finished && h->cur_pic_ptr) {
682                     ff_thread_finish_setup(avctx);
683                     h->setup_finished = 1;
684                 }
685
686                 if (h->avctx->hwaccel &&
687                     (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
688                     goto end;
689             }
690
691             max_slice_ctx = avctx->hwaccel ? 1 : h->nb_slice_ctx;
692             if (h->nb_slice_ctx_queued == max_slice_ctx) {
693                 if (h->avctx->hwaccel) {
694                     ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
695                     h->nb_slice_ctx_queued = 0;
696                 } else
697                     ret = ff_h264_execute_decode_slices(h);
698                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
699                     goto end;
700             }
701             break;
702         case H264_NAL_DPA:
703         case H264_NAL_DPB:
704         case H264_NAL_DPC:
705             avpriv_request_sample(avctx, "data partitioning");
706             break;
707         case H264_NAL_SEI:
708             ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
709             h->has_recovery_point = h->has_recovery_point || h->sei.recovery_point.recovery_frame_cnt != -1;
710             if (avctx->debug & FF_DEBUG_GREEN_MD)
711                 debug_green_metadata(&h->sei.green_metadata, h->avctx);
712             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
713                 goto end;
714             break;
715         case H264_NAL_SPS: {
716             GetBitContext tmp_gb = nal->gb;
717             if (avctx->hwaccel && avctx->hwaccel->decode_params) {
718                 ret = avctx->hwaccel->decode_params(avctx,
719                                                     nal->type,
720                                                     nal->raw_data,
721                                                     nal->raw_size);
722                 if (ret < 0)
723                     goto end;
724             }
725             if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
726                 break;
727             av_log(h->avctx, AV_LOG_DEBUG,
728                    "SPS decoding failure, trying again with the complete NAL\n");
729             init_get_bits8(&tmp_gb, nal->raw_data + 1, nal->raw_size - 1);
730             if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
731                 break;
732             ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps, 1);
733             break;
734         }
735         case H264_NAL_PPS:
736             if (avctx->hwaccel && avctx->hwaccel->decode_params) {
737                 ret = avctx->hwaccel->decode_params(avctx,
738                                                     nal->type,
739                                                     nal->raw_data,
740                                                     nal->raw_size);
741                 if (ret < 0)
742                     goto end;
743             }
744             ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
745                                                        nal->size_bits);
746             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
747                 goto end;
748             break;
749         case H264_NAL_AUD:
750         case H264_NAL_END_SEQUENCE:
751         case H264_NAL_END_STREAM:
752         case H264_NAL_FILLER_DATA:
753         case H264_NAL_SPS_EXT:
754         case H264_NAL_AUXILIARY_SLICE:
755             break;
756         default:
757             av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
758                    nal->type, nal->size_bits);
759         }
760
761         if (err < 0) {
762             av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
763         }
764     }
765
766     ret = ff_h264_execute_decode_slices(h);
767     if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
768         goto end;
769
770     ret = 0;
771 end:
772
773 #if CONFIG_ERROR_RESILIENCE
774     /*
775      * FIXME: Error handling code does not seem to support interlaced
776      * when slices span multiple rows
777      * The ff_er_add_slice calls don't work right for bottom
778      * fields; they cause massive erroneous error concealing
779      * Error marking covers both fields (top and bottom).
780      * This causes a mismatched s->error_count
781      * and a bad error table. Further, the error count goes to
782      * INT_MAX when called for bottom field, because mb_y is
783      * past end by one (callers fault) and resync_mb_y != 0
784      * causes problems for the first MB line, too.
785      */
786     if (!FIELD_PICTURE(h) && h->current_slice &&
787         h->ps.sps == (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data &&
788         h->enable_er) {
789
790         H264SliceContext *sl = h->slice_ctx;
791         int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
792
793         ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
794
795         if (use_last_pic) {
796             ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
797             sl->ref_list[0][0].parent = &h->last_pic_for_ec;
798             memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
799             memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
800             sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
801         } else if (sl->ref_count[0]) {
802             ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
803         } else
804             ff_h264_set_erpic(&sl->er.last_pic, NULL);
805
806         if (sl->ref_count[1])
807             ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
808
809         sl->er.ref_count = sl->ref_count[0];
810
811         ff_er_frame_end(&sl->er);
812         if (use_last_pic)
813             memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
814     }
815 #endif /* CONFIG_ERROR_RESILIENCE */
816     /* clean up */
817     if (h->cur_pic_ptr && !h->droppable && h->has_slice) {
818         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
819                                   h->picture_structure == PICT_BOTTOM_FIELD);
820     }
821
822     return (ret < 0) ? ret : buf_size;
823 }
824
825 /**
826  * Return the number of bytes consumed for building the current frame.
827  */
828 static int get_consumed_bytes(int pos, int buf_size)
829 {
830     if (pos == 0)
831         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
832     if (pos + 10 > buf_size)
833         pos = buf_size; // oops ;)
834
835     return pos;
836 }
837
838 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
839 {
840     AVFrame *src = srcp->f;
841     int ret;
842
843     if (src->format == AV_PIX_FMT_VIDEOTOOLBOX && src->buf[0]->size == 1)
844         return AVERROR_INVALIDDATA;
845
846     ret = av_frame_ref(dst, src);
847     if (ret < 0)
848         return ret;
849
850     av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(&h->sei.frame_packing), 0);
851
852     if (srcp->sei_recovery_frame_cnt == 0)
853         dst->key_frame = 1;
854
855     return 0;
856 }
857
858 static int is_extra(const uint8_t *buf, int buf_size)
859 {
860     int cnt= buf[5]&0x1f;
861     const uint8_t *p= buf+6;
862     while(cnt--){
863         int nalsize= AV_RB16(p) + 2;
864         if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
865             return 0;
866         p += nalsize;
867     }
868     cnt = *(p++);
869     if(!cnt)
870         return 0;
871     while(cnt--){
872         int nalsize= AV_RB16(p) + 2;
873         if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
874             return 0;
875         p += nalsize;
876     }
877     return 1;
878 }
879
880 static int finalize_frame(H264Context *h, AVFrame *dst, H264Picture *out, int *got_frame)
881 {
882     int ret;
883
884     if (((h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
885          (h->avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
886          out->recovered)) {
887
888         if (!h->avctx->hwaccel &&
889             (out->field_poc[0] == INT_MAX ||
890              out->field_poc[1] == INT_MAX)
891            ) {
892             int p;
893             AVFrame *f = out->f;
894             int field = out->field_poc[0] == INT_MAX;
895             uint8_t *dst_data[4];
896             int linesizes[4];
897             const uint8_t *src_data[4];
898
899             av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
900
901             for (p = 0; p<4; p++) {
902                 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
903                 src_data[p] = f->data[p] +  field   *f->linesize[p];
904                 linesizes[p] = 2*f->linesize[p];
905             }
906
907             av_image_copy(dst_data, linesizes, src_data, linesizes,
908                           f->format, f->width, f->height>>1);
909         }
910
911         ret = output_frame(h, dst, out);
912         if (ret < 0)
913             return ret;
914
915         *got_frame = 1;
916
917         if (CONFIG_MPEGVIDEO) {
918             ff_print_debug_info2(h->avctx, dst, NULL,
919                                  out->mb_type,
920                                  out->qscale_table,
921                                  out->motion_val,
922                                  NULL,
923                                  h->mb_width, h->mb_height, h->mb_stride, 1);
924         }
925     }
926
927     return 0;
928 }
929
930 static int send_next_delayed_frame(H264Context *h, AVFrame *dst_frame,
931                                    int *got_frame, int buf_index)
932 {
933     int ret, i, out_idx;
934     H264Picture *out = h->delayed_pic[0];
935
936     h->cur_pic_ptr = NULL;
937     h->first_field = 0;
938
939     out_idx = 0;
940     for (i = 1;
941          h->delayed_pic[i] &&
942          !h->delayed_pic[i]->f->key_frame &&
943          !h->delayed_pic[i]->mmco_reset;
944          i++)
945         if (h->delayed_pic[i]->poc < out->poc) {
946             out     = h->delayed_pic[i];
947             out_idx = i;
948         }
949
950     for (i = out_idx; h->delayed_pic[i]; i++)
951         h->delayed_pic[i] = h->delayed_pic[i + 1];
952
953     if (out) {
954         out->reference &= ~DELAYED_PIC_REF;
955         ret = finalize_frame(h, dst_frame, out, got_frame);
956         if (ret < 0)
957             return ret;
958     }
959
960     return buf_index;
961 }
962
963 static int h264_decode_frame(AVCodecContext *avctx, void *data,
964                              int *got_frame, AVPacket *avpkt)
965 {
966     const uint8_t *buf = avpkt->data;
967     int buf_size       = avpkt->size;
968     H264Context *h     = avctx->priv_data;
969     AVFrame *pict      = data;
970     int buf_index;
971     int ret;
972
973     h->flags = avctx->flags;
974     h->setup_finished = 0;
975     h->nb_slice_ctx_queued = 0;
976
977     ff_h264_unref_picture(h, &h->last_pic_for_ec);
978
979     /* end of stream, output what is still in the buffers */
980     if (buf_size == 0)
981         return send_next_delayed_frame(h, pict, got_frame, 0);
982
983     if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
984         int side_size;
985         uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
986         if (is_extra(side, side_size))
987             ff_h264_decode_extradata(side, side_size,
988                                      &h->ps, &h->is_avc, &h->nal_length_size,
989                                      avctx->err_recognition, avctx);
990     }
991     if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
992         if (is_extra(buf, buf_size))
993             return ff_h264_decode_extradata(buf, buf_size,
994                                             &h->ps, &h->is_avc, &h->nal_length_size,
995                                             avctx->err_recognition, avctx);
996     }
997
998     buf_index = decode_nal_units(h, buf, buf_size);
999     if (buf_index < 0)
1000         return AVERROR_INVALIDDATA;
1001
1002     if (!h->cur_pic_ptr && h->nal_unit_type == H264_NAL_END_SEQUENCE) {
1003         av_assert0(buf_index <= buf_size);
1004         return send_next_delayed_frame(h, pict, got_frame, buf_index);
1005     }
1006
1007     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && (!h->cur_pic_ptr || !h->has_slice)) {
1008         if (avctx->skip_frame >= AVDISCARD_NONREF ||
1009             buf_size >= 4 && !memcmp("Q264", buf, 4))
1010             return buf_size;
1011         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1012         return AVERROR_INVALIDDATA;
1013     }
1014
1015     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1016         (h->mb_y >= h->mb_height && h->mb_height)) {
1017         if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1018             return ret;
1019
1020         /* Wait for second field. */
1021         if (h->next_output_pic) {
1022             ret = finalize_frame(h, pict, h->next_output_pic, got_frame);
1023             if (ret < 0)
1024                 return ret;
1025         }
1026     }
1027
1028     av_assert0(pict->buf[0] || !*got_frame);
1029
1030     ff_h264_unref_picture(h, &h->last_pic_for_ec);
1031
1032     return get_consumed_bytes(buf_index, buf_size);
1033 }
1034
1035 #define OFFSET(x) offsetof(H264Context, x)
1036 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1037 static const AVOption h264_options[] = {
1038     { "is_avc", "is avc", OFFSET(is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0 },
1039     { "nal_length_size", "nal_length_size", OFFSET(nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0 },
1040     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
1041     { NULL },
1042 };
1043
1044 static const AVClass h264_class = {
1045     .class_name = "H264 Decoder",
1046     .item_name  = av_default_item_name,
1047     .option     = h264_options,
1048     .version    = LIBAVUTIL_VERSION_INT,
1049 };
1050
1051 AVCodec ff_h264_decoder = {
1052     .name                  = "h264",
1053     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1054     .type                  = AVMEDIA_TYPE_VIDEO,
1055     .id                    = AV_CODEC_ID_H264,
1056     .priv_data_size        = sizeof(H264Context),
1057     .init                  = h264_decode_init,
1058     .close                 = h264_decode_end,
1059     .decode                = h264_decode_frame,
1060     .capabilities          = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1061                              AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1062                              AV_CODEC_CAP_FRAME_THREADS,
1063     .hw_configs            = (const AVCodecHWConfigInternal*[]) {
1064 #if CONFIG_H264_DXVA2_HWACCEL
1065                                HWACCEL_DXVA2(h264),
1066 #endif
1067 #if CONFIG_H264_D3D11VA_HWACCEL
1068                                HWACCEL_D3D11VA(h264),
1069 #endif
1070 #if CONFIG_H264_D3D11VA2_HWACCEL
1071                                HWACCEL_D3D11VA2(h264),
1072 #endif
1073 #if CONFIG_H264_NVDEC_HWACCEL
1074                                HWACCEL_NVDEC(h264),
1075 #endif
1076 #if CONFIG_H264_VAAPI_HWACCEL
1077                                HWACCEL_VAAPI(h264),
1078 #endif
1079 #if CONFIG_H264_VDPAU_HWACCEL
1080                                HWACCEL_VDPAU(h264),
1081 #endif
1082 #if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
1083                                HWACCEL_VIDEOTOOLBOX(h264),
1084 #endif
1085                                NULL
1086                            },
1087     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_EXPORTS_CROPPING,
1088     .flush                 = flush_dpb,
1089     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1090     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1091     .profiles              = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1092     .priv_class            = &h264_class,
1093 };