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