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