FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
h264.c
Go to the documentation of this file.
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 
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 =
97 }
98 
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;
120  int i;
121 
122  if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
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  */
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) {
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) {
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) {
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) {
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 (mode < 0) {
220  "left block unavailable for requested intra mode at %d %d\n",
221  h->mb_x, h->mb_y);
222  return AVERROR_INVALIDDATA;
223  }
224  if (is_chroma && (h->left_samples_available & 0x8080)) {
225  // mad cow disease mode, aka MBAFF + constrained_intra_pred
226  mode = ALZHEIMER_DC_L0T_PRED8x8 +
227  (!(h->left_samples_available & 0x8000)) +
228  2 * (mode == DC_128_PRED8x8);
229  }
230  }
231 
232  return mode;
233 }
234 
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 && src[i + 2] != 0) { \
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;
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;
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--;
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)
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 && src[si + 2] != 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  */
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 
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);
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 
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]);
410  av_freep(&hx->dc_val_base);
411  av_freep(&hx->er.mb_index2xy);
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 
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 
435  row_mb_num, 8 * sizeof(uint8_t), fail)
437  big_mb_num * 48 * sizeof(uint8_t), fail)
439  (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
441  big_mb_num * sizeof(uint16_t), fail)
443  big_mb_num * sizeof(uint8_t), fail)
445  row_mb_num, 16 * sizeof(uint8_t), fail);
447  row_mb_num, 16 * sizeof(uint8_t), fail);
449  4 * big_mb_num * sizeof(uint8_t), fail);
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 
458  big_mb_num * sizeof(uint32_t), fail);
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])
472 
473  if (!h->DPB) {
474  h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
475  if (!h->DPB)
476  goto fail;
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  */
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 
503  h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
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;
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
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 
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 
548  h->mb_height * h->mb_stride, fail);
549 
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 
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 
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);
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 
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 
672 
674 
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;
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) {
703  return ret;
704  }
705  }
706 
710  h->low_delay = 0;
711  }
712 
713  avctx->internal->allocate_progress = 1;
714 
716 
717  return 0;
718 }
719 
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 {
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) {
777  break;
780  cur->f.interlaced_frame = 1;
781  break;
784  if (FIELD_OR_MBAFF_PICTURE(h))
785  cur->f.interlaced_frame = 1;
786  else
787  // try to flag soft telecine progressive
789  break;
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;
798  cur->f.repeat_pict = 2;
799  break;
801  cur->f.repeat_pict = 4;
802  break;
803  }
804 
805  if ((h->sei_ct_type & 3) &&
807  cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
808  } else {
809  /* Derive interlacing flag from used decoding process. */
811  }
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 {
819  /* Use picture timing SEI information. Even if it is a
820  * information of a past frame, better than nothing. */
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 &&
837  AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
838  if (stereo) {
839  switch (h->frame_packing_arrangement_type) {
840  case 0:
841  stereo->type = AV_STEREO3D_CHECKERBOARD;
842  break;
843  case 1:
844  stereo->type = AV_STEREO3D_COLUMNS;
845  break;
846  case 2:
847  stereo->type = AV_STEREO3D_LINES;
848  break;
849  case 3:
850  if (h->quincunx_subsampling)
852  else
853  stereo->type = AV_STEREO3D_SIDEBYSIDE;
854  break;
855  case 4:
856  stereo->type = AV_STEREO3D_TOPBOTTOM;
857  break;
858  case 5:
860  break;
861  case 6:
862  stereo->type = AV_STEREO3D_2D;
863  break;
864  }
865 
866  if (h->content_interpretation_type == 2)
867  stereo->flags = AV_STEREO3D_FLAG_INVERT;
868  }
869  }
870 
873  double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
874  AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
876  sizeof(int32_t) * 9);
877  if (rotation) {
878  av_display_rotation_set((int32_t *)rotation->data, angle);
879  av_display_matrix_flip((int32_t *)rotation->data,
880  h->sei_hflip, h->sei_vflip);
881  }
882  }
883 
884  cur->mmco_reset = h->mmco_reset;
885  h->mmco_reset = 0;
886 
887  // FIXME do something with unavailable reference frames
888 
889  /* Sort B-frames into display order */
890 
894  h->low_delay = 0;
895  }
896 
900  h->low_delay = 0;
901  }
902 
903  for (i = 0; 1; i++) {
904  if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
905  if(i)
906  h->last_pocs[i-1] = cur->poc;
907  break;
908  } else if(i) {
909  h->last_pocs[i-1]= h->last_pocs[i];
910  }
911  }
912  out_of_order = MAX_DELAYED_PIC_COUNT - i;
913  if( cur->f.pict_type == AV_PICTURE_TYPE_B
915  out_of_order = FFMAX(out_of_order, 1);
916  if (out_of_order == MAX_DELAYED_PIC_COUNT) {
917  av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
918  for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
919  h->last_pocs[i] = INT_MIN;
920  h->last_pocs[0] = cur->poc;
921  cur->mmco_reset = 1;
922  } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
923  av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
924  h->avctx->has_b_frames = out_of_order;
925  h->low_delay = 0;
926  }
927 
928  pics = 0;
929  while (h->delayed_pic[pics])
930  pics++;
931 
933 
934  h->delayed_pic[pics++] = cur;
935  if (cur->reference == 0)
936  cur->reference = DELAYED_PIC_REF;
937 
938  out = h->delayed_pic[0];
939  out_idx = 0;
940  for (i = 1; h->delayed_pic[i] &&
941  !h->delayed_pic[i]->f.key_frame &&
942  !h->delayed_pic[i]->mmco_reset;
943  i++)
944  if (h->delayed_pic[i]->poc < out->poc) {
945  out = h->delayed_pic[i];
946  out_idx = i;
947  }
948  if (h->avctx->has_b_frames == 0 &&
949  (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
950  h->next_outputed_poc = INT_MIN;
951  out_of_order = out->poc < h->next_outputed_poc;
952 
953  if (out_of_order || pics > h->avctx->has_b_frames) {
954  out->reference &= ~DELAYED_PIC_REF;
955  // for frame threading, the owner must be the second field's thread or
956  // else the first thread can release the picture and reuse it unsafely
957  for (i = out_idx; h->delayed_pic[i]; i++)
958  h->delayed_pic[i] = h->delayed_pic[i + 1];
959  }
960  if (!out_of_order && pics > h->avctx->has_b_frames) {
961  h->next_output_pic = out;
962  if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
963  h->next_outputed_poc = INT_MIN;
964  } else
965  h->next_outputed_poc = out->poc;
966  } else {
967  av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
968  }
969 
970  if (h->next_output_pic) {
971  if (h->next_output_pic->recovered) {
972  // We have reached an recovery point and all frames after it in
973  // display order are "recovered".
975  }
977  }
978 
979  if (setup_finished && !h->avctx->hwaccel)
981 }
982 
984 {
985  int list, i;
986  int luma_def, chroma_def;
987 
988  h->use_weight = 0;
989  h->use_weight_chroma = 0;
991  if (h->sps.chroma_format_idc)
993  luma_def = 1 << h->luma_log2_weight_denom;
994  chroma_def = 1 << h->chroma_log2_weight_denom;
995 
996  for (list = 0; list < 2; list++) {
997  h->luma_weight_flag[list] = 0;
998  h->chroma_weight_flag[list] = 0;
999  for (i = 0; i < h->ref_count[list]; i++) {
1000  int luma_weight_flag, chroma_weight_flag;
1001 
1002  luma_weight_flag = get_bits1(&h->gb);
1003  if (luma_weight_flag) {
1004  h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
1005  h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
1006  if (h->luma_weight[i][list][0] != luma_def ||
1007  h->luma_weight[i][list][1] != 0) {
1008  h->use_weight = 1;
1009  h->luma_weight_flag[list] = 1;
1010  }
1011  } else {
1012  h->luma_weight[i][list][0] = luma_def;
1013  h->luma_weight[i][list][1] = 0;
1014  }
1015 
1016  if (h->sps.chroma_format_idc) {
1017  chroma_weight_flag = get_bits1(&h->gb);
1018  if (chroma_weight_flag) {
1019  int j;
1020  for (j = 0; j < 2; j++) {
1021  h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1022  h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1023  if (h->chroma_weight[i][list][j][0] != chroma_def ||
1024  h->chroma_weight[i][list][j][1] != 0) {
1025  h->use_weight_chroma = 1;
1026  h->chroma_weight_flag[list] = 1;
1027  }
1028  }
1029  } else {
1030  int j;
1031  for (j = 0; j < 2; j++) {
1032  h->chroma_weight[i][list][j][0] = chroma_def;
1033  h->chroma_weight[i][list][j][1] = 0;
1034  }
1035  }
1036  }
1037  }
1039  break;
1040  }
1041  h->use_weight = h->use_weight || h->use_weight_chroma;
1042  return 0;
1043 }
1044 
1045 /**
1046  * instantaneous decoder refresh.
1047  */
1048 static void idr(H264Context *h)
1049 {
1050  int i;
1052  h->prev_frame_num =
1053  h->prev_frame_num_offset = 0;
1054  h->prev_poc_msb = 1<<16;
1055  h->prev_poc_lsb = 0;
1056  for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1057  h->last_pocs[i] = INT_MIN;
1058 }
1059 
1060 /* forget old pics after a seek */
1062 {
1063  int i, j;
1064 
1065  h->outputed_poc = h->next_outputed_poc = INT_MIN;
1066  h->prev_interlaced_frame = 1;
1067  idr(h);
1068 
1069  h->prev_frame_num = -1;
1070  if (h->cur_pic_ptr) {
1071  h->cur_pic_ptr->reference = 0;
1072  for (j=i=0; h->delayed_pic[i]; i++)
1073  if (h->delayed_pic[i] != h->cur_pic_ptr)
1074  h->delayed_pic[j++] = h->delayed_pic[i];
1075  h->delayed_pic[j] = NULL;
1076  }
1077  h->first_field = 0;
1078  memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
1079  memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
1080  memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
1081  memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
1082  ff_h264_reset_sei(h);
1083  h->recovery_frame = -1;
1084  h->frame_recovered = 0;
1085  h->list_count = 0;
1086  h->current_slice = 0;
1087  h->mmco_reset = 1;
1088 }
1089 
1090 /* forget old pics after a seek */
1091 static void flush_dpb(AVCodecContext *avctx)
1092 {
1093  H264Context *h = avctx->priv_data;
1094  int i;
1095 
1096  for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
1097  if (h->delayed_pic[i])
1098  h->delayed_pic[i]->reference = 0;
1099  h->delayed_pic[i] = NULL;
1100  }
1101 
1103 
1104  if (h->DPB)
1105  for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1106  ff_h264_unref_picture(h, &h->DPB[i]);
1107  h->cur_pic_ptr = NULL;
1109 
1110  h->mb_x = h->mb_y = 0;
1111 
1112  h->parse_context.state = -1;
1114  h->parse_context.overread = 0;
1116  h->parse_context.index = 0;
1117  h->parse_context.last_index = 0;
1118 
1119  ff_h264_free_tables(h, 1);
1120  h->context_initialized = 0;
1121 }
1122 
1123 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1124 {
1125  const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1126  int field_poc[2];
1127 
1129  if (h->frame_num < h->prev_frame_num)
1130  h->frame_num_offset += max_frame_num;
1131 
1132  if (h->sps.poc_type == 0) {
1133  const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1134 
1135  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 if (h->poc_lsb > h->prev_poc_lsb &&
1139  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1140  h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1141  else
1142  h->poc_msb = h->prev_poc_msb;
1143  field_poc[0] =
1144  field_poc[1] = h->poc_msb + h->poc_lsb;
1145  if (h->picture_structure == PICT_FRAME)
1146  field_poc[1] += h->delta_poc_bottom;
1147  } else if (h->sps.poc_type == 1) {
1148  int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1149  int i;
1150 
1151  if (h->sps.poc_cycle_length != 0)
1152  abs_frame_num = h->frame_num_offset + h->frame_num;
1153  else
1154  abs_frame_num = 0;
1155 
1156  if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1157  abs_frame_num--;
1158 
1159  expected_delta_per_poc_cycle = 0;
1160  for (i = 0; i < h->sps.poc_cycle_length; i++)
1161  // FIXME integrate during sps parse
1162  expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1163 
1164  if (abs_frame_num > 0) {
1165  int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1166  int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1167 
1168  expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1169  for (i = 0; i <= frame_num_in_poc_cycle; i++)
1170  expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1171  } else
1172  expectedpoc = 0;
1173 
1174  if (h->nal_ref_idc == 0)
1175  expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1176 
1177  field_poc[0] = expectedpoc + h->delta_poc[0];
1178  field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1179 
1180  if (h->picture_structure == PICT_FRAME)
1181  field_poc[1] += h->delta_poc[1];
1182  } else {
1183  int poc = 2 * (h->frame_num_offset + h->frame_num);
1184 
1185  if (!h->nal_ref_idc)
1186  poc--;
1187 
1188  field_poc[0] = poc;
1189  field_poc[1] = poc;
1190  }
1191 
1193  pic_field_poc[0] = field_poc[0];
1195  pic_field_poc[1] = field_poc[1];
1196  *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1197 
1198  return 0;
1199 }
1200 
1201 /**
1202  * Compute profile from profile_idc and constraint_set?_flags.
1203  *
1204  * @param sps SPS
1205  *
1206  * @return profile as defined by FF_PROFILE_H264_*
1207  */
1209 {
1210  int profile = sps->profile_idc;
1211 
1212  switch (sps->profile_idc) {
1214  // constraint_set1_flag set to 1
1215  profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1216  break;
1220  // constraint_set3_flag set to 1
1221  profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1222  break;
1223  }
1224 
1225  return profile;
1226 }
1227 
1229 {
1230  if (h->flags & CODEC_FLAG_LOW_DELAY ||
1232  !h->sps.num_reorder_frames)) {
1233  if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1234  av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1235  "Reenabling low delay requires a codec flush.\n");
1236  else
1237  h->low_delay = 1;
1238  }
1239 
1240  if (h->avctx->has_b_frames < 2)
1241  h->avctx->has_b_frames = !h->low_delay;
1242 
1243  if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1245  if (h->avctx->codec &&
1247  (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
1249  "VDPAU decoding does not support video colorspace.\n");
1250  return AVERROR_INVALIDDATA;
1251  }
1252  if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
1253  h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
1256  h->pixel_shift = h->sps.bit_depth_luma > 8;
1257 
1259  h->sps.chroma_format_idc);
1263  h->sps.chroma_format_idc);
1264 
1265  if (CONFIG_ERROR_RESILIENCE)
1266  ff_me_cmp_init(&h->mecc, h->avctx);
1268  } else {
1269  av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1270  h->sps.bit_depth_luma);
1271  return AVERROR_INVALIDDATA;
1272  }
1273  }
1274  return 0;
1275 }
1276 
1278 {
1279  int ref_count[2], list_count;
1280  int num_ref_idx_active_override_flag;
1281 
1282  // set defaults, might be overridden a few lines later
1283  ref_count[0] = h->pps.ref_count[0];
1284  ref_count[1] = h->pps.ref_count[1];
1285 
1286  if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1287  unsigned max[2];
1288  max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1289 
1292  num_ref_idx_active_override_flag = get_bits1(&h->gb);
1293 
1294  if (num_ref_idx_active_override_flag) {
1295  ref_count[0] = get_ue_golomb(&h->gb) + 1;
1296  if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1297  ref_count[1] = get_ue_golomb(&h->gb) + 1;
1298  } else
1299  // full range is spec-ok in this case, even for frames
1300  ref_count[1] = 1;
1301  }
1302 
1303  if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1304  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]);
1305  h->ref_count[0] = h->ref_count[1] = 0;
1306  h->list_count = 0;
1307  return AVERROR_INVALIDDATA;
1308  }
1309 
1311  list_count = 2;
1312  else
1313  list_count = 1;
1314  } else {
1315  list_count = 0;
1316  ref_count[0] = ref_count[1] = 0;
1317  }
1318 
1319  if (list_count != h->list_count ||
1320  ref_count[0] != h->ref_count[0] ||
1321  ref_count[1] != h->ref_count[1]) {
1322  h->ref_count[0] = ref_count[0];
1323  h->ref_count[1] = ref_count[1];
1324  h->list_count = list_count;
1325  return 1;
1326  }
1327 
1328  return 0;
1329 }
1330 
1331 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1332 
1333 static int get_bit_length(H264Context *h, const uint8_t *buf,
1334  const uint8_t *ptr, int dst_length,
1335  int i, int next_avc)
1336 {
1337  if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1338  buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1339  buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1341 
1342  if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1343  while (dst_length > 0 && ptr[dst_length - 1] == 0)
1344  dst_length--;
1345 
1346  if (!dst_length)
1347  return 0;
1348 
1349  return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1350 }
1351 
1352 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1353 {
1354  int next_avc = h->is_avc ? 0 : buf_size;
1355  int nal_index = 0;
1356  int buf_index = 0;
1357  int nals_needed = 0;
1358  int first_slice = 0;
1359 
1360  while(1) {
1361  int nalsize = 0;
1362  int dst_length, bit_length, consumed;
1363  const uint8_t *ptr;
1364 
1365  if (buf_index >= next_avc) {
1366  nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1367  if (nalsize < 0)
1368  break;
1369  next_avc = buf_index + nalsize;
1370  } else {
1371  buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1372  if (buf_index >= buf_size)
1373  break;
1374  if (buf_index >= next_avc)
1375  continue;
1376  }
1377 
1378  ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1379  next_avc - buf_index);
1380 
1381  if (!ptr || dst_length < 0)
1382  return AVERROR_INVALIDDATA;
1383 
1384  buf_index += consumed;
1385 
1386  bit_length = get_bit_length(h, buf, ptr, dst_length,
1387  buf_index, next_avc);
1388  nal_index++;
1389 
1390  /* packets can sometimes contain multiple PPS/SPS,
1391  * e.g. two PAFF field pictures in one packet, or a demuxer
1392  * which splits NALs strangely if so, when frame threading we
1393  * can't start the next thread until we've read all of them */
1394  switch (h->nal_unit_type) {
1395  case NAL_SPS:
1396  case NAL_PPS:
1397  nals_needed = nal_index;
1398  break;
1399  case NAL_DPA:
1400  case NAL_IDR_SLICE:
1401  case NAL_SLICE:
1402  init_get_bits(&h->gb, ptr, bit_length);
1403  if (!get_ue_golomb(&h->gb) ||
1404  !first_slice ||
1405  first_slice != h->nal_unit_type)
1406  nals_needed = nal_index;
1407  if (!first_slice)
1408  first_slice = h->nal_unit_type;
1409  }
1410  }
1411 
1412  return nals_needed;
1413 }
1414 
1415 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1416  int parse_extradata)
1417 {
1418  AVCodecContext *const avctx = h->avctx;
1419  H264Context *hx; ///< thread context
1420  int buf_index;
1421  unsigned context_count;
1422  int next_avc;
1423  int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1424  int nal_index;
1425  int idr_cleared=0;
1426  int ret = 0;
1427 
1428  h->nal_unit_type= 0;
1429 
1430  if(!h->slice_context_count)
1431  h->slice_context_count= 1;
1433  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1434  h->current_slice = 0;
1435  if (!h->first_field)
1436  h->cur_pic_ptr = NULL;
1437  ff_h264_reset_sei(h);
1438  }
1439 
1440  if (h->nal_length_size == 4) {
1441  if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1442  h->is_avc = 0;
1443  }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1444  h->is_avc = 1;
1445  }
1446 
1447  if (avctx->active_thread_type & FF_THREAD_FRAME)
1448  nals_needed = get_last_needed_nal(h, buf, buf_size);
1449 
1450  {
1451  buf_index = 0;
1452  context_count = 0;
1453  next_avc = h->is_avc ? 0 : buf_size;
1454  nal_index = 0;
1455  for (;;) {
1456  int consumed;
1457  int dst_length;
1458  int bit_length;
1459  const uint8_t *ptr;
1460  int nalsize = 0;
1461  int err;
1462 
1463  if (buf_index >= next_avc) {
1464  nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1465  if (nalsize < 0)
1466  break;
1467  next_avc = buf_index + nalsize;
1468  } else {
1469  buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1470  if (buf_index >= buf_size)
1471  break;
1472  if (buf_index >= next_avc)
1473  continue;
1474  }
1475 
1476  hx = h->thread_context[context_count];
1477 
1478  ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1479  &consumed, next_avc - buf_index);
1480  if (!ptr || dst_length < 0) {
1481  ret = -1;
1482  goto end;
1483  }
1484 
1485  bit_length = get_bit_length(h, buf, ptr, dst_length,
1486  buf_index + consumed, next_avc);
1487 
1488  if (h->avctx->debug & FF_DEBUG_STARTCODE)
1490  "NAL %d/%d at %d/%d length %d\n",
1491  hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
1492 
1493  if (h->is_avc && (nalsize != consumed) && nalsize)
1495  "AVC: Consumed only %d bytes instead of %d\n",
1496  consumed, nalsize);
1497 
1498  buf_index += consumed;
1499  nal_index++;
1500 
1501  if (avctx->skip_frame >= AVDISCARD_NONREF &&
1502  h->nal_ref_idc == 0 &&
1503  h->nal_unit_type != NAL_SEI)
1504  continue;
1505 
1506 again:
1507  if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
1508  || nals_needed >= nal_index)
1509  h->au_pps_id = -1;
1510  /* Ignore per frame NAL unit type during extradata
1511  * parsing. Decoding slices is not possible in codec init
1512  * with frame-mt */
1513  if (parse_extradata) {
1514  switch (hx->nal_unit_type) {
1515  case NAL_IDR_SLICE:
1516  case NAL_SLICE:
1517  case NAL_DPA:
1518  case NAL_DPB:
1519  case NAL_DPC:
1521  "Ignoring NAL %d in global header/extradata\n",
1522  hx->nal_unit_type);
1523  // fall through to next case
1524  case NAL_AUXILIARY_SLICE:
1526  }
1527  }
1528 
1529  err = 0;
1530 
1531  switch (hx->nal_unit_type) {
1532  case NAL_IDR_SLICE:
1533  if ((ptr[0] & 0xFC) == 0x98) {
1534  av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1535  h->next_outputed_poc = INT_MIN;
1536  ret = -1;
1537  goto end;
1538  }
1539  if (h->nal_unit_type != NAL_IDR_SLICE) {
1541  "Invalid mix of idr and non-idr slices\n");
1542  ret = -1;
1543  goto end;
1544  }
1545  if(!idr_cleared)
1546  idr(h); // FIXME ensure we don't lose some frames if there is reordering
1547  idr_cleared = 1;
1548  h->has_recovery_point = 1;
1549  case NAL_SLICE:
1550  init_get_bits(&hx->gb, ptr, bit_length);
1551  hx->intra_gb_ptr =
1552  hx->inter_gb_ptr = &hx->gb;
1553  hx->data_partitioning = 0;
1554 
1555  if ((err = ff_h264_decode_slice_header(hx, h)))
1556  break;
1557 
1558  if (h->sei_recovery_frame_cnt >= 0) {
1560  h->valid_recovery_point = 1;
1561 
1562  if ( h->recovery_frame < 0
1563  || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
1565  ((1 << h->sps.log2_max_frame_num) - 1);
1566 
1567  if (!h->valid_recovery_point)
1568  h->recovery_frame = h->frame_num;
1569  }
1570  }
1571 
1572  h->cur_pic_ptr->f.key_frame |=
1573  (hx->nal_unit_type == NAL_IDR_SLICE);
1574 
1575  if (hx->nal_unit_type == NAL_IDR_SLICE ||
1576  h->recovery_frame == h->frame_num) {
1577  h->recovery_frame = -1;
1578  h->cur_pic_ptr->recovered = 1;
1579  }
1580  // If we have an IDR, all frames after it in decoded order are
1581  // "recovered".
1582  if (hx->nal_unit_type == NAL_IDR_SLICE)
1584  h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1585  h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1586 #if 1
1588 #else
1590 #endif
1591 
1592  if (h->current_slice == 1) {
1593  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1594  decode_postinit(h, nal_index >= nals_needed);
1595 
1596  if (h->avctx->hwaccel &&
1597  (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1598  return ret;
1599  if (CONFIG_H264_VDPAU_DECODER &&
1602  }
1603 
1604  if (hx->redundant_pic_count == 0) {
1605  if (avctx->hwaccel) {
1606  ret = avctx->hwaccel->decode_slice(avctx,
1607  &buf[buf_index - consumed],
1608  consumed);
1609  if (ret < 0)
1610  return ret;
1611  } else if (CONFIG_H264_VDPAU_DECODER &&
1614  start_code,
1615  sizeof(start_code));
1617  &buf[buf_index - consumed],
1618  consumed);
1619  } else
1620  context_count++;
1621  }
1622  break;
1623  case NAL_DPA:
1624  if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
1626  "Decoding in chunks is not supported for "
1627  "partitioned slices.\n");
1628  return AVERROR(ENOSYS);
1629  }
1630 
1631  init_get_bits(&hx->gb, ptr, bit_length);
1632  hx->intra_gb_ptr =
1633  hx->inter_gb_ptr = NULL;
1634 
1635  if ((err = ff_h264_decode_slice_header(hx, h))) {
1636  /* make sure data_partitioning is cleared if it was set
1637  * before, so we don't try decoding a slice without a valid
1638  * slice header later */
1639  h->data_partitioning = 0;
1640  break;
1641  }
1642 
1643  hx->data_partitioning = 1;
1644  break;
1645  case NAL_DPB:
1646  init_get_bits(&hx->intra_gb, ptr, bit_length);
1647  hx->intra_gb_ptr = &hx->intra_gb;
1648  break;
1649  case NAL_DPC:
1650  init_get_bits(&hx->inter_gb, ptr, bit_length);
1651  hx->inter_gb_ptr = &hx->inter_gb;
1652 
1653  av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
1654  break;
1655 
1656  if (hx->redundant_pic_count == 0 &&
1657  hx->intra_gb_ptr &&
1658  hx->data_partitioning &&
1659  h->cur_pic_ptr && h->context_initialized &&
1660  (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
1661  (avctx->skip_frame < AVDISCARD_BIDIR ||
1663  (avctx->skip_frame < AVDISCARD_NONINTRA ||
1665  avctx->skip_frame < AVDISCARD_ALL)
1666  context_count++;
1667  break;
1668  case NAL_SEI:
1669  init_get_bits(&h->gb, ptr, bit_length);
1670  ret = ff_h264_decode_sei(h);
1671  if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1672  goto end;
1673  break;
1674  case NAL_SPS:
1675  init_get_bits(&h->gb, ptr, bit_length);
1676  if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
1678  "SPS decoding failure, trying again with the complete NAL\n");
1679  if (h->is_avc)
1680  av_assert0(next_avc - buf_index + consumed == nalsize);
1681  if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1682  break;
1683  init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1684  8*(next_avc - buf_index + consumed - 1));
1686  }
1687 
1688  break;
1689  case NAL_PPS:
1690  init_get_bits(&h->gb, ptr, bit_length);
1691  ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1692  if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1693  goto end;
1694  break;
1695  case NAL_AUD:
1696  case NAL_END_SEQUENCE:
1697  case NAL_END_STREAM:
1698  case NAL_FILLER_DATA:
1699  case NAL_SPS_EXT:
1700  case NAL_AUXILIARY_SLICE:
1701  break;
1702  case NAL_FF_IGNORE:
1703  break;
1704  default:
1705  av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1706  hx->nal_unit_type, bit_length);
1707  }
1708 
1709  if (context_count == h->max_contexts) {
1710  ret = ff_h264_execute_decode_slices(h, context_count);
1711  if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1712  goto end;
1713  context_count = 0;
1714  }
1715 
1716  if (err < 0 || err == SLICE_SKIPED) {
1717  if (err < 0)
1718  av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1719  h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1720  } else if (err == SLICE_SINGLETHREAD) {
1721  /* Slice could not be decoded in parallel mode, copy down
1722  * NAL unit stuff to context 0 and restart. Note that
1723  * rbsp_buffer is not transferred, but since we no longer
1724  * run in parallel mode this should not be an issue. */
1725  h->nal_unit_type = hx->nal_unit_type;
1726  h->nal_ref_idc = hx->nal_ref_idc;
1727  hx = h;
1728  goto again;
1729  }
1730  }
1731  }
1732  if (context_count) {
1733  ret = ff_h264_execute_decode_slices(h, context_count);
1734  if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1735  goto end;
1736  }
1737 
1738  ret = 0;
1739 end:
1740  /* clean up */
1741  if (h->cur_pic_ptr && !h->droppable) {
1744  }
1745 
1746  return (ret < 0) ? ret : buf_index;
1747 }
1748 
1749 /**
1750  * Return the number of bytes consumed for building the current frame.
1751  */
1752 static int get_consumed_bytes(int pos, int buf_size)
1753 {
1754  if (pos == 0)
1755  pos = 1; // avoid infinite loops (I doubt that is needed but...)
1756  if (pos + 10 > buf_size)
1757  pos = buf_size; // oops ;)
1758 
1759  return pos;
1760 }
1761 
1763 {
1764  AVFrame *src = &srcp->f;
1765  const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1766  int i;
1767  int ret = av_frame_ref(dst, src);
1768  if (ret < 0)
1769  return ret;
1770 
1771  av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1772 
1773  if (srcp->sei_recovery_frame_cnt == 0)
1774  dst->key_frame = 1;
1775  if (!srcp->crop)
1776  return 0;
1777 
1778  for (i = 0; i < desc->nb_components; i++) {
1779  int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1780  int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1781  int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1782  (srcp->crop_top >> vshift) * dst->linesize[i];
1783  dst->data[i] += off;
1784  }
1785  return 0;
1786 }
1787 
1788 static int is_extra(const uint8_t *buf, int buf_size)
1789 {
1790  int cnt= buf[5]&0x1f;
1791  const uint8_t *p= buf+6;
1792  while(cnt--){
1793  int nalsize= AV_RB16(p) + 2;
1794  if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1795  return 0;
1796  p += nalsize;
1797  }
1798  cnt = *(p++);
1799  if(!cnt)
1800  return 0;
1801  while(cnt--){
1802  int nalsize= AV_RB16(p) + 2;
1803  if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1804  return 0;
1805  p += nalsize;
1806  }
1807  return 1;
1808 }
1809 
1810 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1811  int *got_frame, AVPacket *avpkt)
1812 {
1813  const uint8_t *buf = avpkt->data;
1814  int buf_size = avpkt->size;
1815  H264Context *h = avctx->priv_data;
1816  AVFrame *pict = data;
1817  int buf_index = 0;
1818  H264Picture *out;
1819  int i, out_idx;
1820  int ret;
1821 
1822  h->flags = avctx->flags;
1823  /* reset data partitioning here, to ensure GetBitContexts from previous
1824  * packets do not get used. */
1825  h->data_partitioning = 0;
1826 
1827  /* end of stream, output what is still in the buffers */
1828  if (buf_size == 0) {
1829  out:
1830 
1831  h->cur_pic_ptr = NULL;
1832  h->first_field = 0;
1833 
1834  // FIXME factorize this with the output code below
1835  out = h->delayed_pic[0];
1836  out_idx = 0;
1837  for (i = 1;
1838  h->delayed_pic[i] &&
1839  !h->delayed_pic[i]->f.key_frame &&
1840  !h->delayed_pic[i]->mmco_reset;
1841  i++)
1842  if (h->delayed_pic[i]->poc < out->poc) {
1843  out = h->delayed_pic[i];
1844  out_idx = i;
1845  }
1846 
1847  for (i = out_idx; h->delayed_pic[i]; i++)
1848  h->delayed_pic[i] = h->delayed_pic[i + 1];
1849 
1850  if (out) {
1851  out->reference &= ~DELAYED_PIC_REF;
1852  ret = output_frame(h, pict, out);
1853  if (ret < 0)
1854  return ret;
1855  *got_frame = 1;
1856  }
1857 
1858  return buf_index;
1859  }
1860  if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1861  int side_size;
1862  uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1863  if (is_extra(side, side_size))
1864  ff_h264_decode_extradata(h, side, side_size);
1865  }
1866  if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1867  if (is_extra(buf, buf_size))
1868  return ff_h264_decode_extradata(h, buf, buf_size);
1869  }
1870 
1871  buf_index = decode_nal_units(h, buf, buf_size, 0);
1872  if (buf_index < 0)
1873  return AVERROR_INVALIDDATA;
1874 
1875  if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1876  av_assert0(buf_index <= buf_size);
1877  goto out;
1878  }
1879 
1880  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1881  if (avctx->skip_frame >= AVDISCARD_NONREF ||
1882  buf_size >= 4 && !memcmp("Q264", buf, 4))
1883  return buf_size;
1884  av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1885  return AVERROR_INVALIDDATA;
1886  }
1887 
1888  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1889  (h->mb_y >= h->mb_height && h->mb_height)) {
1890  if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1891  decode_postinit(h, 1);
1892 
1893  ff_h264_field_end(h, 0);
1894 
1895  /* Wait for second field. */
1896  *got_frame = 0;
1897  if (h->next_output_pic && (
1898  h->next_output_pic->recovered)) {
1899  if (!h->next_output_pic->recovered)
1901 
1902  ret = output_frame(h, pict, h->next_output_pic);
1903  if (ret < 0)
1904  return ret;
1905  *got_frame = 1;
1906  if (CONFIG_MPEGVIDEO) {
1911  &h->low_delay,
1912  h->mb_width, h->mb_height, h->mb_stride, 1);
1913  }
1914  }
1915  }
1916 
1917  assert(pict->buf[0] || !*got_frame);
1918 
1919  return get_consumed_bytes(buf_index, buf_size);
1920 }
1921 
1923 {
1924  int i;
1925 
1926  ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1927 
1928  for (i = 0; i < MAX_SPS_COUNT; i++)
1929  av_freep(h->sps_buffers + i);
1930 
1931  for (i = 0; i < MAX_PPS_COUNT; i++)
1932  av_freep(h->pps_buffers + i);
1933 }
1934 
1936 {
1937  H264Context *h = avctx->priv_data;
1938 
1941 
1943 
1944  return 0;
1945 }
1946 
1947 static const AVProfile profiles[] = {
1948  { FF_PROFILE_H264_BASELINE, "Baseline" },
1949  { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1950  { FF_PROFILE_H264_MAIN, "Main" },
1951  { FF_PROFILE_H264_EXTENDED, "Extended" },
1952  { FF_PROFILE_H264_HIGH, "High" },
1953  { FF_PROFILE_H264_HIGH_10, "High 10" },
1954  { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1955  { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1956  { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1957  { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1958  { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1959  { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1960  { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1961  { FF_PROFILE_UNKNOWN },
1962 };
1963 
1964 static const AVOption h264_options[] = {
1965  {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1966  {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1967  {NULL}
1968 };
1969 
1970 static const AVClass h264_class = {
1971  .class_name = "H264 Decoder",
1972  .item_name = av_default_item_name,
1973  .option = h264_options,
1974  .version = LIBAVUTIL_VERSION_INT,
1975 };
1976 
1978  .name = "h264",
1979  .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1980  .type = AVMEDIA_TYPE_VIDEO,
1981  .id = AV_CODEC_ID_H264,
1982  .priv_data_size = sizeof(H264Context),
1986  .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1989  .flush = flush_dpb,
1991  .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1992  .profiles = NULL_IF_CONFIG_SMALL(profiles),
1993  .priv_class = &h264_class,
1994 };
1995 
1996 #if CONFIG_H264_VDPAU_DECODER
1997 static const AVClass h264_vdpau_class = {
1998  .class_name = "H264 VDPAU Decoder",
1999  .item_name = av_default_item_name,
2000  .option = h264_options,
2001  .version = LIBAVUTIL_VERSION_INT,
2002 };
2003 
2004 AVCodec ff_h264_vdpau_decoder = {
2005  .name = "h264_vdpau",
2006  .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
2007  .type = AVMEDIA_TYPE_VIDEO,
2008  .id = AV_CODEC_ID_H264,
2009  .priv_data_size = sizeof(H264Context),
2014  .flush = flush_dpb,
2015  .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2016  AV_PIX_FMT_NONE},
2017  .profiles = NULL_IF_CONFIG_SMALL(profiles),
2018  .priv_class = &h264_vdpau_class,
2019 };
2020 #endif