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