]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264.c
h264: Add support for Closed Caption export
[ffmpeg] / libavcodec / h264.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... decoder
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * H.264 / AVC / MPEG4 part10 codec.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/stereo3d.h"
33 #include "libavutil/timer.h"
34 #include "internal.h"
35 #include "cabac.h"
36 #include "cabac_functions.h"
37 #include "error_resilience.h"
38 #include "avcodec.h"
39 #include "h264.h"
40 #include "h264data.h"
41 #include "h264chroma.h"
42 #include "h264_mvpred.h"
43 #include "golomb.h"
44 #include "mathops.h"
45 #include "me_cmp.h"
46 #include "mpegutils.h"
47 #include "rectangle.h"
48 #include "svq3.h"
49 #include "thread.h"
50
51 #include <assert.h>
52
53 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
54
55 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
56                               int (*mv)[2][4][2],
57                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
58 {
59     H264Context *h = opaque;
60     H264SliceContext *sl = &h->slice_ctx[0];
61
62     sl->mb_x = mb_x;
63     sl->mb_y = mb_y;
64     sl->mb_xy = mb_x + mb_y * h->mb_stride;
65     memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
66     assert(ref >= 0);
67     /* FIXME: It is possible albeit uncommon that slice references
68      * differ between slices. We take the easy approach and ignore
69      * it for now. If this turns out to have any relevance in
70      * practice then correct remapping should be added. */
71     if (ref >= sl->ref_count[0])
72         ref = 0;
73     fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
74                    2, 2, 2, ref, 1);
75     fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
76     fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
77                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
78     assert(!FRAME_MBAFF(h));
79     ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
80 }
81
82 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
83                              int y, int height)
84 {
85     AVCodecContext *avctx = h->avctx;
86     const AVFrame   *src  = h->cur_pic.f;
87     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
88     int vshift = desc->log2_chroma_h;
89     const int field_pic = h->picture_structure != PICT_FRAME;
90     if (field_pic) {
91         height <<= 1;
92         y      <<= 1;
93     }
94
95     height = FFMIN(height, avctx->height - y);
96
97     if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
98         return;
99
100     if (avctx->draw_horiz_band) {
101         int offset[AV_NUM_DATA_POINTERS];
102         int i;
103
104         offset[0] = y * src->linesize[0];
105         offset[1] =
106         offset[2] = (y >> vshift) * src->linesize[1];
107         for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
108             offset[i] = 0;
109
110         emms_c();
111
112         avctx->draw_horiz_band(avctx, src, offset,
113                                y, h->picture_structure, height);
114     }
115 }
116
117 /**
118  * Check if the top & left blocks are available if needed and
119  * change the dc mode so it only uses the available blocks.
120  */
121 int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
122 {
123     static const int8_t top[12] = {
124         -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
125     };
126     static const int8_t left[12] = {
127         0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
128     };
129     int i;
130
131     if (!(sl->top_samples_available & 0x8000)) {
132         for (i = 0; i < 4; i++) {
133             int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
134             if (status < 0) {
135                 av_log(h->avctx, AV_LOG_ERROR,
136                        "top block unavailable for requested intra4x4 mode %d at %d %d\n",
137                        status, sl->mb_x, sl->mb_y);
138                 return AVERROR_INVALIDDATA;
139             } else if (status) {
140                 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
141             }
142         }
143     }
144
145     if ((sl->left_samples_available & 0x8888) != 0x8888) {
146         static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
147         for (i = 0; i < 4; i++)
148             if (!(sl->left_samples_available & mask[i])) {
149                 int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
150                 if (status < 0) {
151                     av_log(h->avctx, AV_LOG_ERROR,
152                            "left block unavailable for requested intra4x4 mode %d at %d %d\n",
153                            status, sl->mb_x, sl->mb_y);
154                     return AVERROR_INVALIDDATA;
155                 } else if (status) {
156                     sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
157                 }
158             }
159     }
160
161     return 0;
162 } // FIXME cleanup like ff_h264_check_intra_pred_mode
163
164 /**
165  * Check if the top & left blocks are available if needed and
166  * change the dc mode so it only uses the available blocks.
167  */
168 int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
169                                   int mode, int is_chroma)
170 {
171     static const int8_t top[4]  = { LEFT_DC_PRED8x8, 1, -1, -1 };
172     static const int8_t left[5] = { TOP_DC_PRED8x8, -1,  2, -1, DC_128_PRED8x8 };
173
174     if (mode > 3U) {
175         av_log(h->avctx, AV_LOG_ERROR,
176                "out of range intra chroma pred mode at %d %d\n",
177                sl->mb_x, sl->mb_y);
178         return AVERROR_INVALIDDATA;
179     }
180
181     if (!(sl->top_samples_available & 0x8000)) {
182         mode = top[mode];
183         if (mode < 0) {
184             av_log(h->avctx, AV_LOG_ERROR,
185                    "top block unavailable for requested intra mode at %d %d\n",
186                    sl->mb_x, sl->mb_y);
187             return AVERROR_INVALIDDATA;
188         }
189     }
190
191     if ((sl->left_samples_available & 0x8080) != 0x8080) {
192         mode = left[mode];
193         if (is_chroma && (sl->left_samples_available & 0x8080)) {
194             // mad cow disease mode, aka MBAFF + constrained_intra_pred
195             mode = ALZHEIMER_DC_L0T_PRED8x8 +
196                    (!(sl->left_samples_available & 0x8000)) +
197                    2 * (mode == DC_128_PRED8x8);
198         }
199         if (mode < 0) {
200             av_log(h->avctx, AV_LOG_ERROR,
201                    "left block unavailable for requested intra mode at %d %d\n",
202                    sl->mb_x, sl->mb_y);
203             return AVERROR_INVALIDDATA;
204         }
205     }
206
207     return mode;
208 }
209
210 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
211                                   const uint8_t *src,
212                                   int *dst_length, int *consumed, int length)
213 {
214     int i, si, di;
215     uint8_t *dst;
216
217     // src[0]&0x80; // forbidden bit
218     h->nal_ref_idc   = src[0] >> 5;
219     h->nal_unit_type = src[0] & 0x1F;
220
221     src++;
222     length--;
223
224 #define STARTCODE_TEST                                                  \
225     if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {         \
226         if (src[i + 2] != 3) {                                          \
227             /* startcode, so we must be past the end */                 \
228             length = i;                                                 \
229         }                                                               \
230         break;                                                          \
231     }
232
233 #if HAVE_FAST_UNALIGNED
234 #define FIND_FIRST_ZERO                                                 \
235     if (i > 0 && !src[i])                                               \
236         i--;                                                            \
237     while (src[i])                                                      \
238         i++
239
240 #if HAVE_FAST_64BIT
241     for (i = 0; i + 1 < length; i += 9) {
242         if (!((~AV_RN64A(src + i) &
243                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
244               0x8000800080008080ULL))
245             continue;
246         FIND_FIRST_ZERO;
247         STARTCODE_TEST;
248         i -= 7;
249     }
250 #else
251     for (i = 0; i + 1 < length; i += 5) {
252         if (!((~AV_RN32A(src + i) &
253                (AV_RN32A(src + i) - 0x01000101U)) &
254               0x80008080U))
255             continue;
256         FIND_FIRST_ZERO;
257         STARTCODE_TEST;
258         i -= 3;
259     }
260 #endif
261 #else
262     for (i = 0; i + 1 < length; i += 2) {
263         if (src[i])
264             continue;
265         if (i > 0 && src[i - 1] == 0)
266             i--;
267         STARTCODE_TEST;
268     }
269 #endif
270
271     if (i >= length - 1) { // no escaped 0
272         *dst_length = length;
273         *consumed   = length + 1; // +1 for the header
274         return src;
275     }
276
277     av_fast_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size,
278                    length + FF_INPUT_BUFFER_PADDING_SIZE);
279     dst = sl->rbsp_buffer;
280
281     if (!dst)
282         return NULL;
283
284     memcpy(dst, src, i);
285     si = di = i;
286     while (si + 2 < length) {
287         // remove escapes (very rare 1:2^22)
288         if (src[si + 2] > 3) {
289             dst[di++] = src[si++];
290             dst[di++] = src[si++];
291         } else if (src[si] == 0 && src[si + 1] == 0) {
292             if (src[si + 2] == 3) { // escape
293                 dst[di++]  = 0;
294                 dst[di++]  = 0;
295                 si        += 3;
296                 continue;
297             } else // next start code
298                 goto nsc;
299         }
300
301         dst[di++] = src[si++];
302     }
303     while (si < length)
304         dst[di++] = src[si++];
305
306 nsc:
307     memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
308
309     *dst_length = di;
310     *consumed   = si + 1; // +1 for the header
311     /* FIXME store exact number of bits in the getbitcontext
312      * (it is needed for decoding) */
313     return dst;
314 }
315
316 /**
317  * Identify the exact end of the bitstream
318  * @return the length of the trailing, or 0 if damaged
319  */
320 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
321 {
322     int v = *src;
323     int r;
324
325     ff_tlog(h->avctx, "rbsp trailing %X\n", v);
326
327     for (r = 1; r < 9; r++) {
328         if (v & 1)
329             return r;
330         v >>= 1;
331     }
332     return 0;
333 }
334
335 void ff_h264_free_tables(H264Context *h)
336 {
337     int i;
338
339     av_freep(&h->intra4x4_pred_mode);
340     av_freep(&h->chroma_pred_mode_table);
341     av_freep(&h->cbp_table);
342     av_freep(&h->mvd_table[0]);
343     av_freep(&h->mvd_table[1]);
344     av_freep(&h->direct_table);
345     av_freep(&h->non_zero_count);
346     av_freep(&h->slice_table_base);
347     h->slice_table = NULL;
348     av_freep(&h->list_counts);
349
350     av_freep(&h->mb2b_xy);
351     av_freep(&h->mb2br_xy);
352
353     av_buffer_pool_uninit(&h->qscale_table_pool);
354     av_buffer_pool_uninit(&h->mb_type_pool);
355     av_buffer_pool_uninit(&h->motion_val_pool);
356     av_buffer_pool_uninit(&h->ref_index_pool);
357
358     for (i = 0; i < h->nb_slice_ctx; i++) {
359         H264SliceContext *sl = &h->slice_ctx[i];
360
361         av_freep(&sl->dc_val_base);
362         av_freep(&sl->er.mb_index2xy);
363         av_freep(&sl->er.error_status_table);
364         av_freep(&sl->er.er_temp_buffer);
365
366         av_freep(&sl->bipred_scratchpad);
367         av_freep(&sl->edge_emu_buffer);
368         av_freep(&sl->top_borders[0]);
369         av_freep(&sl->top_borders[1]);
370
371         sl->bipred_scratchpad_allocated = 0;
372         sl->edge_emu_buffer_allocated   = 0;
373         sl->top_borders_allocated[0]    = 0;
374         sl->top_borders_allocated[1]    = 0;
375     }
376 }
377
378 int ff_h264_alloc_tables(H264Context *h)
379 {
380     const int big_mb_num = h->mb_stride * (h->mb_height + 1);
381     const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
382     int x, y;
383
384     FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
385                       row_mb_num * 8 * sizeof(uint8_t), fail)
386     h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
387
388     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
389                       big_mb_num * 48 * sizeof(uint8_t), fail)
390     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
391                       (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
392     FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
393                       big_mb_num * sizeof(uint16_t), fail)
394     FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
395                       big_mb_num * sizeof(uint8_t), fail)
396     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
397                       16 * row_mb_num * sizeof(uint8_t), fail);
398     FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
399                       16 * row_mb_num * sizeof(uint8_t), fail);
400     h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
401     h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
402
403     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
404                       4 * big_mb_num * sizeof(uint8_t), fail);
405     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
406                       big_mb_num * sizeof(uint8_t), fail)
407
408     memset(h->slice_table_base, -1,
409            (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
410     h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
411
412     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
413                       big_mb_num * sizeof(uint32_t), fail);
414     FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
415                       big_mb_num * sizeof(uint32_t), fail);
416     for (y = 0; y < h->mb_height; y++)
417         for (x = 0; x < h->mb_width; x++) {
418             const int mb_xy = x + y * h->mb_stride;
419             const int b_xy  = 4 * x + 4 * y * h->b_stride;
420
421             h->mb2b_xy[mb_xy]  = b_xy;
422             h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
423         }
424
425     if (!h->dequant4_coeff[0])
426         h264_init_dequant_tables(h);
427
428     return 0;
429
430 fail:
431     ff_h264_free_tables(h);
432     return AVERROR(ENOMEM);
433 }
434
435 /**
436  * Init context
437  * Allocate buffers which are not shared amongst multiple threads.
438  */
439 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
440 {
441     ERContext *er = &sl->er;
442     int mb_array_size = h->mb_height * h->mb_stride;
443     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
444     int c_size  = h->mb_stride * (h->mb_height + 1);
445     int yc_size = y_size + 2   * c_size;
446     int x, y, i;
447
448     sl->ref_cache[0][scan8[5]  + 1] =
449     sl->ref_cache[0][scan8[7]  + 1] =
450     sl->ref_cache[0][scan8[13] + 1] =
451     sl->ref_cache[1][scan8[5]  + 1] =
452     sl->ref_cache[1][scan8[7]  + 1] =
453     sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
454
455     if (CONFIG_ERROR_RESILIENCE) {
456         /* init ER */
457         er->avctx          = h->avctx;
458         er->decode_mb      = h264_er_decode_mb;
459         er->opaque         = h;
460         er->quarter_sample = 1;
461
462         er->mb_num      = h->mb_num;
463         er->mb_width    = h->mb_width;
464         er->mb_height   = h->mb_height;
465         er->mb_stride   = h->mb_stride;
466         er->b8_stride   = h->mb_width * 2 + 1;
467
468         // error resilience code looks cleaner with this
469         FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
470                           (h->mb_num + 1) * sizeof(int), fail);
471
472         for (y = 0; y < h->mb_height; y++)
473             for (x = 0; x < h->mb_width; x++)
474                 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
475
476         er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
477                                                       h->mb_stride + h->mb_width;
478
479         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
480                           mb_array_size * sizeof(uint8_t), fail);
481
482         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
483                          h->mb_height * h->mb_stride, fail);
484
485         FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
486                           yc_size * sizeof(int16_t), fail);
487         er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
488         er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
489         er->dc_val[2] = er->dc_val[1] + c_size;
490         for (i = 0; i < yc_size; i++)
491             sl->dc_val_base[i] = 1024;
492     }
493
494     return 0;
495
496 fail:
497     return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
498 }
499
500 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
501                             int parse_extradata);
502
503 int ff_h264_decode_extradata(H264Context *h)
504 {
505     AVCodecContext *avctx = h->avctx;
506     int ret;
507
508     if (avctx->extradata[0] == 1) {
509         int i, cnt, nalsize;
510         unsigned char *p = avctx->extradata;
511
512         h->is_avc = 1;
513
514         if (avctx->extradata_size < 7) {
515             av_log(avctx, AV_LOG_ERROR,
516                    "avcC %d too short\n", avctx->extradata_size);
517             return AVERROR_INVALIDDATA;
518         }
519         /* sps and pps in the avcC always have length coded with 2 bytes,
520          * so put a fake nal_length_size = 2 while parsing them */
521         h->nal_length_size = 2;
522         // Decode sps from avcC
523         cnt = *(p + 5) & 0x1f; // Number of sps
524         p  += 6;
525         for (i = 0; i < cnt; i++) {
526             nalsize = AV_RB16(p) + 2;
527             if (p - avctx->extradata + nalsize > avctx->extradata_size)
528                 return AVERROR_INVALIDDATA;
529             ret = decode_nal_units(h, p, nalsize, 1);
530             if (ret < 0) {
531                 av_log(avctx, AV_LOG_ERROR,
532                        "Decoding sps %d from avcC failed\n", i);
533                 return ret;
534             }
535             p += nalsize;
536         }
537         // Decode pps from avcC
538         cnt = *(p++); // Number of pps
539         for (i = 0; i < cnt; i++) {
540             nalsize = AV_RB16(p) + 2;
541             if (p - avctx->extradata + nalsize > avctx->extradata_size)
542                 return AVERROR_INVALIDDATA;
543             ret = decode_nal_units(h, p, nalsize, 1);
544             if (ret < 0) {
545                 av_log(avctx, AV_LOG_ERROR,
546                        "Decoding pps %d from avcC failed\n", i);
547                 return ret;
548             }
549             p += nalsize;
550         }
551         // Store right nal length size that will be used to parse all other nals
552         h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
553     } else {
554         h->is_avc = 0;
555         ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
556         if (ret < 0)
557             return ret;
558     }
559     return 0;
560 }
561
562 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
563 {
564     int i;
565
566     h->avctx                 = avctx;
567     h->dequant_coeff_pps     = -1;
568
569     h->picture_structure     = PICT_FRAME;
570     h->slice_context_count   = 1;
571     h->workaround_bugs       = avctx->workaround_bugs;
572     h->flags                 = avctx->flags;
573     h->prev_poc_msb          = 1 << 16;
574     h->x264_build            = -1;
575     h->recovery_frame        = -1;
576     h->frame_recovered       = 0;
577
578     h->next_outputed_poc = INT_MIN;
579     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
580         h->last_pocs[i] = INT_MIN;
581
582     ff_h264_reset_sei(h);
583
584     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
585
586     h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;
587     h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
588     if (!h->slice_ctx) {
589         h->nb_slice_ctx = 0;
590         return AVERROR(ENOMEM);
591     }
592
593     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
594         h->DPB[i].f = av_frame_alloc();
595         if (!h->DPB[i].f)
596             return AVERROR(ENOMEM);
597     }
598
599     h->cur_pic.f = av_frame_alloc();
600     if (!h->cur_pic.f)
601         return AVERROR(ENOMEM);
602
603     for (i = 0; i < h->nb_slice_ctx; i++)
604         h->slice_ctx[i].h264 = h;
605
606     return 0;
607 }
608
609 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
610 {
611     H264Context *h = avctx->priv_data;
612     int ret;
613
614     ret = h264_init_context(avctx, h);
615     if (ret < 0)
616         return ret;
617
618     /* set defaults */
619     if (!avctx->has_b_frames)
620         h->low_delay = 1;
621
622     ff_h264_decode_init_vlc();
623
624     ff_init_cabac_states();
625
626     if (avctx->codec_id == AV_CODEC_ID_H264) {
627         if (avctx->ticks_per_frame == 1)
628             h->avctx->framerate.num *= 2;
629         avctx->ticks_per_frame = 2;
630     }
631
632     if (avctx->extradata_size > 0 && avctx->extradata) {
633        ret = ff_h264_decode_extradata(h);
634        if (ret < 0) {
635            ff_h264_free_context(h);
636            return ret;
637        }
638     }
639
640     if (h->sps.bitstream_restriction_flag &&
641         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
642         h->avctx->has_b_frames = h->sps.num_reorder_frames;
643         h->low_delay           = 0;
644     }
645
646     avctx->internal->allocate_progress = 1;
647
648     if (h->enable_er) {
649         av_log(avctx, AV_LOG_WARNING,
650                "Error resilience is enabled. It is unsafe and unsupported and may crash. "
651                "Use it at your own risk\n");
652     }
653
654     return 0;
655 }
656
657 static int decode_init_thread_copy(AVCodecContext *avctx)
658 {
659     H264Context *h = avctx->priv_data;
660     int ret;
661
662     if (!avctx->internal->is_copy)
663         return 0;
664
665     memset(h, 0, sizeof(*h));
666
667     ret = h264_init_context(avctx, h);
668     if (ret < 0)
669         return ret;
670
671     h->context_initialized = 0;
672
673     return 0;
674 }
675
676 /**
677  * Run setup operations that must be run after slice header decoding.
678  * This includes finding the next displayed frame.
679  *
680  * @param h h264 master context
681  * @param setup_finished enough NALs have been read that we can call
682  * ff_thread_finish_setup()
683  */
684 static void decode_postinit(H264Context *h, int setup_finished)
685 {
686     H264Picture *out = h->cur_pic_ptr;
687     H264Picture *cur = h->cur_pic_ptr;
688     int i, pics, out_of_order, out_idx;
689     int invalid = 0, cnt = 0;
690
691     h->cur_pic_ptr->f->pict_type = h->pict_type;
692
693     if (h->next_output_pic)
694         return;
695
696     if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
697         /* FIXME: if we have two PAFF fields in one packet, we can't start
698          * the next thread here. If we have one field per packet, we can.
699          * The check in decode_nal_units() is not good enough to find this
700          * yet, so we assume the worst for now. */
701         // if (setup_finished)
702         //    ff_thread_finish_setup(h->avctx);
703         return;
704     }
705
706     cur->f->interlaced_frame = 0;
707     cur->f->repeat_pict      = 0;
708
709     /* Signal interlacing information externally. */
710     /* Prioritize picture timing SEI information over used
711      * decoding process if it exists. */
712
713     if (h->sps.pic_struct_present_flag) {
714         switch (h->sei_pic_struct) {
715         case SEI_PIC_STRUCT_FRAME:
716             break;
717         case SEI_PIC_STRUCT_TOP_FIELD:
718         case SEI_PIC_STRUCT_BOTTOM_FIELD:
719             cur->f->interlaced_frame = 1;
720             break;
721         case SEI_PIC_STRUCT_TOP_BOTTOM:
722         case SEI_PIC_STRUCT_BOTTOM_TOP:
723             if (FIELD_OR_MBAFF_PICTURE(h))
724                 cur->f->interlaced_frame = 1;
725             else
726                 // try to flag soft telecine progressive
727                 cur->f->interlaced_frame = h->prev_interlaced_frame;
728             break;
729         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
730         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
731             /* Signal the possibility of telecined film externally
732              * (pic_struct 5,6). From these hints, let the applications
733              * decide if they apply deinterlacing. */
734             cur->f->repeat_pict = 1;
735             break;
736         case SEI_PIC_STRUCT_FRAME_DOUBLING:
737             cur->f->repeat_pict = 2;
738             break;
739         case SEI_PIC_STRUCT_FRAME_TRIPLING:
740             cur->f->repeat_pict = 4;
741             break;
742         }
743
744         if ((h->sei_ct_type & 3) &&
745             h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
746             cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
747     } else {
748         /* Derive interlacing flag from used decoding process. */
749         cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
750     }
751     h->prev_interlaced_frame = cur->f->interlaced_frame;
752
753     if (cur->field_poc[0] != cur->field_poc[1]) {
754         /* Derive top_field_first from field pocs. */
755         cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
756     } else {
757         if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
758             /* Use picture timing SEI information. Even if it is a
759              * information of a past frame, better than nothing. */
760             if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
761                 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
762                 cur->f->top_field_first = 1;
763             else
764                 cur->f->top_field_first = 0;
765         } else {
766             /* Most likely progressive */
767             cur->f->top_field_first = 0;
768         }
769     }
770
771     if (h->sei_frame_packing_present &&
772         h->frame_packing_arrangement_type >= 0 &&
773         h->frame_packing_arrangement_type <= 6 &&
774         h->content_interpretation_type > 0 &&
775         h->content_interpretation_type < 3) {
776         AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
777         if (!stereo)
778             return;
779
780         switch (h->frame_packing_arrangement_type) {
781         case 0:
782             stereo->type = AV_STEREO3D_CHECKERBOARD;
783             break;
784         case 1:
785             stereo->type = AV_STEREO3D_COLUMNS;
786             break;
787         case 2:
788             stereo->type = AV_STEREO3D_LINES;
789             break;
790         case 3:
791             if (h->quincunx_subsampling)
792                 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
793             else
794                 stereo->type = AV_STEREO3D_SIDEBYSIDE;
795             break;
796         case 4:
797             stereo->type = AV_STEREO3D_TOPBOTTOM;
798             break;
799         case 5:
800             stereo->type = AV_STEREO3D_FRAMESEQUENCE;
801             break;
802         case 6:
803             stereo->type = AV_STEREO3D_2D;
804             break;
805         }
806
807         if (h->content_interpretation_type == 2)
808             stereo->flags = AV_STEREO3D_FLAG_INVERT;
809     }
810
811     if (h->sei_display_orientation_present &&
812         (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
813         double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
814         AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
815                                                            AV_FRAME_DATA_DISPLAYMATRIX,
816                                                            sizeof(int32_t) * 9);
817         if (!rotation)
818             return;
819
820         av_display_rotation_set((int32_t *)rotation->data, angle);
821         av_display_matrix_flip((int32_t *)rotation->data,
822                                h->sei_hflip, h->sei_vflip);
823     }
824
825     if (h->sei_reguserdata_afd_present) {
826         AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
827                                                      sizeof(uint8_t));
828         if (!sd)
829             return;
830
831         *sd->data = h->active_format_description;
832         h->sei_reguserdata_afd_present = 0;
833     }
834
835     if (h->a53_caption) {
836         AVFrameSideData *sd = av_frame_new_side_data(cur->f,
837                                                      AV_FRAME_DATA_A53_CC,
838                                                      h->a53_caption_size);
839         if (!sd)
840             return;
841
842         memcpy(sd->data, h->a53_caption, h->a53_caption_size);
843         av_freep(&h->a53_caption);
844         h->a53_caption_size = 0;
845     }
846
847     // FIXME do something with unavailable reference frames
848
849     /* Sort B-frames into display order */
850
851     if (h->sps.bitstream_restriction_flag &&
852         h->avctx->has_b_frames < h->sps.num_reorder_frames) {
853         h->avctx->has_b_frames = h->sps.num_reorder_frames;
854         h->low_delay           = 0;
855     }
856
857     if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
858         !h->sps.bitstream_restriction_flag) {
859         h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
860         h->low_delay           = 0;
861     }
862
863     pics = 0;
864     while (h->delayed_pic[pics])
865         pics++;
866
867     assert(pics <= MAX_DELAYED_PIC_COUNT);
868
869     h->delayed_pic[pics++] = cur;
870     if (cur->reference == 0)
871         cur->reference = DELAYED_PIC_REF;
872
873     /* Frame reordering. This code takes pictures from coding order and sorts
874      * them by their incremental POC value into display order. It supports POC
875      * gaps, MMCO reset codes and random resets.
876      * A "display group" can start either with a IDR frame (f.key_frame = 1),
877      * and/or can be closed down with a MMCO reset code. In sequences where
878      * there is no delay, we can't detect that (since the frame was already
879      * output to the user), so we also set h->mmco_reset to detect the MMCO
880      * reset code.
881      * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
882      * we increase the delay between input and output. All frames affected by
883      * the lag (e.g. those that should have been output before another frame
884      * that we already returned to the user) will be dropped. This is a bug
885      * that we will fix later. */
886     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
887         cnt     += out->poc < h->last_pocs[i];
888         invalid += out->poc == INT_MIN;
889     }
890     if (!h->mmco_reset && !cur->f->key_frame &&
891         cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
892         h->mmco_reset = 2;
893         if (pics > 1)
894             h->delayed_pic[pics - 2]->mmco_reset = 2;
895     }
896     if (h->mmco_reset || cur->f->key_frame) {
897         for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
898             h->last_pocs[i] = INT_MIN;
899         cnt     = 0;
900         invalid = MAX_DELAYED_PIC_COUNT;
901     }
902     out     = h->delayed_pic[0];
903     out_idx = 0;
904     for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
905                 h->delayed_pic[i] &&
906                 !h->delayed_pic[i - 1]->mmco_reset &&
907                 !h->delayed_pic[i]->f->key_frame;
908          i++)
909         if (h->delayed_pic[i]->poc < out->poc) {
910             out     = h->delayed_pic[i];
911             out_idx = i;
912         }
913     if (h->avctx->has_b_frames == 0 &&
914         (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
915         h->next_outputed_poc = INT_MIN;
916     out_of_order = !out->f->key_frame && !h->mmco_reset &&
917                    (out->poc < h->next_outputed_poc);
918
919     if (h->sps.bitstream_restriction_flag &&
920         h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
921     } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
922                h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
923         if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
924             h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
925         }
926         h->low_delay = 0;
927     } else if (h->low_delay &&
928                ((h->next_outputed_poc != INT_MIN &&
929                  out->poc > h->next_outputed_poc + 2) ||
930                 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
931         h->low_delay = 0;
932         h->avctx->has_b_frames++;
933     }
934
935     if (pics > h->avctx->has_b_frames) {
936         out->reference &= ~DELAYED_PIC_REF;
937         // for frame threading, the owner must be the second field's thread or
938         // else the first thread can release the picture and reuse it unsafely
939         for (i = out_idx; h->delayed_pic[i]; i++)
940             h->delayed_pic[i] = h->delayed_pic[i + 1];
941     }
942     memmove(h->last_pocs, &h->last_pocs[1],
943             sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
944     h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
945     if (!out_of_order && pics > h->avctx->has_b_frames) {
946         h->next_output_pic = out;
947         if (out->mmco_reset) {
948             if (out_idx > 0) {
949                 h->next_outputed_poc                    = out->poc;
950                 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
951             } else {
952                 h->next_outputed_poc = INT_MIN;
953             }
954         } else {
955             if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
956                 h->next_outputed_poc = INT_MIN;
957             } else {
958                 h->next_outputed_poc = out->poc;
959             }
960         }
961         h->mmco_reset = 0;
962     } else {
963         av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
964     }
965
966     if (h->next_output_pic) {
967         if (h->next_output_pic->recovered) {
968             // We have reached an recovery point and all frames after it in
969             // display order are "recovered".
970             h->frame_recovered |= FRAME_RECOVERED_SEI;
971         }
972         h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
973     }
974
975     if (setup_finished && !h->avctx->hwaccel) {
976         ff_thread_finish_setup(h->avctx);
977
978         if (h->avctx->active_thread_type & FF_THREAD_FRAME)
979             h->setup_finished = 1;
980     }
981 }
982
983 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
984 {
985     int list, i;
986     int luma_def, chroma_def;
987
988     sl->use_weight             = 0;
989     sl->use_weight_chroma      = 0;
990     sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
991     if (h->sps.chroma_format_idc)
992         sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
993     luma_def   = 1 << sl->luma_log2_weight_denom;
994     chroma_def = 1 << sl->chroma_log2_weight_denom;
995
996     for (list = 0; list < 2; list++) {
997         sl->luma_weight_flag[list]   = 0;
998         sl->chroma_weight_flag[list] = 0;
999         for (i = 0; i < sl->ref_count[list]; i++) {
1000             int luma_weight_flag, chroma_weight_flag;
1001
1002             luma_weight_flag = get_bits1(&sl->gb);
1003             if (luma_weight_flag) {
1004                 sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
1005                 sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
1006                 if (sl->luma_weight[i][list][0] != luma_def ||
1007                     sl->luma_weight[i][list][1] != 0) {
1008                     sl->use_weight             = 1;
1009                     sl->luma_weight_flag[list] = 1;
1010                 }
1011             } else {
1012                 sl->luma_weight[i][list][0] = luma_def;
1013                 sl->luma_weight[i][list][1] = 0;
1014             }
1015
1016             if (h->sps.chroma_format_idc) {
1017                 chroma_weight_flag = get_bits1(&sl->gb);
1018                 if (chroma_weight_flag) {
1019                     int j;
1020                     for (j = 0; j < 2; j++) {
1021                         sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
1022                         sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
1023                         if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1024                             sl->chroma_weight[i][list][j][1] != 0) {
1025                             sl->use_weight_chroma        = 1;
1026                             sl->chroma_weight_flag[list] = 1;
1027                         }
1028                     }
1029                 } else {
1030                     int j;
1031                     for (j = 0; j < 2; j++) {
1032                         sl->chroma_weight[i][list][j][0] = chroma_def;
1033                         sl->chroma_weight[i][list][j][1] = 0;
1034                     }
1035                 }
1036             }
1037         }
1038         if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1039             break;
1040     }
1041     sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1042     return 0;
1043 }
1044
1045 /**
1046  * instantaneous decoder refresh.
1047  */
1048 static void idr(H264Context *h)
1049 {
1050     ff_h264_remove_all_refs(h);
1051     h->prev_frame_num        =
1052     h->prev_frame_num_offset =
1053     h->prev_poc_msb          =
1054     h->prev_poc_lsb          = 0;
1055 }
1056
1057 /* forget old pics after a seek */
1058 void ff_h264_flush_change(H264Context *h)
1059 {
1060     int i;
1061     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1062         h->last_pocs[i] = INT_MIN;
1063     h->next_outputed_poc = INT_MIN;
1064     h->prev_interlaced_frame = 1;
1065     idr(h);
1066     if (h->cur_pic_ptr)
1067         h->cur_pic_ptr->reference = 0;
1068     h->first_field = 0;
1069     ff_h264_reset_sei(h);
1070     h->recovery_frame = -1;
1071     h->frame_recovered = 0;
1072 }
1073
1074 /* forget old pics after a seek */
1075 static void flush_dpb(AVCodecContext *avctx)
1076 {
1077     H264Context *h = avctx->priv_data;
1078     int i;
1079
1080     memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1081
1082     ff_h264_flush_change(h);
1083
1084     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1085         ff_h264_unref_picture(h, &h->DPB[i]);
1086     h->cur_pic_ptr = NULL;
1087     ff_h264_unref_picture(h, &h->cur_pic);
1088
1089     h->mb_y = 0;
1090
1091     ff_h264_free_tables(h);
1092     h->context_initialized = 0;
1093 }
1094
1095 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1096 {
1097     const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1098     int field_poc[2];
1099
1100     h->frame_num_offset = h->prev_frame_num_offset;
1101     if (h->frame_num < h->prev_frame_num)
1102         h->frame_num_offset += max_frame_num;
1103
1104     if (h->sps.poc_type == 0) {
1105         const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1106
1107         if (h->poc_lsb < h->prev_poc_lsb &&
1108             h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1109             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1110         else if (h->poc_lsb > h->prev_poc_lsb &&
1111                  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1112             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1113         else
1114             h->poc_msb = h->prev_poc_msb;
1115         field_poc[0] =
1116         field_poc[1] = h->poc_msb + h->poc_lsb;
1117         if (h->picture_structure == PICT_FRAME)
1118             field_poc[1] += h->delta_poc_bottom;
1119     } else if (h->sps.poc_type == 1) {
1120         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1121         int i;
1122
1123         if (h->sps.poc_cycle_length != 0)
1124             abs_frame_num = h->frame_num_offset + h->frame_num;
1125         else
1126             abs_frame_num = 0;
1127
1128         if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1129             abs_frame_num--;
1130
1131         expected_delta_per_poc_cycle = 0;
1132         for (i = 0; i < h->sps.poc_cycle_length; i++)
1133             // FIXME integrate during sps parse
1134             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1135
1136         if (abs_frame_num > 0) {
1137             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1138             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1139
1140             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1141             for (i = 0; i <= frame_num_in_poc_cycle; i++)
1142                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1143         } else
1144             expectedpoc = 0;
1145
1146         if (h->nal_ref_idc == 0)
1147             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1148
1149         field_poc[0] = expectedpoc + h->delta_poc[0];
1150         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1151
1152         if (h->picture_structure == PICT_FRAME)
1153             field_poc[1] += h->delta_poc[1];
1154     } else {
1155         int poc = 2 * (h->frame_num_offset + h->frame_num);
1156
1157         if (!h->nal_ref_idc)
1158             poc--;
1159
1160         field_poc[0] = poc;
1161         field_poc[1] = poc;
1162     }
1163
1164     if (h->picture_structure != PICT_BOTTOM_FIELD)
1165         pic_field_poc[0] = field_poc[0];
1166     if (h->picture_structure != PICT_TOP_FIELD)
1167         pic_field_poc[1] = field_poc[1];
1168     *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1169
1170     return 0;
1171 }
1172
1173 /**
1174  * Compute profile from profile_idc and constraint_set?_flags.
1175  *
1176  * @param sps SPS
1177  *
1178  * @return profile as defined by FF_PROFILE_H264_*
1179  */
1180 int ff_h264_get_profile(SPS *sps)
1181 {
1182     int profile = sps->profile_idc;
1183
1184     switch (sps->profile_idc) {
1185     case FF_PROFILE_H264_BASELINE:
1186         // constraint_set1_flag set to 1
1187         profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1188         break;
1189     case FF_PROFILE_H264_HIGH_10:
1190     case FF_PROFILE_H264_HIGH_422:
1191     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1192         // constraint_set3_flag set to 1
1193         profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1194         break;
1195     }
1196
1197     return profile;
1198 }
1199
1200 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1201 {
1202     int ref_count[2], list_count;
1203     int num_ref_idx_active_override_flag, max_refs;
1204
1205     // set defaults, might be overridden a few lines later
1206     ref_count[0] = h->pps.ref_count[0];
1207     ref_count[1] = h->pps.ref_count[1];
1208
1209     if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1210         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1211             sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1212         num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1213
1214         if (num_ref_idx_active_override_flag) {
1215             ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1216             if (ref_count[0] < 1)
1217                 return AVERROR_INVALIDDATA;
1218             if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1219                 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1220                 if (ref_count[1] < 1)
1221                     return AVERROR_INVALIDDATA;
1222             }
1223         }
1224
1225         if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1226             list_count = 2;
1227         else
1228             list_count = 1;
1229     } else {
1230         list_count   = 0;
1231         ref_count[0] = ref_count[1] = 0;
1232     }
1233
1234     max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1235
1236     if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1237         av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1238         sl->ref_count[0] = sl->ref_count[1] = 0;
1239         return AVERROR_INVALIDDATA;
1240     }
1241
1242     if (list_count   != sl->list_count   ||
1243         ref_count[0] != sl->ref_count[0] ||
1244         ref_count[1] != sl->ref_count[1]) {
1245         sl->ref_count[0] = ref_count[0];
1246         sl->ref_count[1] = ref_count[1];
1247         sl->list_count   = list_count;
1248         return 1;
1249     }
1250
1251     return 0;
1252 }
1253
1254 static int find_start_code(const uint8_t *buf, int buf_size,
1255                            int buf_index, int next_avc)
1256 {
1257     // start code prefix search
1258     for (; buf_index + 3 < next_avc; buf_index++)
1259         // This should always succeed in the first iteration.
1260         if (buf[buf_index]     == 0 &&
1261             buf[buf_index + 1] == 0 &&
1262             buf[buf_index + 2] == 1)
1263             break;
1264
1265     if (buf_index + 3 >= buf_size)
1266         return buf_size;
1267
1268     return buf_index + 3;
1269 }
1270
1271 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1272                            int buf_size, int *buf_index)
1273 {
1274     int i, nalsize = 0;
1275
1276     if (*buf_index >= buf_size - h->nal_length_size)
1277         return -1;
1278
1279     for (i = 0; i < h->nal_length_size; i++)
1280         nalsize = (nalsize << 8) | buf[(*buf_index)++];
1281     if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1282         av_log(h->avctx, AV_LOG_ERROR,
1283                "AVC: nal size %d\n", nalsize);
1284         return -1;
1285     }
1286     return nalsize;
1287 }
1288
1289 static int get_bit_length(H264Context *h, const uint8_t *buf,
1290                           const uint8_t *ptr, int dst_length,
1291                           int i, int next_avc)
1292 {
1293     if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1294         buf[i]     == 0x00 && buf[i + 1] == 0x00 &&
1295         buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1296         h->workaround_bugs |= FF_BUG_TRUNCATED;
1297
1298     if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1299         while (dst_length > 0 && ptr[dst_length - 1] == 0)
1300             dst_length--;
1301
1302     if (!dst_length)
1303         return 0;
1304
1305     return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1306 }
1307
1308 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1309 {
1310     int next_avc    = h->is_avc ? 0 : buf_size;
1311     int nal_index   = 0;
1312     int buf_index   = 0;
1313     int nals_needed = 0;
1314
1315     while(1) {
1316         GetBitContext gb;
1317         int nalsize = 0;
1318         int dst_length, bit_length, consumed;
1319         const uint8_t *ptr;
1320
1321         if (buf_index >= next_avc) {
1322             nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1323             if (nalsize < 0)
1324                 break;
1325             next_avc = buf_index + nalsize;
1326         } else {
1327             buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1328             if (buf_index >= buf_size)
1329                 break;
1330         }
1331
1332         ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1333                                  next_avc - buf_index);
1334
1335         if (!ptr || dst_length < 0)
1336             return AVERROR_INVALIDDATA;
1337
1338         buf_index += consumed;
1339
1340         bit_length = get_bit_length(h, buf, ptr, dst_length,
1341                                     buf_index, next_avc);
1342         nal_index++;
1343
1344         /* packets can sometimes contain multiple PPS/SPS,
1345          * e.g. two PAFF field pictures in one packet, or a demuxer
1346          * which splits NALs strangely if so, when frame threading we
1347          * can't start the next thread until we've read all of them */
1348         switch (h->nal_unit_type) {
1349         case NAL_SPS:
1350         case NAL_PPS:
1351             nals_needed = nal_index;
1352             break;
1353         case NAL_DPA:
1354         case NAL_IDR_SLICE:
1355         case NAL_SLICE:
1356             init_get_bits(&gb, ptr, bit_length);
1357             if (!get_ue_golomb(&gb))
1358                 nals_needed = nal_index;
1359         }
1360     }
1361
1362     return nals_needed;
1363 }
1364
1365 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1366                             int parse_extradata)
1367 {
1368     AVCodecContext *const avctx = h->avctx;
1369     H264SliceContext *sl;
1370     int buf_index;
1371     unsigned context_count;
1372     int next_avc;
1373     int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1374     int nal_index;
1375     int ret = 0;
1376
1377     h->max_contexts = h->slice_context_count;
1378     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1379         h->current_slice = 0;
1380         if (!h->first_field)
1381             h->cur_pic_ptr = NULL;
1382         ff_h264_reset_sei(h);
1383     }
1384
1385     if (avctx->active_thread_type & FF_THREAD_FRAME)
1386         nals_needed = get_last_needed_nal(h, buf, buf_size);
1387
1388     {
1389         buf_index     = 0;
1390         context_count = 0;
1391         next_avc      = h->is_avc ? 0 : buf_size;
1392         nal_index     = 0;
1393         for (;;) {
1394             int consumed;
1395             int dst_length;
1396             int bit_length;
1397             const uint8_t *ptr;
1398             int nalsize = 0;
1399             int err;
1400
1401             if (buf_index >= next_avc) {
1402                 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1403                 if (nalsize < 0)
1404                     break;
1405                 next_avc = buf_index + nalsize;
1406             } else {
1407                 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1408                 if (buf_index >= buf_size)
1409                     break;
1410                 if (buf_index >= next_avc)
1411                     continue;
1412             }
1413
1414             sl = &h->slice_ctx[context_count];
1415
1416             ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1417                                      &consumed, next_avc - buf_index);
1418             if (!ptr || dst_length < 0) {
1419                 ret = -1;
1420                 goto end;
1421             }
1422
1423             bit_length = get_bit_length(h, buf, ptr, dst_length,
1424                                         buf_index + consumed, next_avc);
1425
1426             if (h->avctx->debug & FF_DEBUG_STARTCODE)
1427                 av_log(h->avctx, AV_LOG_DEBUG,
1428                        "NAL %d at %d/%d length %d\n",
1429                        h->nal_unit_type, buf_index, buf_size, dst_length);
1430
1431             if (h->is_avc && (nalsize != consumed) && nalsize)
1432                 av_log(h->avctx, AV_LOG_DEBUG,
1433                        "AVC: Consumed only %d bytes instead of %d\n",
1434                        consumed, nalsize);
1435
1436             buf_index += consumed;
1437             nal_index++;
1438
1439             if (avctx->skip_frame >= AVDISCARD_NONREF &&
1440                 h->nal_ref_idc == 0 &&
1441                 h->nal_unit_type != NAL_SEI)
1442                 continue;
1443
1444 again:
1445             /* Ignore every NAL unit type except PPS and SPS during extradata
1446              * parsing. Decoding slices is not possible in codec init
1447              * with frame-mt */
1448             if (parse_extradata && HAVE_THREADS &&
1449                 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1450                 (h->nal_unit_type != NAL_PPS &&
1451                  h->nal_unit_type != NAL_SPS)) {
1452                 if (h->nal_unit_type < NAL_AUD ||
1453                     h->nal_unit_type > NAL_AUXILIARY_SLICE)
1454                     av_log(avctx, AV_LOG_INFO,
1455                            "Ignoring NAL unit %d during extradata parsing\n",
1456                            h->nal_unit_type);
1457                 h->nal_unit_type = NAL_FF_IGNORE;
1458             }
1459             err = 0;
1460             switch (h->nal_unit_type) {
1461             case NAL_IDR_SLICE:
1462                 if (h->nal_unit_type != NAL_IDR_SLICE) {
1463                     av_log(h->avctx, AV_LOG_ERROR,
1464                            "Invalid mix of idr and non-idr slices\n");
1465                     ret = -1;
1466                     goto end;
1467                 }
1468                 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1469             case NAL_SLICE:
1470                 init_get_bits(&sl->gb, ptr, bit_length);
1471
1472                 if ((err = ff_h264_decode_slice_header(h, sl)))
1473                     break;
1474
1475                 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1476                     h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1477                                         ((1 << h->sps.log2_max_frame_num) - 1);
1478                 }
1479
1480                 h->cur_pic_ptr->f->key_frame |=
1481                     (h->nal_unit_type == NAL_IDR_SLICE) ||
1482                     (h->sei_recovery_frame_cnt >= 0);
1483
1484                 if (h->nal_unit_type == NAL_IDR_SLICE ||
1485                     h->recovery_frame == h->frame_num) {
1486                     h->recovery_frame         = -1;
1487                     h->cur_pic_ptr->recovered = 1;
1488                 }
1489                 // If we have an IDR, all frames after it in decoded order are
1490                 // "recovered".
1491                 if (h->nal_unit_type == NAL_IDR_SLICE)
1492                     h->frame_recovered |= FRAME_RECOVERED_IDR;
1493                 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1494
1495                 if (h->current_slice == 1) {
1496                     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1497                         decode_postinit(h, nal_index >= nals_needed);
1498
1499                     if (h->avctx->hwaccel &&
1500                         (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1501                         return ret;
1502                 }
1503
1504                 if (sl->redundant_pic_count == 0 &&
1505                     (avctx->skip_frame < AVDISCARD_NONREF ||
1506                      h->nal_ref_idc) &&
1507                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
1508                      sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1509                     (avctx->skip_frame < AVDISCARD_NONKEY ||
1510                      sl->slice_type_nos == AV_PICTURE_TYPE_I) &&
1511                     avctx->skip_frame < AVDISCARD_ALL) {
1512                     if (avctx->hwaccel) {
1513                         ret = avctx->hwaccel->decode_slice(avctx,
1514                                                            &buf[buf_index - consumed],
1515                                                            consumed);
1516                         if (ret < 0)
1517                             return ret;
1518                     } else
1519                         context_count++;
1520                 }
1521                 break;
1522             case NAL_DPA:
1523             case NAL_DPB:
1524             case NAL_DPC:
1525                 avpriv_request_sample(avctx, "data partitioning");
1526                 ret = AVERROR(ENOSYS);
1527                 goto end;
1528                 break;
1529             case NAL_SEI:
1530                 init_get_bits(&h->gb, ptr, bit_length);
1531                 ret = ff_h264_decode_sei(h);
1532                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1533                     goto end;
1534                 break;
1535             case NAL_SPS:
1536                 init_get_bits(&h->gb, ptr, bit_length);
1537                 ret = ff_h264_decode_seq_parameter_set(h);
1538                 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
1539                     av_log(h->avctx, AV_LOG_DEBUG,
1540                            "SPS decoding failure, trying again with the complete NAL\n");
1541                     init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
1542                                   8 * (nalsize - 1));
1543                     ff_h264_decode_seq_parameter_set(h);
1544                 }
1545
1546                 break;
1547             case NAL_PPS:
1548                 init_get_bits(&h->gb, ptr, bit_length);
1549                 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1550                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1551                     goto end;
1552                 break;
1553             case NAL_AUD:
1554             case NAL_END_SEQUENCE:
1555             case NAL_END_STREAM:
1556             case NAL_FILLER_DATA:
1557             case NAL_SPS_EXT:
1558             case NAL_AUXILIARY_SLICE:
1559                 break;
1560             case NAL_FF_IGNORE:
1561                 break;
1562             default:
1563                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1564                        h->nal_unit_type, bit_length);
1565             }
1566
1567             if (context_count == h->max_contexts) {
1568                 ret = ff_h264_execute_decode_slices(h, context_count);
1569                 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1570                     goto end;
1571                 context_count = 0;
1572             }
1573
1574             if (err < 0) {
1575                 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1576                 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1577             } else if (err == 1) {
1578                 /* Slice could not be decoded in parallel mode, restart. Note
1579                  * that rbsp_buffer is not transferred, but since we no longer
1580                  * run in parallel mode this should not be an issue. */
1581                 sl               = &h->slice_ctx[0];
1582                 goto again;
1583             }
1584         }
1585     }
1586     if (context_count) {
1587         ret = ff_h264_execute_decode_slices(h, context_count);
1588         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1589             goto end;
1590     }
1591
1592     ret = 0;
1593 end:
1594     /* clean up */
1595     if (h->cur_pic_ptr && !h->droppable) {
1596         ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1597                                   h->picture_structure == PICT_BOTTOM_FIELD);
1598     }
1599
1600     return (ret < 0) ? ret : buf_index;
1601 }
1602
1603 /**
1604  * Return the number of bytes consumed for building the current frame.
1605  */
1606 static int get_consumed_bytes(int pos, int buf_size)
1607 {
1608     if (pos == 0)
1609         pos = 1;        // avoid infinite loops (I doubt that is needed but...)
1610     if (pos + 10 > buf_size)
1611         pos = buf_size; // oops ;)
1612
1613     return pos;
1614 }
1615
1616 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1617 {
1618     int i;
1619     int ret = av_frame_ref(dst, src);
1620     if (ret < 0)
1621         return ret;
1622
1623     if (!h->sps.crop)
1624         return 0;
1625
1626     for (i = 0; i < 3; i++) {
1627         int hshift = (i > 0) ? h->chroma_x_shift : 0;
1628         int vshift = (i > 0) ? h->chroma_y_shift : 0;
1629         int off    = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1630                      (h->sps.crop_top >> vshift) * dst->linesize[i];
1631         dst->data[i] += off;
1632     }
1633     return 0;
1634 }
1635
1636 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1637                              int *got_frame, AVPacket *avpkt)
1638 {
1639     const uint8_t *buf = avpkt->data;
1640     int buf_size       = avpkt->size;
1641     H264Context *h     = avctx->priv_data;
1642     AVFrame *pict      = data;
1643     int buf_index      = 0;
1644     int ret;
1645
1646     h->flags = avctx->flags;
1647     h->setup_finished = 0;
1648
1649     /* end of stream, output what is still in the buffers */
1650 out:
1651     if (buf_size == 0) {
1652         H264Picture *out;
1653         int i, out_idx;
1654
1655         h->cur_pic_ptr = NULL;
1656
1657         // FIXME factorize this with the output code below
1658         out     = h->delayed_pic[0];
1659         out_idx = 0;
1660         for (i = 1;
1661              h->delayed_pic[i] &&
1662              !h->delayed_pic[i]->f->key_frame &&
1663              !h->delayed_pic[i]->mmco_reset;
1664              i++)
1665             if (h->delayed_pic[i]->poc < out->poc) {
1666                 out     = h->delayed_pic[i];
1667                 out_idx = i;
1668             }
1669
1670         for (i = out_idx; h->delayed_pic[i]; i++)
1671             h->delayed_pic[i] = h->delayed_pic[i + 1];
1672
1673         if (out) {
1674             ret = output_frame(h, pict, out->f);
1675             if (ret < 0)
1676                 return ret;
1677             *got_frame = 1;
1678         }
1679
1680         return buf_index;
1681     }
1682
1683     buf_index = decode_nal_units(h, buf, buf_size, 0);
1684     if (buf_index < 0)
1685         return AVERROR_INVALIDDATA;
1686
1687     if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1688         buf_size = 0;
1689         goto out;
1690     }
1691
1692     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1693         if (avctx->skip_frame >= AVDISCARD_NONREF)
1694             return 0;
1695         av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1696         return AVERROR_INVALIDDATA;
1697     }
1698
1699     if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1700         (h->mb_y >= h->mb_height && h->mb_height)) {
1701         if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1702             decode_postinit(h, 1);
1703
1704         ff_h264_field_end(h, &h->slice_ctx[0], 0);
1705
1706         *got_frame = 0;
1707         if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1708                                    h->next_output_pic->recovered)) {
1709             if (!h->next_output_pic->recovered)
1710                 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1711
1712             ret = output_frame(h, pict, h->next_output_pic->f);
1713             if (ret < 0)
1714                 return ret;
1715             *got_frame = 1;
1716         }
1717     }
1718
1719     assert(pict->buf[0] || !*got_frame);
1720
1721     return get_consumed_bytes(buf_index, buf_size);
1722 }
1723
1724 av_cold void ff_h264_free_context(H264Context *h)
1725 {
1726     int i;
1727
1728     ff_h264_free_tables(h);
1729
1730     for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1731         ff_h264_unref_picture(h, &h->DPB[i]);
1732         av_frame_free(&h->DPB[i].f);
1733     }
1734
1735     h->cur_pic_ptr = NULL;
1736
1737     for (i = 0; i < h->nb_slice_ctx; i++)
1738         av_freep(&h->slice_ctx[i].rbsp_buffer);
1739     av_freep(&h->slice_ctx);
1740     h->nb_slice_ctx = 0;
1741
1742     for (i = 0; i < MAX_SPS_COUNT; i++)
1743         av_freep(h->sps_buffers + i);
1744
1745     for (i = 0; i < MAX_PPS_COUNT; i++)
1746         av_freep(h->pps_buffers + i);
1747 }
1748
1749 static av_cold int h264_decode_end(AVCodecContext *avctx)
1750 {
1751     H264Context *h = avctx->priv_data;
1752
1753     ff_h264_free_context(h);
1754
1755     ff_h264_unref_picture(h, &h->cur_pic);
1756     av_frame_free(&h->cur_pic.f);
1757
1758     return 0;
1759 }
1760
1761 #define OFFSET(x) offsetof(H264Context, x)
1762 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1763 static const AVOption h264_options[] = {
1764     { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1765     { NULL },
1766 };
1767
1768 static const AVClass h264_class = {
1769     .class_name = "h264",
1770     .item_name  = av_default_item_name,
1771     .option     = h264_options,
1772     .version    = LIBAVUTIL_VERSION_INT,
1773 };
1774
1775 static const AVProfile profiles[] = {
1776     { FF_PROFILE_H264_BASELINE,             "Baseline"              },
1777     { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
1778     { FF_PROFILE_H264_MAIN,                 "Main"                  },
1779     { FF_PROFILE_H264_EXTENDED,             "Extended"              },
1780     { FF_PROFILE_H264_HIGH,                 "High"                  },
1781     { FF_PROFILE_H264_HIGH_10,              "High 10"               },
1782     { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
1783     { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
1784     { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
1785     { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
1786     { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
1787     { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
1788     { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
1789     { FF_PROFILE_UNKNOWN },
1790 };
1791
1792 AVCodec ff_h264_decoder = {
1793     .name                  = "h264",
1794     .long_name             = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1795     .type                  = AVMEDIA_TYPE_VIDEO,
1796     .id                    = AV_CODEC_ID_H264,
1797     .priv_data_size        = sizeof(H264Context),
1798     .init                  = ff_h264_decode_init,
1799     .close                 = h264_decode_end,
1800     .decode                = h264_decode_frame,
1801     .capabilities          = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1802                              CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1803                              CODEC_CAP_FRAME_THREADS,
1804     .flush                 = flush_dpb,
1805     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1806     .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1807     .profiles              = NULL_IF_CONFIG_SMALL(profiles),
1808     .priv_class            = &h264_class,
1809 };