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