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