]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264dec.c
lavc: Drop deprecated global afd field
[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 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 "golomb_legacy.h"
40 #include "h264.h"
41 #include "h264dec.h"
42 #include "h2645_parse.h"
43 #include "h264data.h"
44 #include "h264chroma.h"
45 #include "h264_mvpred.h"
46 #include "h264_ps.h"
47 #include "mathops.h"
48 #include "me_cmp.h"
49 #include "mpegutils.h"
50 #include "profiles.h"
51 #include "rectangle.h"
52 #include "thread.h"
53
54 #include <assert.h>
55
56 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
57
58 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
59                               int (*mv)[2][4][2],
60                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
61 {
62     H264Context *h = opaque;
63     H264SliceContext *sl = &h->slice_ctx[0];
64
65     sl->mb_x = mb_x;
66     sl->mb_y = mb_y;
67     sl->mb_xy = mb_x + mb_y * h->mb_stride;
68     memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
69     assert(ref >= 0);
70     /* FIXME: It is possible albeit uncommon that slice references
71      * differ between slices. We take the easy approach and ignore
72      * it for now. If this turns out to have any relevance in
73      * practice then correct remapping should be added. */
74     if (ref >= sl->ref_count[0])
75         ref = 0;
76     fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
77                    2, 2, 2, ref, 1);
78     fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
79     fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
80                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
81     assert(!FRAME_MBAFF(h));
82     ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
83 }
84
85 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
86                              int y, int height)
87 {
88     AVCodecContext *avctx = h->avctx;
89     const AVFrame   *src  = h->cur_pic.f;
90     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
91     int vshift = desc->log2_chroma_h;
92     const int field_pic = h->picture_structure != PICT_FRAME;
93     if (field_pic) {
94         height <<= 1;
95         y      <<= 1;
96     }
97
98     height = FFMIN(height, avctx->height - y);
99
100     if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
101         return;
102
103     if (avctx->draw_horiz_band) {
104         int offset[AV_NUM_DATA_POINTERS];
105         int i;
106
107         offset[0] = y * src->linesize[0];
108         offset[1] =
109         offset[2] = (y >> vshift) * src->linesize[1];
110         for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
111             offset[i] = 0;
112
113         emms_c();
114
115         avctx->draw_horiz_band(avctx, src, offset,
116                                y, h->picture_structure, height);
117     }
118 }
119
120 void ff_h264_free_tables(H264Context *h)
121 {
122     int i;
123
124     av_freep(&h->intra4x4_pred_mode);
125     av_freep(&h->chroma_pred_mode_table);
126     av_freep(&h->cbp_table);
127     av_freep(&h->mvd_table[0]);
128     av_freep(&h->mvd_table[1]);
129     av_freep(&h->direct_table);
130     av_freep(&h->non_zero_count);
131     av_freep(&h->slice_table_base);
132     h->slice_table = NULL;
133     av_freep(&h->list_counts);
134
135     av_freep(&h->mb2b_xy);
136     av_freep(&h->mb2br_xy);
137
138     av_buffer_pool_uninit(&h->qscale_table_pool);
139     av_buffer_pool_uninit(&h->mb_type_pool);
140     av_buffer_pool_uninit(&h->motion_val_pool);
141     av_buffer_pool_uninit(&h->ref_index_pool);
142
143     for (i = 0; i < h->nb_slice_ctx; i++) {
144         H264SliceContext *sl = &h->slice_ctx[i];
145
146         av_freep(&sl->dc_val_base);
147         av_freep(&sl->er.mb_index2xy);
148         av_freep(&sl->er.error_status_table);
149         av_freep(&sl->er.er_temp_buffer);
150
151         av_freep(&sl->bipred_scratchpad);
152         av_freep(&sl->edge_emu_buffer);
153         av_freep(&sl->top_borders[0]);
154         av_freep(&sl->top_borders[1]);
155
156         sl->bipred_scratchpad_allocated = 0;
157         sl->edge_emu_buffer_allocated   = 0;
158         sl->top_borders_allocated[0]    = 0;
159         sl->top_borders_allocated[1]    = 0;
160     }
161 }
162
163 int ff_h264_alloc_tables(H264Context *h)
164 {
165     const int big_mb_num = h->mb_stride * (h->mb_height + 1);
166     const int row_mb_num = h->mb_stride * 2 * h->nb_slice_ctx;
167     int x, y;
168
169     FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
170                       row_mb_num * 8 * sizeof(uint8_t), fail)
171     h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
172
173     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
174                       big_mb_num * 48 * sizeof(uint8_t), fail)
175     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
176                       (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
177     FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
178                       big_mb_num * sizeof(uint16_t), fail)
179     FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
180                       big_mb_num * sizeof(uint8_t), fail)
181     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
182                       16 * row_mb_num * sizeof(uint8_t), fail);
183     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
184                       16 * row_mb_num * sizeof(uint8_t), fail);
185     h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
186     h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
187
188     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
189                       4 * big_mb_num * sizeof(uint8_t), fail);
190     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
191                       big_mb_num * sizeof(uint8_t), fail)
192
193     memset(h->slice_table_base, -1,
194            (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
195     h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
196
197     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
198                       big_mb_num * sizeof(uint32_t), fail);
199     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
200                       big_mb_num * sizeof(uint32_t), fail);
201     for (y = 0; y < h->mb_height; y++)
202         for (x = 0; x < h->mb_width; x++) {
203             const int mb_xy = x + y * h->mb_stride;
204             const int b_xy  = 4 * x + 4 * y * h->b_stride;
205
206             h->mb2b_xy[mb_xy]  = b_xy;
207             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
208         }
209
210     return 0;
211
212 fail:
213     ff_h264_free_tables(h);
214     return AVERROR(ENOMEM);
215 }
216
217 /**
218  * Init context
219  * Allocate buffers which are not shared amongst multiple threads.
220  */
221 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
222 {
223     ERContext *er = &sl->er;
224     int mb_array_size = h->mb_height * h->mb_stride;
225     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
226     int c_size  = h->mb_stride * (h->mb_height + 1);
227     int yc_size = y_size + 2   * c_size;
228     int x, y, i;
229
230     sl->ref_cache[0][scan8[5]  + 1] =
231     sl->ref_cache[0][scan8[7]  + 1] =
232     sl->ref_cache[0][scan8[13] + 1] =
233     sl->ref_cache[1][scan8[5]  + 1] =
234     sl->ref_cache[1][scan8[7]  + 1] =
235     sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
236
237     if (CONFIG_ERROR_RESILIENCE) {
238         /* init ER */
239         er->avctx          = h->avctx;
240         er->decode_mb      = h264_er_decode_mb;
241         er->opaque         = h;
242         er->quarter_sample = 1;
243
244         er->mb_num      = h->mb_num;
245         er->mb_width    = h->mb_width;
246         er->mb_height   = h->mb_height;
247         er->mb_stride   = h->mb_stride;
248         er->b8_stride   = h->mb_width * 2 + 1;
249
250         // error resilience code looks cleaner with this
251         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
252                           (h->mb_num + 1) * sizeof(int), fail);
253
254         for (y = 0; y < h->mb_height; y++)
255             for (x = 0; x < h->mb_width; x++)
256                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
257
258         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
259                                                       h->mb_stride + h->mb_width;
260
261         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
262                           mb_array_size * sizeof(uint8_t), fail);
263
264         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
265                          h->mb_height * h->mb_stride, fail);
266
267         FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
268                           yc_size * sizeof(int16_t), fail);
269         er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
270         er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
271         er->dc_val[2] = er->dc_val[1] + c_size;
272         for (i = 0; i < yc_size; i++)
273             sl->dc_val_base[i] = 1024;
274     }
275
276     return 0;
277
278 fail:
279     return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
280 }
281
282 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
283 {
284     int i;
285
286     h->avctx                 = avctx;
287
288     h->width_from_caller     = avctx->width;
289     h->height_from_caller    = avctx->height;
290
291     h->picture_structure     = PICT_FRAME;
292     h->workaround_bugs       = avctx->workaround_bugs;
293     h->flags                 = avctx->flags;
294     h->poc.prev_poc_msb      = 1 << 16;
295     h->recovery_frame        = -1;
296     h->frame_recovered       = 0;
297
298     h->next_outputed_poc = INT_MIN;
299     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
300         h->last_pocs[i] = INT_MIN;
301
302     ff_h264_sei_uninit(&h->sei);
303
304     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
305
306     h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
307     h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
308     if (!h->slice_ctx) {
309         h->nb_slice_ctx = 0;
310         return AVERROR(ENOMEM);
311     }
312
313     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
314         h->DPB[i].f = av_frame_alloc();
315         if (!h->DPB[i].f)
316             return AVERROR(ENOMEM);
317     }
318
319     h->cur_pic.f = av_frame_alloc();
320     if (!h->cur_pic.f)
321         return AVERROR(ENOMEM);
322
323     h->output_frame = av_frame_alloc();
324     if (!h->output_frame)
325         return AVERROR(ENOMEM);
326
327     for (i = 0; i < h->nb_slice_ctx; i++)
328         h->slice_ctx[i].h264 = h;
329
330     return 0;
331 }
332
333 static av_cold int h264_decode_end(AVCodecContext *avctx)
334 {
335     H264Context *h = avctx->priv_data;
336     int i;
337
338     ff_h264_free_tables(h);
339
340     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
341         ff_h264_unref_picture(h, &h->DPB[i]);
342         av_frame_free(&h->DPB[i].f);
343     }
344
345     h->cur_pic_ptr = NULL;
346
347     av_freep(&h->slice_ctx);
348     h->nb_slice_ctx = 0;
349
350     for (i = 0; i < MAX_SPS_COUNT; i++)
351         av_buffer_unref(&h->ps.sps_list[i]);
352
353     for (i = 0; i < MAX_PPS_COUNT; i++)
354         av_buffer_unref(&h->ps.pps_list[i]);
355
356     ff_h2645_packet_uninit(&h->pkt);
357
358     ff_h264_unref_picture(h, &h->cur_pic);
359     av_frame_free(&h->cur_pic.f);
360     av_frame_free(&h->output_frame);
361
362     return 0;
363 }
364
365 static AVOnce h264_vlc_init = AV_ONCE_INIT;
366
367 static av_cold int h264_decode_init(AVCodecContext *avctx)
368 {
369     H264Context *h = avctx->priv_data;
370     int ret;
371
372     ret = h264_init_context(avctx, h);
373     if (ret < 0)
374         return ret;
375
376     ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
377     if (ret != 0) {
378         av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
379         return AVERROR_UNKNOWN;
380     }
381
382     if (avctx->ticks_per_frame == 1)
383         h->avctx->framerate.num *= 2;
384     avctx->ticks_per_frame = 2;
385
386     if (avctx->extradata_size > 0 && avctx->extradata) {
387        ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
388                                       &h->ps, &h->is_avc, &h->nal_length_size,
389                                       avctx->err_recognition, avctx);
390        if (ret < 0) {
391            h264_decode_end(avctx);
392            return ret;
393        }
394     }
395
396     if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
397         h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
398         h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
399     }
400
401     avctx->internal->allocate_progress = 1;
402
403     if (h->enable_er) {
404         av_log(avctx, AV_LOG_WARNING,
405                "Error resilience is enabled. It is unsafe and unsupported and may crash. "
406                "Use it at your own risk\n");
407     }
408
409     return 0;
410 }
411
412 static int decode_init_thread_copy(AVCodecContext *avctx)
413 {
414     H264Context *h = avctx->priv_data;
415     int ret;
416
417     if (!avctx->internal->is_copy)
418         return 0;
419
420     memset(h, 0, sizeof(*h));
421
422     ret = h264_init_context(avctx, h);
423     if (ret < 0)
424         return ret;
425
426     h->context_initialized = 0;
427
428     return 0;
429 }
430
431 /**
432  * instantaneous decoder refresh.
433  */
434 static void idr(H264Context *h)
435 {
436     ff_h264_remove_all_refs(h);
437     h->poc.prev_frame_num        =
438     h->poc.prev_frame_num_offset =
439     h->poc.prev_poc_msb          =
440     h->poc.prev_poc_lsb          = 0;
441 }
442
443 /* forget old pics after a seek */
444 void ff_h264_flush_change(H264Context *h)
445 {
446     int i;
447     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
448         h->last_pocs[i] = INT_MIN;
449     h->next_outputed_poc = INT_MIN;
450     h->prev_interlaced_frame = 1;
451     idr(h);
452     if (h->cur_pic_ptr)
453         h->cur_pic_ptr->reference = 0;
454     h->first_field = 0;
455     h->recovery_frame = -1;
456     h->frame_recovered = 0;
457 }
458
459 /* forget old pics after a seek */
460 static void flush_dpb(AVCodecContext *avctx)
461 {
462     H264Context *h = avctx->priv_data;
463     int i;
464
465     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
466
467     ff_h264_flush_change(h);
468     ff_h264_sei_uninit(&h->sei);
469
470     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
471         ff_h264_unref_picture(h, &h->DPB[i]);
472     h->cur_pic_ptr = NULL;
473     ff_h264_unref_picture(h, &h->cur_pic);
474
475     h->mb_y = 0;
476
477     ff_h264_free_tables(h);
478     h->context_initialized = 0;
479 }
480
481 static int get_last_needed_nal(H264Context *h)
482 {
483     int nals_needed = 0;
484     int i, ret;
485
486     for (i = 0; i < h->pkt.nb_nals; i++) {
487         H2645NAL *nal = &h->pkt.nals[i];
488         GetBitContext gb;
489
490         /* packets can sometimes contain multiple PPS/SPS,
491          * e.g. two PAFF field pictures in one packet, or a demuxer
492          * which splits NALs strangely if so, when frame threading we
493          * can't start the next thread until we've read all of them */
494         switch (nal->type) {
495         case H264_NAL_SPS:
496         case H264_NAL_PPS:
497             nals_needed = i;
498             break;
499         case H264_NAL_DPA:
500         case H264_NAL_IDR_SLICE:
501         case H264_NAL_SLICE:
502             ret = init_get_bits8(&gb, nal->data + 1, nal->size - 1);
503             if (ret < 0) {
504                 av_log(h->avctx, AV_LOG_ERROR, "Invalid zero-sized VCL NAL unit\n");
505                 if (h->avctx->err_recognition & AV_EF_EXPLODE)
506                     return ret;
507
508                 break;
509             }
510             if (!get_ue_golomb(&gb))
511                 nals_needed = i;
512         }
513     }
514
515     return nals_needed;
516 }
517
518 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
519 {
520     AVCodecContext *const avctx = h->avctx;
521     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
522     int i, ret = 0;
523
524     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
525         h->current_slice = 0;
526         h->field_started = 0;
527         if (!h->first_field)
528             h->cur_pic_ptr = NULL;
529         ff_h264_sei_uninit(&h->sei);
530     }
531
532     ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
533                                 h->nal_length_size, avctx->codec_id);
534     if (ret < 0) {
535         av_log(avctx, AV_LOG_ERROR,
536                "Error splitting the input into NAL units.\n");
537
538         /* There are samples in the wild with mp4-style extradata, but Annex B
539          * data in the packets. If we fail parsing the packet as mp4, try it again
540          * as Annex B. */
541         if (h->is_avc && !(avctx->err_recognition & AV_EF_EXPLODE)) {
542             int err = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, 0, 0,
543                                             avctx->codec_id);
544             if (err >= 0) {
545                 av_log(avctx, AV_LOG_WARNING,
546                        "The stream seems to contain AVCC extradata with Annex B "
547                        "formatted data, which is invalid.");
548                 h->is_avc = 0;
549                 ret       = 0;
550             }
551         }
552
553         if (ret < 0)
554             return ret;
555     }
556
557     if (avctx->active_thread_type & FF_THREAD_FRAME)
558         nals_needed = get_last_needed_nal(h);
559
560     for (i = 0; i < h->pkt.nb_nals; i++) {
561         H2645NAL *nal = &h->pkt.nals[i];
562         int max_slice_ctx, err;
563
564         if (avctx->skip_frame >= AVDISCARD_NONREF &&
565             nal->ref_idc == 0 && nal->type != H264_NAL_SEI)
566             continue;
567
568         // FIXME these should stop being context-global variables
569         h->nal_ref_idc   = nal->ref_idc;
570         h->nal_unit_type = nal->type;
571
572         err = 0;
573         switch (nal->type) {
574         case H264_NAL_IDR_SLICE:
575             idr(h); // FIXME ensure we don't lose some frames if there is reordering
576         case H264_NAL_SLICE:
577             if ((err = ff_h264_queue_decode_slice(h, nal)))
578                 break;
579
580             if (avctx->active_thread_type & FF_THREAD_FRAME &&
581                 i >= nals_needed && !h->setup_finished && h->cur_pic_ptr) {
582                 ff_thread_finish_setup(avctx);
583                 h->setup_finished = 1;
584             }
585
586             max_slice_ctx = avctx->hwaccel ? 1 : h->nb_slice_ctx;
587             if (h->nb_slice_ctx_queued == max_slice_ctx) {
588                 if (avctx->hwaccel) {
589                     ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
590                     h->nb_slice_ctx_queued = 0;
591                 } else
592                     ret = ff_h264_execute_decode_slices(h);
593                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
594                     goto end;
595             }
596             break;
597         case H264_NAL_DPA:
598         case H264_NAL_DPB:
599         case H264_NAL_DPC:
600             avpriv_request_sample(avctx, "data partitioning");
601             ret = AVERROR(ENOSYS);
602             goto end;
603             break;
604         case H264_NAL_SEI:
605             ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
606             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
607                 goto end;
608             break;
609         case H264_NAL_SPS:
610             ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
611             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
612                 goto end;
613             break;
614         case H264_NAL_PPS:
615             ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
616                                                        nal->size_bits);
617             if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
618                 goto end;
619             break;
620         case H264_NAL_AUD:
621         case H264_NAL_END_SEQUENCE:
622         case H264_NAL_END_STREAM:
623         case H264_NAL_FILLER_DATA:
624         case H264_NAL_SPS_EXT:
625         case H264_NAL_AUXILIARY_SLICE:
626             break;
627         default:
628             av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
629                    nal->type, nal->size_bits);
630         }
631
632         if (err < 0) {
633             av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
634         }
635     }
636
637     ret = ff_h264_execute_decode_slices(h);
638     if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
639         goto end;
640
641     ret = 0;
642 end:
643     /* clean up */
644     if (h->cur_pic_ptr && !h->droppable) {
645         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
646                                   h->picture_structure == PICT_BOTTOM_FIELD);
647     }
648
649     return (ret < 0) ? ret : buf_size;
650 }
651
652 /**
653  * Return the number of bytes consumed for building the current frame.
654  */
655 static int get_consumed_bytes(int pos, int buf_size)
656 {
657     if (pos == 0)
658         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
659     if (pos + 10 > buf_size)
660         pos = buf_size; // oops ;)
661
662     return pos;
663 }
664
665 static int h264_decode_frame(AVCodecContext *avctx, void *data,
666                              int *got_frame, AVPacket *avpkt)
667 {
668     const uint8_t *buf = avpkt->data;
669     int buf_size       = avpkt->size;
670     H264Context *h     = avctx->priv_data;
671     AVFrame *pict      = data;
672     int buf_index      = 0;
673     int ret;
674     const uint8_t *new_extradata;
675     int new_extradata_size;
676
677     h->flags = avctx->flags;
678     h->setup_finished = 0;
679     h->nb_slice_ctx_queued = 0;
680
681     /* end of stream, output what is still in the buffers */
682 out:
683     if (buf_size == 0) {
684         H264Picture *out;
685         int i, out_idx;
686
687         h->cur_pic_ptr = NULL;
688
689         // FIXME factorize this with the output code below
690         out     = h->delayed_pic[0];
691         out_idx = 0;
692         for (i = 1;
693              h->delayed_pic[i] &&
694              !h->delayed_pic[i]->f->key_frame &&
695              !h->delayed_pic[i]->mmco_reset;
696              i++)
697             if (h->delayed_pic[i]->poc < out->poc) {
698                 out     = h->delayed_pic[i];
699                 out_idx = i;
700             }
701
702         for (i = out_idx; h->delayed_pic[i]; i++)
703             h->delayed_pic[i] = h->delayed_pic[i + 1];
704
705         if (out) {
706             ret = av_frame_ref(pict, out->f);
707             if (ret < 0)
708                 return ret;
709             *got_frame = 1;
710         }
711
712         return buf_index;
713     }
714
715     new_extradata_size = 0;
716     new_extradata = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
717                                             &new_extradata_size);
718     if (new_extradata_size > 0 && new_extradata) {
719         ret = ff_h264_decode_extradata(new_extradata, new_extradata_size,
720                                        &h->ps, &h->is_avc, &h->nal_length_size,
721                                        avctx->err_recognition, avctx);
722         if (ret < 0)
723             return ret;
724     }
725
726     buf_index = decode_nal_units(h, buf, buf_size);
727     if (buf_index < 0)
728         return AVERROR_INVALIDDATA;
729
730     if (!h->cur_pic_ptr && h->nal_unit_type == H264_NAL_END_SEQUENCE) {
731         buf_size = 0;
732         goto out;
733     }
734
735     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
736         if (avctx->skip_frame >= AVDISCARD_NONREF)
737             return 0;
738         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
739         return AVERROR_INVALIDDATA;
740     }
741
742     if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
743         (h->mb_y >= h->mb_height && h->mb_height)) {
744         if (h->field_started)
745             ff_h264_field_end(h, &h->slice_ctx[0], 0);
746
747         *got_frame = 0;
748         if (h->output_frame->buf[0]) {
749             ret = av_frame_ref(pict, h->output_frame);
750             av_frame_unref(h->output_frame);
751             if (ret < 0)
752                 return ret;
753             *got_frame = 1;
754         }
755     }
756
757     assert(pict->buf[0] || !*got_frame);
758
759     return get_consumed_bytes(buf_index, buf_size);
760 }
761
762 #define OFFSET(x) offsetof(H264Context, x)
763 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
764 static const AVOption h264_options[] = {
765     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
766     { NULL },
767 };
768
769 static const AVClass h264_class = {
770     .class_name = "h264",
771     .item_name  = av_default_item_name,
772     .option     = h264_options,
773     .version    = LIBAVUTIL_VERSION_INT,
774 };
775
776 AVCodec ff_h264_decoder = {
777     .name                  = "h264",
778     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
779     .type                  = AVMEDIA_TYPE_VIDEO,
780     .id                    = AV_CODEC_ID_H264,
781     .priv_data_size        = sizeof(H264Context),
782     .init                  = h264_decode_init,
783     .close                 = h264_decode_end,
784     .decode                = h264_decode_frame,
785     .capabilities          = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
786                              AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
787                              AV_CODEC_CAP_FRAME_THREADS,
788     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_EXPORTS_CROPPING,
789     .flush                 = flush_dpb,
790     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
791     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
792     .profiles              = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
793     .priv_class            = &h264_class,
794 };