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