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