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/imgutils.h"
32 #include "libavutil/opt.h"
33 #include "internal.h"
34 #include "cabac.h"
35 #include "cabac_functions.h"
36 #include "dsputil.h"
37 #include "error_resilience.h"
38 #include "avcodec.h"
39 #include "mpegvideo.h"
40 #include "h264.h"
41 #include "h264data.h"
42 #include "h264chroma.h"
43 #include "h264_mvpred.h"
44 #include "golomb.h"
45 #include "mathops.h"
46 #include "rectangle.h"
47 #include "svq3.h"
48 #include "thread.h"
49 #include "vdpau_internal.h"
50 
51 #include <assert.h>
52 
53 static void flush_change(H264Context *h);
54 
55 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56 
57 static const uint8_t rem6[QP_MAX_NUM + 1] = {
58  0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
59  3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
60  0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
61  3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
62  0, 1, 2, 3,
63 };
64 
65 static const uint8_t div6[QP_MAX_NUM + 1] = {
66  0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
67  3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
68  7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
69  10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
70  14,14,14,14,
71 };
72 
73 static const uint8_t field_scan[16+1] = {
74  0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
75  0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
76  2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
77  3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
78 };
79 
80 static const uint8_t field_scan8x8[64+1] = {
81  0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
82  1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
83  2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
84  0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
85  2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
86  2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
87  2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
88  3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
89  3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
90  4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
91  4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
92  5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
93  5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
94  7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
95  6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
96  7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
97 };
98 
99 static const uint8_t field_scan8x8_cavlc[64+1] = {
100  0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
101  2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
102  3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
103  5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
104  0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
105  1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
106  3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
107  5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
108  0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
109  1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
110  3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
111  5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
112  1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
113  1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
114  3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
115  6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
116 };
117 
118 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
119 static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
120  0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
121  4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
122  3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
123  2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
124  1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
125  3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
126  2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
127  3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
128  0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
129  2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
130  1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
131  4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
132  0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
133  1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
134  0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
135  5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
136 };
137 
138 static const uint8_t dequant4_coeff_init[6][3] = {
139  { 10, 13, 16 },
140  { 11, 14, 18 },
141  { 13, 16, 20 },
142  { 14, 18, 23 },
143  { 16, 20, 25 },
144  { 18, 23, 29 },
145 };
146 
147 static const uint8_t dequant8_coeff_init_scan[16] = {
148  0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
149 };
150 
151 static const uint8_t dequant8_coeff_init[6][6] = {
152  { 20, 18, 32, 19, 25, 24 },
153  { 22, 19, 35, 21, 28, 26 },
154  { 26, 23, 42, 24, 33, 31 },
155  { 28, 25, 45, 26, 35, 33 },
156  { 32, 28, 51, 30, 40, 38 },
157  { 36, 32, 58, 34, 46, 43 },
158 };
159 
161 #if CONFIG_H264_DXVA2_HWACCEL
163 #endif
164 #if CONFIG_H264_VAAPI_HWACCEL
166 #endif
167 #if CONFIG_H264_VDA_HWACCEL
169 #endif
170 #if CONFIG_H264_VDPAU_HWACCEL
172 #endif
175 };
176 
178 #if CONFIG_H264_DXVA2_HWACCEL
180 #endif
181 #if CONFIG_H264_VAAPI_HWACCEL
183 #endif
184 #if CONFIG_H264_VDA_HWACCEL
186 #endif
187 #if CONFIG_H264_VDPAU_HWACCEL
189 #endif
192 };
193 
195 {
196  H264Context *h = avctx->priv_data;
197  return h ? h->sps.num_reorder_frames : 0;
198 }
199 
200 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
201  int (*mv)[2][4][2],
202  int mb_x, int mb_y, int mb_intra, int mb_skipped)
203 {
204  H264Context *h = opaque;
205 
206  h->mb_x = mb_x;
207  h->mb_y = mb_y;
208  h->mb_xy = mb_x + mb_y * h->mb_stride;
209  memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
210  av_assert1(ref >= 0);
211  /* FIXME: It is possible albeit uncommon that slice references
212  * differ between slices. We take the easy approach and ignore
213  * it for now. If this turns out to have any relevance in
214  * practice then correct remapping should be added. */
215  if (ref >= h->ref_count[0])
216  ref = 0;
217  if (!h->ref_list[0][ref].f.data[0]) {
218  av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
219  ref = 0;
220  }
221  if ((h->ref_list[0][ref].reference&3) != 3) {
222  av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
223  return;
224  }
225  fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
226  2, 2, 2, ref, 1);
227  fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
228  fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
229  pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
230  h->mb_mbaff =
231  h->mb_field_decoding_flag = 0;
233 }
234 
236 {
237  AVCodecContext *avctx = h->avctx;
238  Picture *cur = &h->cur_pic;
239  Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
240  const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
241  int vshift = desc->log2_chroma_h;
242  const int field_pic = h->picture_structure != PICT_FRAME;
243  if (field_pic) {
244  height <<= 1;
245  y <<= 1;
246  }
247 
248  height = FFMIN(height, avctx->height - y);
249 
250  if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
251  return;
252 
253  if (avctx->draw_horiz_band) {
254  AVFrame *src;
256  int i;
257 
258  if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
260  src = &cur->f;
261  else if (last)
262  src = &last->f;
263  else
264  return;
265 
266  offset[0] = y * src->linesize[0];
267  offset[1] =
268  offset[2] = (y >> vshift) * src->linesize[1];
269  for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
270  offset[i] = 0;
271 
272  emms_c();
273 
274  avctx->draw_horiz_band(avctx, src, offset,
275  y, h->picture_structure, height);
276  }
277 }
278 
279 static void unref_picture(H264Context *h, Picture *pic)
280 {
281  int off = offsetof(Picture, tf) + sizeof(pic->tf);
282  int i;
283 
284  if (!pic->f.data[0])
285  return;
286 
287  ff_thread_release_buffer(h->avctx, &pic->tf);
289 
292  for (i = 0; i < 2; i++) {
294  av_buffer_unref(&pic->ref_index_buf[i]);
295  }
296 
297  memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
298 }
299 
300 static void release_unused_pictures(H264Context *h, int remove_current)
301 {
302  int i;
303 
304  /* release non reference frames */
305  for (i = 0; i < MAX_PICTURE_COUNT; i++) {
306  if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
307  (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
308  unref_picture(h, &h->DPB[i]);
309  }
310  }
311 }
312 
313 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
314 {
315  int ret, i;
316 
317  av_assert0(!dst->f.buf[0]);
318  av_assert0(src->f.buf[0]);
319 
320  src->tf.f = &src->f;
321  dst->tf.f = &dst->f;
322  ret = ff_thread_ref_frame(&dst->tf, &src->tf);
323  if (ret < 0)
324  goto fail;
325 
328  if (!dst->qscale_table_buf || !dst->mb_type_buf)
329  goto fail;
330  dst->qscale_table = src->qscale_table;
331  dst->mb_type = src->mb_type;
332 
333  for (i = 0; i < 2; i++) {
334  dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
335  dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
336  if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
337  goto fail;
338  dst->motion_val[i] = src->motion_val[i];
339  dst->ref_index[i] = src->ref_index[i];
340  }
341 
342  if (src->hwaccel_picture_private) {
344  if (!dst->hwaccel_priv_buf)
345  goto fail;
347  }
348 
349  for (i = 0; i < 2; i++)
350  dst->field_poc[i] = src->field_poc[i];
351 
352  memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
353  memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
354 
355  dst->poc = src->poc;
356  dst->frame_num = src->frame_num;
357  dst->mmco_reset = src->mmco_reset;
358  dst->pic_id = src->pic_id;
359  dst->long_ref = src->long_ref;
360  dst->mbaff = src->mbaff;
361  dst->field_picture = src->field_picture;
362  dst->needs_realloc = src->needs_realloc;
363  dst->reference = src->reference;
364  dst->sync = src->sync;
365  dst->crop = src->crop;
366  dst->crop_left = src->crop_left;
367  dst->crop_top = src->crop_top;
368 
369  return 0;
370 fail:
371  unref_picture(h, dst);
372  return ret;
373 }
374 
375 static int alloc_scratch_buffers(H264Context *h, int linesize)
376 {
377  int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
378 
379  if (h->bipred_scratchpad)
380  return 0;
381 
382  h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
383  // edge emu needs blocksize + filter length - 1
384  // (= 21x21 for h264)
385  h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
386  h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
387 
388  if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
391  av_freep(&h->me.scratchpad);
392  return AVERROR(ENOMEM);
393  }
394 
395  h->me.temp = h->me.scratchpad;
396 
397  return 0;
398 }
399 
401 {
402  const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
403  const int mb_array_size = h->mb_stride * h->mb_height;
404  const int b4_stride = h->mb_width * 4 + 1;
405  const int b4_array_size = b4_stride * h->mb_height * 4;
406 
407  h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
409  h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
410  sizeof(uint32_t), av_buffer_allocz);
411  h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
412  sizeof(int16_t), av_buffer_allocz);
413  h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
414 
415  if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
416  !h->ref_index_pool) {
421  return AVERROR(ENOMEM);
422  }
423 
424  return 0;
425 }
426 
427 static int alloc_picture(H264Context *h, Picture *pic)
428 {
429  int i, ret = 0;
430 
431  av_assert0(!pic->f.data[0]);
432 
433  pic->tf.f = &pic->f;
434  ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
436  if (ret < 0)
437  goto fail;
438 
439  h->linesize = pic->f.linesize[0];
440  h->uvlinesize = pic->f.linesize[1];
441  pic->crop = h->sps.crop;
442  pic->crop_top = h->sps.crop_top;
443  pic->crop_left= h->sps.crop_left;
444 
445  if (h->avctx->hwaccel) {
446  const AVHWAccel *hwaccel = h->avctx->hwaccel;
448  if (hwaccel->priv_data_size) {
450  if (!pic->hwaccel_priv_buf)
451  return AVERROR(ENOMEM);
453  }
454  }
455 
456  if (!h->qscale_table_pool) {
457  ret = init_table_pools(h);
458  if (ret < 0)
459  goto fail;
460  }
461 
464  if (!pic->qscale_table_buf || !pic->mb_type_buf)
465  goto fail;
466 
467  pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
468  pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
469 
470  for (i = 0; i < 2; i++) {
473  if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
474  goto fail;
475 
476  pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
477  pic->ref_index[i] = pic->ref_index_buf[i]->data;
478  }
479 
480  return 0;
481 fail:
482  unref_picture(h, pic);
483  return (ret < 0) ? ret : AVERROR(ENOMEM);
484 }
485 
486 static inline int pic_is_unused(H264Context *h, Picture *pic)
487 {
488  if (pic->f.data[0] == NULL)
489  return 1;
490  if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
491  return 1;
492  return 0;
493 }
494 
496 {
497  int i;
498 
499  for (i = 0; i < MAX_PICTURE_COUNT; i++) {
500  if (pic_is_unused(h, &h->DPB[i]))
501  break;
502  }
503  if (i == MAX_PICTURE_COUNT)
504  return AVERROR_INVALIDDATA;
505 
506  if (h->DPB[i].needs_realloc) {
507  h->DPB[i].needs_realloc = 0;
508  unref_picture(h, &h->DPB[i]);
509  }
510 
511  return i;
512 }
513 
514 /**
515  * Check if the top & left blocks are available if needed and
516  * change the dc mode so it only uses the available blocks.
517  */
519 {
520  static const int8_t top[12] = {
521  -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
522  };
523  static const int8_t left[12] = {
524  0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
525  };
526  int i;
527 
528  if (!(h->top_samples_available & 0x8000)) {
529  for (i = 0; i < 4; i++) {
530  int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
531  if (status < 0) {
533  "top block unavailable for requested intra4x4 mode %d at %d %d\n",
534  status, h->mb_x, h->mb_y);
535  return AVERROR_INVALIDDATA;
536  } else if (status) {
537  h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
538  }
539  }
540  }
541 
542  if ((h->left_samples_available & 0x8888) != 0x8888) {
543  static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
544  for (i = 0; i < 4; i++)
545  if (!(h->left_samples_available & mask[i])) {
546  int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
547  if (status < 0) {
549  "left block unavailable for requested intra4x4 mode %d at %d %d\n",
550  status, h->mb_x, h->mb_y);
551  return AVERROR_INVALIDDATA;
552  } else if (status) {
553  h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
554  }
555  }
556  }
557 
558  return 0;
559 } // FIXME cleanup like ff_h264_check_intra_pred_mode
560 
561 /**
562  * Check if the top & left blocks are available if needed and
563  * change the dc mode so it only uses the available blocks.
564  */
565 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
566 {
567  static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
568  static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
569 
570  if (mode > 3U) {
572  "out of range intra chroma pred mode at %d %d\n",
573  h->mb_x, h->mb_y);
574  return AVERROR_INVALIDDATA;
575  }
576 
577  if (!(h->top_samples_available & 0x8000)) {
578  mode = top[mode];
579  if (mode < 0) {
581  "top block unavailable for requested intra mode at %d %d\n",
582  h->mb_x, h->mb_y);
583  return AVERROR_INVALIDDATA;
584  }
585  }
586 
587  if ((h->left_samples_available & 0x8080) != 0x8080) {
588  mode = left[mode];
589  if (is_chroma && (h->left_samples_available & 0x8080)) {
590  // mad cow disease mode, aka MBAFF + constrained_intra_pred
591  mode = ALZHEIMER_DC_L0T_PRED8x8 +
592  (!(h->left_samples_available & 0x8000)) +
593  2 * (mode == DC_128_PRED8x8);
594  }
595  if (mode < 0) {
597  "left block unavailable for requested intra mode at %d %d\n",
598  h->mb_x, h->mb_y);
599  return AVERROR_INVALIDDATA;
600  }
601  }
602 
603  return mode;
604 }
605 
607  int *dst_length, int *consumed, int length)
608 {
609  int i, si, di;
610  uint8_t *dst;
611  int bufidx;
612 
613  // src[0]&0x80; // forbidden bit
614  h->nal_ref_idc = src[0] >> 5;
615  h->nal_unit_type = src[0] & 0x1F;
616 
617  src++;
618  length--;
619 
620 #define STARTCODE_TEST \
621  if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
622  if (src[i + 2] != 3) { \
623  /* startcode, so we must be past the end */ \
624  length = i; \
625  } \
626  break; \
627  }
628 
629 #if HAVE_FAST_UNALIGNED
630 #define FIND_FIRST_ZERO \
631  if (i > 0 && !src[i]) \
632  i--; \
633  while (src[i]) \
634  i++
635 
636 #if HAVE_FAST_64BIT
637  for (i = 0; i + 1 < length; i += 9) {
638  if (!((~AV_RN64A(src + i) &
639  (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
640  0x8000800080008080ULL))
641  continue;
642  FIND_FIRST_ZERO;
644  i -= 7;
645  }
646 #else
647  for (i = 0; i + 1 < length; i += 5) {
648  if (!((~AV_RN32A(src + i) &
649  (AV_RN32A(src + i) - 0x01000101U)) &
650  0x80008080U))
651  continue;
652  FIND_FIRST_ZERO;
654  i -= 3;
655  }
656 #endif
657 #else
658  for (i = 0; i + 1 < length; i += 2) {
659  if (src[i])
660  continue;
661  if (i > 0 && src[i - 1] == 0)
662  i--;
664  }
665 #endif
666 
667  // use second escape buffer for inter data
668  bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
669 
670  si = h->rbsp_buffer_size[bufidx];
671  av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
672  dst = h->rbsp_buffer[bufidx];
673 
674  if (dst == NULL)
675  return NULL;
676 
677  if(i>=length-1){ //no escaped 0
678  *dst_length= length;
679  *consumed= length+1; //+1 for the header
680  if(h->avctx->flags2 & CODEC_FLAG2_FAST){
681  return src;
682  }else{
683  memcpy(dst, src, length);
684  return dst;
685  }
686  }
687 
688  memcpy(dst, src, i);
689  si = di = i;
690  while (si + 2 < length) {
691  // remove escapes (very rare 1:2^22)
692  if (src[si + 2] > 3) {
693  dst[di++] = src[si++];
694  dst[di++] = src[si++];
695  } else if (src[si] == 0 && src[si + 1] == 0) {
696  if (src[si + 2] == 3) { // escape
697  dst[di++] = 0;
698  dst[di++] = 0;
699  si += 3;
700  continue;
701  } else // next start code
702  goto nsc;
703  }
704 
705  dst[di++] = src[si++];
706  }
707  while (si < length)
708  dst[di++] = src[si++];
709 
710 nsc:
711  memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
712 
713  *dst_length = di;
714  *consumed = si + 1; // +1 for the header
715  /* FIXME store exact number of bits in the getbitcontext
716  * (it is needed for decoding) */
717  return dst;
718 }
719 
720 /**
721  * Identify the exact end of the bitstream
722  * @return the length of the trailing, or 0 if damaged
723  */
725 {
726  int v = *src;
727  int r;
728 
729  tprintf(h->avctx, "rbsp trailing %X\n", v);
730 
731  for (r = 1; r < 9; r++) {
732  if (v & 1)
733  return r;
734  v >>= 1;
735  }
736  return 0;
737 }
738 
739 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
740  int height, int y_offset, int list)
741 {
742  int raw_my = h->mv_cache[list][scan8[n]][1];
743  int filter_height_down = (raw_my & 3) ? 3 : 0;
744  int full_my = (raw_my >> 2) + y_offset;
745  int bottom = full_my + filter_height_down + height;
746 
747  av_assert2(height >= 0);
748 
749  return FFMAX(0, bottom);
750 }
751 
752 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
753  int height, int y_offset, int list0,
754  int list1, int *nrefs)
755 {
756  int my;
757 
758  y_offset += 16 * (h->mb_y >> MB_FIELD(h));
759 
760  if (list0) {
761  int ref_n = h->ref_cache[0][scan8[n]];
762  Picture *ref = &h->ref_list[0][ref_n];
763 
764  // Error resilience puts the current picture in the ref list.
765  // Don't try to wait on these as it will cause a deadlock.
766  // Fields can wait on each other, though.
767  if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
768  (ref->reference & 3) != h->picture_structure) {
769  my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
770  if (refs[0][ref_n] < 0)
771  nrefs[0] += 1;
772  refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
773  }
774  }
775 
776  if (list1) {
777  int ref_n = h->ref_cache[1][scan8[n]];
778  Picture *ref = &h->ref_list[1][ref_n];
779 
780  if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
781  (ref->reference & 3) != h->picture_structure) {
782  my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
783  if (refs[1][ref_n] < 0)
784  nrefs[1] += 1;
785  refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
786  }
787  }
788 }
789 
790 /**
791  * Wait until all reference frames are available for MC operations.
792  *
793  * @param h the H264 context
794  */
796 {
797  const int mb_xy = h->mb_xy;
798  const int mb_type = h->cur_pic.mb_type[mb_xy];
799  int refs[2][48];
800  int nrefs[2] = { 0 };
801  int ref, list;
802 
803  memset(refs, -1, sizeof(refs));
804 
805  if (IS_16X16(mb_type)) {
806  get_lowest_part_y(h, refs, 0, 16, 0,
807  IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
808  } else if (IS_16X8(mb_type)) {
809  get_lowest_part_y(h, refs, 0, 8, 0,
810  IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
811  get_lowest_part_y(h, refs, 8, 8, 8,
812  IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
813  } else if (IS_8X16(mb_type)) {
814  get_lowest_part_y(h, refs, 0, 16, 0,
815  IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
816  get_lowest_part_y(h, refs, 4, 16, 0,
817  IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
818  } else {
819  int i;
820 
821  av_assert2(IS_8X8(mb_type));
822 
823  for (i = 0; i < 4; i++) {
824  const int sub_mb_type = h->sub_mb_type[i];
825  const int n = 4 * i;
826  int y_offset = (i & 2) << 2;
827 
828  if (IS_SUB_8X8(sub_mb_type)) {
829  get_lowest_part_y(h, refs, n, 8, y_offset,
830  IS_DIR(sub_mb_type, 0, 0),
831  IS_DIR(sub_mb_type, 0, 1),
832  nrefs);
833  } else if (IS_SUB_8X4(sub_mb_type)) {
834  get_lowest_part_y(h, refs, n, 4, y_offset,
835  IS_DIR(sub_mb_type, 0, 0),
836  IS_DIR(sub_mb_type, 0, 1),
837  nrefs);
838  get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
839  IS_DIR(sub_mb_type, 0, 0),
840  IS_DIR(sub_mb_type, 0, 1),
841  nrefs);
842  } else if (IS_SUB_4X8(sub_mb_type)) {
843  get_lowest_part_y(h, refs, n, 8, y_offset,
844  IS_DIR(sub_mb_type, 0, 0),
845  IS_DIR(sub_mb_type, 0, 1),
846  nrefs);
847  get_lowest_part_y(h, refs, n + 1, 8, y_offset,
848  IS_DIR(sub_mb_type, 0, 0),
849  IS_DIR(sub_mb_type, 0, 1),
850  nrefs);
851  } else {
852  int j;
853  av_assert2(IS_SUB_4X4(sub_mb_type));
854  for (j = 0; j < 4; j++) {
855  int sub_y_offset = y_offset + 2 * (j & 2);
856  get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
857  IS_DIR(sub_mb_type, 0, 0),
858  IS_DIR(sub_mb_type, 0, 1),
859  nrefs);
860  }
861  }
862  }
863  }
864 
865  for (list = h->list_count - 1; list >= 0; list--)
866  for (ref = 0; ref < 48 && nrefs[list]; ref++) {
867  int row = refs[list][ref];
868  if (row >= 0) {
869  Picture *ref_pic = &h->ref_list[list][ref];
870  int ref_field = ref_pic->reference - 1;
871  int ref_field_picture = ref_pic->field_picture;
872  int pic_height = 16 * h->mb_height >> ref_field_picture;
873 
874  row <<= MB_MBAFF(h);
875  nrefs[list]--;
876 
877  if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
878  ff_thread_await_progress(&ref_pic->tf,
879  FFMIN((row >> 1) - !(row & 1),
880  pic_height - 1),
881  1);
882  ff_thread_await_progress(&ref_pic->tf,
883  FFMIN((row >> 1), pic_height - 1),
884  0);
885  } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
886  ff_thread_await_progress(&ref_pic->tf,
887  FFMIN(row * 2 + ref_field,
888  pic_height - 1),
889  0);
890  } else if (FIELD_PICTURE(h)) {
891  ff_thread_await_progress(&ref_pic->tf,
892  FFMIN(row, pic_height - 1),
893  ref_field);
894  } else {
895  ff_thread_await_progress(&ref_pic->tf,
896  FFMIN(row, pic_height - 1),
897  0);
898  }
899  }
900  }
901 }
902 
904  int n, int square, int height,
905  int delta, int list,
906  uint8_t *dest_y, uint8_t *dest_cb,
907  uint8_t *dest_cr,
908  int src_x_offset, int src_y_offset,
909  qpel_mc_func *qpix_op,
910  h264_chroma_mc_func chroma_op,
911  int pixel_shift, int chroma_idc)
912 {
913  const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
914  int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
915  const int luma_xy = (mx & 3) + ((my & 3) << 2);
916  ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
917  uint8_t *src_y = pic->f.data[0] + offset;
918  uint8_t *src_cb, *src_cr;
919  int extra_width = 0;
920  int extra_height = 0;
921  int emu = 0;
922  const int full_mx = mx >> 2;
923  const int full_my = my >> 2;
924  const int pic_width = 16 * h->mb_width;
925  const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
926  int ysh;
927 
928  if (mx & 7)
929  extra_width -= 3;
930  if (my & 7)
931  extra_height -= 3;
932 
933  if (full_mx < 0 - extra_width ||
934  full_my < 0 - extra_height ||
935  full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
936  full_my + 16 /*FIXME*/ > pic_height + extra_height) {
938  src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
939  h->mb_linesize,
940  16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
941  full_my - 2, pic_width, pic_height);
942  src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
943  emu = 1;
944  }
945 
946  qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
947  if (!square)
948  qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
949 
950  if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
951  return;
952 
953  if (chroma_idc == 3 /* yuv444 */) {
954  src_cb = pic->f.data[1] + offset;
955  if (emu) {
957  src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
958  h->mb_linesize,
959  16 + 5, 16 + 5 /*FIXME*/,
960  full_mx - 2, full_my - 2,
961  pic_width, pic_height);
962  src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
963  }
964  qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
965  if (!square)
966  qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
967 
968  src_cr = pic->f.data[2] + offset;
969  if (emu) {
971  src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
972  h->mb_linesize,
973  16 + 5, 16 + 5 /*FIXME*/,
974  full_mx - 2, full_my - 2,
975  pic_width, pic_height);
976  src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
977  }
978  qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
979  if (!square)
980  qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
981  return;
982  }
983 
984  ysh = 3 - (chroma_idc == 2 /* yuv422 */);
985  if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
986  // chroma offset when predicting from a field of opposite parity
987  my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
988  emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
989  }
990 
991  src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
992  (my >> ysh) * h->mb_uvlinesize;
993  src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
994  (my >> ysh) * h->mb_uvlinesize;
995 
996  if (emu) {
998  9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
999  pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1000  src_cb = h->edge_emu_buffer;
1001  }
1002  chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
1003  height >> (chroma_idc == 1 /* yuv420 */),
1004  mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1005 
1006  if (emu) {
1008  9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1009  pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1010  src_cr = h->edge_emu_buffer;
1011  }
1012  chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
1013  mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1014 }
1015 
1017  int height, int delta,
1018  uint8_t *dest_y, uint8_t *dest_cb,
1019  uint8_t *dest_cr,
1020  int x_offset, int y_offset,
1021  qpel_mc_func *qpix_put,
1022  h264_chroma_mc_func chroma_put,
1023  qpel_mc_func *qpix_avg,
1024  h264_chroma_mc_func chroma_avg,
1025  int list0, int list1,
1026  int pixel_shift, int chroma_idc)
1027 {
1028  qpel_mc_func *qpix_op = qpix_put;
1029  h264_chroma_mc_func chroma_op = chroma_put;
1030 
1031  dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1032  if (chroma_idc == 3 /* yuv444 */) {
1033  dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1034  dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1035  } else if (chroma_idc == 2 /* yuv422 */) {
1036  dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1037  dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1038  } else { /* yuv420 */
1039  dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1040  dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1041  }
1042  x_offset += 8 * h->mb_x;
1043  y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1044 
1045  if (list0) {
1046  Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1047  mc_dir_part(h, ref, n, square, height, delta, 0,
1048  dest_y, dest_cb, dest_cr, x_offset, y_offset,
1049  qpix_op, chroma_op, pixel_shift, chroma_idc);
1050 
1051  qpix_op = qpix_avg;
1052  chroma_op = chroma_avg;
1053  }
1054 
1055  if (list1) {
1056  Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1057  mc_dir_part(h, ref, n, square, height, delta, 1,
1058  dest_y, dest_cb, dest_cr, x_offset, y_offset,
1059  qpix_op, chroma_op, pixel_shift, chroma_idc);
1060  }
1061 }
1062 
1064  int height, int delta,
1065  uint8_t *dest_y, uint8_t *dest_cb,
1066  uint8_t *dest_cr,
1067  int x_offset, int y_offset,
1068  qpel_mc_func *qpix_put,
1069  h264_chroma_mc_func chroma_put,
1070  h264_weight_func luma_weight_op,
1071  h264_weight_func chroma_weight_op,
1072  h264_biweight_func luma_weight_avg,
1073  h264_biweight_func chroma_weight_avg,
1074  int list0, int list1,
1075  int pixel_shift, int chroma_idc)
1076 {
1077  int chroma_height;
1078 
1079  dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1080  if (chroma_idc == 3 /* yuv444 */) {
1081  chroma_height = height;
1082  chroma_weight_avg = luma_weight_avg;
1083  chroma_weight_op = luma_weight_op;
1084  dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1085  dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1086  } else if (chroma_idc == 2 /* yuv422 */) {
1087  chroma_height = height;
1088  dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1089  dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1090  } else { /* yuv420 */
1091  chroma_height = height >> 1;
1092  dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1093  dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1094  }
1095  x_offset += 8 * h->mb_x;
1096  y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1097 
1098  if (list0 && list1) {
1099  /* don't optimize for luma-only case, since B-frames usually
1100  * use implicit weights => chroma too. */
1101  uint8_t *tmp_cb = h->bipred_scratchpad;
1102  uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1103  uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1104  int refn0 = h->ref_cache[0][scan8[n]];
1105  int refn1 = h->ref_cache[1][scan8[n]];
1106 
1107  mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1108  dest_y, dest_cb, dest_cr,
1109  x_offset, y_offset, qpix_put, chroma_put,
1110  pixel_shift, chroma_idc);
1111  mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1112  tmp_y, tmp_cb, tmp_cr,
1113  x_offset, y_offset, qpix_put, chroma_put,
1114  pixel_shift, chroma_idc);
1115 
1116  if (h->use_weight == 2) {
1117  int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1118  int weight1 = 64 - weight0;
1119  luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1120  height, 5, weight0, weight1, 0);
1121  chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1122  chroma_height, 5, weight0, weight1, 0);
1123  chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1124  chroma_height, 5, weight0, weight1, 0);
1125  } else {
1126  luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1128  h->luma_weight[refn0][0][0],
1129  h->luma_weight[refn1][1][0],
1130  h->luma_weight[refn0][0][1] +
1131  h->luma_weight[refn1][1][1]);
1132  chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1134  h->chroma_weight[refn0][0][0][0],
1135  h->chroma_weight[refn1][1][0][0],
1136  h->chroma_weight[refn0][0][0][1] +
1137  h->chroma_weight[refn1][1][0][1]);
1138  chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1140  h->chroma_weight[refn0][0][1][0],
1141  h->chroma_weight[refn1][1][1][0],
1142  h->chroma_weight[refn0][0][1][1] +
1143  h->chroma_weight[refn1][1][1][1]);
1144  }
1145  } else {
1146  int list = list1 ? 1 : 0;
1147  int refn = h->ref_cache[list][scan8[n]];
1148  Picture *ref = &h->ref_list[list][refn];
1149  mc_dir_part(h, ref, n, square, height, delta, list,
1150  dest_y, dest_cb, dest_cr, x_offset, y_offset,
1151  qpix_put, chroma_put, pixel_shift, chroma_idc);
1152 
1153  luma_weight_op(dest_y, h->mb_linesize, height,
1155  h->luma_weight[refn][list][0],
1156  h->luma_weight[refn][list][1]);
1157  if (h->use_weight_chroma) {
1158  chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1160  h->chroma_weight[refn][list][0][0],
1161  h->chroma_weight[refn][list][0][1]);
1162  chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1164  h->chroma_weight[refn][list][1][0],
1165  h->chroma_weight[refn][list][1][1]);
1166  }
1167  }
1168 }
1169 
1171  int pixel_shift, int chroma_idc)
1172 {
1173  /* fetch pixels for estimated mv 4 macroblocks ahead
1174  * optimized for 64byte cache lines */
1175  const int refn = h->ref_cache[list][scan8[0]];
1176  if (refn >= 0) {
1177  const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1178  const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1179  uint8_t **src = h->ref_list[list][refn].f.data;
1180  int off = (mx << pixel_shift) +
1181  (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1182  (64 << pixel_shift);
1183  h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1184  if (chroma_idc == 3 /* yuv444 */) {
1185  h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1186  h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1187  } else {
1188  off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
1189  h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1190  }
1191  }
1192 }
1193 
1194 static void free_tables(H264Context *h, int free_rbsp)
1195 {
1196  int i;
1197  H264Context *hx;
1198 
1201  av_freep(&h->cbp_table);
1202  av_freep(&h->mvd_table[0]);
1203  av_freep(&h->mvd_table[1]);
1204  av_freep(&h->direct_table);
1205  av_freep(&h->non_zero_count);
1207  h->slice_table = NULL;
1208  av_freep(&h->list_counts);
1209 
1210  av_freep(&h->mb2b_xy);
1211  av_freep(&h->mb2br_xy);
1212 
1213  for (i = 0; i < 3; i++)
1215 
1220 
1221  if (free_rbsp && h->DPB) {
1222  for (i = 0; i < MAX_PICTURE_COUNT; i++)
1223  unref_picture(h, &h->DPB[i]);
1224  av_freep(&h->DPB);
1225  } else if (h->DPB) {
1226  for (i = 0; i < MAX_PICTURE_COUNT; i++)
1227  h->DPB[i].needs_realloc = 1;
1228  }
1229 
1230  h->cur_pic_ptr = NULL;
1231 
1232  for (i = 0; i < MAX_THREADS; i++) {
1233  hx = h->thread_context[i];
1234  if (!hx)
1235  continue;
1236  av_freep(&hx->top_borders[1]);
1237  av_freep(&hx->top_borders[0]);
1239  av_freep(&hx->edge_emu_buffer);
1240  av_freep(&hx->dc_val_base);
1241  av_freep(&hx->me.scratchpad);
1242  av_freep(&hx->er.mb_index2xy);
1244  av_freep(&hx->er.er_temp_buffer);
1245  av_freep(&hx->er.mbintra_table);
1246  av_freep(&hx->er.mbskip_table);
1247 
1248  if (free_rbsp) {
1249  av_freep(&hx->rbsp_buffer[1]);
1250  av_freep(&hx->rbsp_buffer[0]);
1251  hx->rbsp_buffer_size[0] = 0;
1252  hx->rbsp_buffer_size[1] = 0;
1253  }
1254  if (i)
1255  av_freep(&h->thread_context[i]);
1256  }
1257 }
1258 
1260 {
1261  int i, j, q, x;
1262  const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1263 
1264  for (i = 0; i < 6; i++) {
1265  h->dequant8_coeff[i] = h->dequant8_buffer[i];
1266  for (j = 0; j < i; j++)
1267  if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1268  64 * sizeof(uint8_t))) {
1269  h->dequant8_coeff[i] = h->dequant8_buffer[j];
1270  break;
1271  }
1272  if (j < i)
1273  continue;
1274 
1275  for (q = 0; q < max_qp + 1; q++) {
1276  int shift = div6[q];
1277  int idx = rem6[q];
1278  for (x = 0; x < 64; x++)
1279  h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1280  ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1281  h->pps.scaling_matrix8[i][x]) << shift;
1282  }
1283  }
1284 }
1285 
1287 {
1288  int i, j, q, x;
1289  const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1290  for (i = 0; i < 6; i++) {
1291  h->dequant4_coeff[i] = h->dequant4_buffer[i];
1292  for (j = 0; j < i; j++)
1293  if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1294  16 * sizeof(uint8_t))) {
1295  h->dequant4_coeff[i] = h->dequant4_buffer[j];
1296  break;
1297  }
1298  if (j < i)
1299  continue;
1300 
1301  for (q = 0; q < max_qp + 1; q++) {
1302  int shift = div6[q] + 2;
1303  int idx = rem6[q];
1304  for (x = 0; x < 16; x++)
1305  h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1306  ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1307  h->pps.scaling_matrix4[i][x]) << shift;
1308  }
1309  }
1310 }
1311 
1313 {
1314  int i, x;
1316  if (h->pps.transform_8x8_mode)
1318  if (h->sps.transform_bypass) {
1319  for (i = 0; i < 6; i++)
1320  for (x = 0; x < 16; x++)
1321  h->dequant4_coeff[i][0][x] = 1 << 6;
1323  for (i = 0; i < 6; i++)
1324  for (x = 0; x < 64; x++)
1325  h->dequant8_coeff[i][0][x] = 1 << 6;
1326  }
1327 }
1328 
1330 {
1331  const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1332  const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1333  int x, y, i;
1334 
1336  row_mb_num * 8 * sizeof(uint8_t), fail)
1338  big_mb_num * 48 * sizeof(uint8_t), fail)
1340  (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1342  big_mb_num * sizeof(uint16_t), fail)
1344  big_mb_num * sizeof(uint8_t), fail)
1345  FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1346  16 * row_mb_num * sizeof(uint8_t), fail);
1347  FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1348  16 * row_mb_num * sizeof(uint8_t), fail);
1350  4 * big_mb_num * sizeof(uint8_t), fail);
1352  big_mb_num * sizeof(uint8_t), fail)
1353 
1354  memset(h->slice_table_base, -1,
1355  (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1356  h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1357 
1359  big_mb_num * sizeof(uint32_t), fail);
1361  big_mb_num * sizeof(uint32_t), fail);
1362  for (y = 0; y < h->mb_height; y++)
1363  for (x = 0; x < h->mb_width; x++) {
1364  const int mb_xy = x + y * h->mb_stride;
1365  const int b_xy = 4 * x + 4 * y * h->b_stride;
1366 
1367  h->mb2b_xy[mb_xy] = b_xy;
1368  h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1369  }
1370 
1371  if (!h->dequant4_coeff[0])
1373 
1374  if (!h->DPB) {
1375  h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1376  if (!h->DPB)
1377  return AVERROR(ENOMEM);
1378  for (i = 0; i < MAX_PICTURE_COUNT; i++)
1381  }
1382 
1383  return 0;
1384 
1385 fail:
1386  free_tables(h, 1);
1387  return AVERROR(ENOMEM);
1388 }
1389 
1390 /**
1391  * Mimic alloc_tables(), but for every context thread.
1392  */
1393 static void clone_tables(H264Context *dst, H264Context *src, int i)
1394 {
1395  dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1396  dst->non_zero_count = src->non_zero_count;
1397  dst->slice_table = src->slice_table;
1398  dst->cbp_table = src->cbp_table;
1399  dst->mb2b_xy = src->mb2b_xy;
1400  dst->mb2br_xy = src->mb2br_xy;
1402  dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1403  dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1404  dst->direct_table = src->direct_table;
1405  dst->list_counts = src->list_counts;
1406  dst->DPB = src->DPB;
1407  dst->cur_pic_ptr = src->cur_pic_ptr;
1408  dst->cur_pic = src->cur_pic;
1409  dst->bipred_scratchpad = NULL;
1410  dst->edge_emu_buffer = NULL;
1411  dst->me.scratchpad = NULL;
1413  src->sps.chroma_format_idc);
1414 }
1415 
1416 /**
1417  * Init context
1418  * Allocate buffers which are not shared amongst multiple threads.
1419  */
1421 {
1422  ERContext *er = &h->er;
1423  int mb_array_size = h->mb_height * h->mb_stride;
1424  int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1425  int c_size = h->mb_stride * (h->mb_height + 1);
1426  int yc_size = y_size + 2 * c_size;
1427  int x, y, i;
1428 
1430  h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1432  h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1433 
1434  h->ref_cache[0][scan8[5] + 1] =
1435  h->ref_cache[0][scan8[7] + 1] =
1436  h->ref_cache[0][scan8[13] + 1] =
1437  h->ref_cache[1][scan8[5] + 1] =
1438  h->ref_cache[1][scan8[7] + 1] =
1439  h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1440 
1441  if (CONFIG_ERROR_RESILIENCE) {
1442  /* init ER */
1443  er->avctx = h->avctx;
1444  er->dsp = &h->dsp;
1446  er->opaque = h;
1447  er->quarter_sample = 1;
1448 
1449  er->mb_num = h->mb_num;
1450  er->mb_width = h->mb_width;
1451  er->mb_height = h->mb_height;
1452  er->mb_stride = h->mb_stride;
1453  er->b8_stride = h->mb_width * 2 + 1;
1454 
1455  FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1456  fail); // error ressilience code looks cleaner with this
1457  for (y = 0; y < h->mb_height; y++)
1458  for (x = 0; x < h->mb_width; x++)
1459  er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1460 
1461  er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1462  h->mb_stride + h->mb_width;
1463 
1465  mb_array_size * sizeof(uint8_t), fail);
1466 
1467  FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1468  memset(er->mbintra_table, 1, mb_array_size);
1469 
1470  FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1471 
1473  fail);
1474 
1475  FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1476  er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1477  er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1478  er->dc_val[2] = er->dc_val[1] + c_size;
1479  for (i = 0; i < yc_size; i++)
1480  h->dc_val_base[i] = 1024;
1481  }
1482 
1483  return 0;
1484 
1485 fail:
1486  return AVERROR(ENOMEM); // free_tables will clean up for us
1487 }
1488 
1489 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1490  int parse_extradata);
1491 
1493 {
1494  AVCodecContext *avctx = h->avctx;
1495  int ret;
1496 
1497  if (!buf || size <= 0)
1498  return -1;
1499 
1500  if (buf[0] == 1) {
1501  int i, cnt, nalsize;
1502  const unsigned char *p = buf;
1503 
1504  h->is_avc = 1;
1505 
1506  if (size < 7) {
1507  av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1508  return AVERROR_INVALIDDATA;
1509  }
1510  /* sps and pps in the avcC always have length coded with 2 bytes,
1511  * so put a fake nal_length_size = 2 while parsing them */
1512  h->nal_length_size = 2;
1513  // Decode sps from avcC
1514  cnt = *(p + 5) & 0x1f; // Number of sps
1515  p += 6;
1516  for (i = 0; i < cnt; i++) {
1517  nalsize = AV_RB16(p) + 2;
1518  if(nalsize > size - (p-buf))
1519  return AVERROR_INVALIDDATA;
1520  ret = decode_nal_units(h, p, nalsize, 1);
1521  if (ret < 0) {
1522  av_log(avctx, AV_LOG_ERROR,
1523  "Decoding sps %d from avcC failed\n", i);
1524  return ret;
1525  }
1526  p += nalsize;
1527  }
1528  // Decode pps from avcC
1529  cnt = *(p++); // Number of pps
1530  for (i = 0; i < cnt; i++) {
1531  nalsize = AV_RB16(p) + 2;
1532  if(nalsize > size - (p-buf))
1533  return AVERROR_INVALIDDATA;
1534  ret = decode_nal_units(h, p, nalsize, 1);
1535  if (ret < 0) {
1536  av_log(avctx, AV_LOG_ERROR,
1537  "Decoding pps %d from avcC failed\n", i);
1538  return ret;
1539  }
1540  p += nalsize;
1541  }
1542  // Now store right nal length size, that will be used to parse all other nals
1543  h->nal_length_size = (buf[4] & 0x03) + 1;
1544  } else {
1545  h->is_avc = 0;
1546  ret = decode_nal_units(h, buf, size, 1);
1547  if (ret < 0)
1548  return ret;
1549  }
1550  return size;
1551 }
1552 
1554 {
1555  H264Context *h = avctx->priv_data;
1556  int i;
1557  int ret;
1558 
1559  h->avctx = avctx;
1560 
1561  h->bit_depth_luma = 8;
1562  h->chroma_format_idc = 1;
1563 
1564  h->avctx->bits_per_raw_sample = 8;
1565  h->cur_chroma_format_idc = 1;
1566 
1567  ff_h264dsp_init(&h->h264dsp, 8, 1);
1568  av_assert0(h->sps.bit_depth_chroma == 0);
1570  ff_h264qpel_init(&h->h264qpel, 8);
1571  ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1572 
1573  h->dequant_coeff_pps = -1;
1574  h->current_sps_id = -1;
1575 
1576  /* needed so that IDCT permutation is known early */
1577  if (CONFIG_ERROR_RESILIENCE)
1578  ff_dsputil_init(&h->dsp, h->avctx);
1579  ff_videodsp_init(&h->vdsp, 8);
1580 
1581  memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1582  memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1583 
1585  h->slice_context_count = 1;
1586  h->workaround_bugs = avctx->workaround_bugs;
1587  h->flags = avctx->flags;
1588 
1589  /* set defaults */
1590  // s->decode_mb = ff_h263_decode_mb;
1591  if (!avctx->has_b_frames)
1592  h->low_delay = 1;
1593 
1595 
1597 
1599 
1600  h->pixel_shift = 0;
1601  h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1602 
1603  h->thread_context[0] = h;
1604  h->outputed_poc = h->next_outputed_poc = INT_MIN;
1605  for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1606  h->last_pocs[i] = INT_MIN;
1607  h->prev_poc_msb = 1 << 16;
1608  h->prev_frame_num = -1;
1609  h->x264_build = -1;
1611  ff_h264_reset_sei(h);
1612  if (avctx->codec_id == AV_CODEC_ID_H264) {
1613  if (avctx->ticks_per_frame == 1) {
1614  if(h->avctx->time_base.den < INT_MAX/2) {
1615  h->avctx->time_base.den *= 2;
1616  } else
1617  h->avctx->time_base.num /= 2;
1618  }
1619  avctx->ticks_per_frame = 2;
1620  }
1621 
1622  if (avctx->extradata_size > 0 && avctx->extradata) {
1623  ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
1624  if (ret < 0) {
1626  return ret;
1627  }
1628  }
1629 
1633  h->low_delay = 0;
1634  }
1635 
1636  avctx->internal->allocate_progress = 1;
1637 
1638  flush_change(h);
1639 
1640  return 0;
1641 }
1642 
1643 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1644 #undef REBASE_PICTURE
1645 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1646  ((pic && pic >= old_ctx->DPB && \
1647  pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1648  &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1649 
1651  H264Context *new_base,
1652  H264Context *old_base)
1653 {
1654  int i;
1655 
1656  for (i = 0; i < count; i++) {
1657  assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1658  IN_RANGE(from[i], old_base->DPB,
1659  sizeof(Picture) * MAX_PICTURE_COUNT) ||
1660  !from[i]));
1661  to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1662  }
1663 }
1664 
1665 static void copy_parameter_set(void **to, void **from, int count, int size)
1666 {
1667  int i;
1668 
1669  for (i = 0; i < count; i++) {
1670  if (to[i] && !from[i])
1671  av_freep(&to[i]);
1672  else if (from[i] && !to[i])
1673  to[i] = av_malloc(size);
1674 
1675  if (from[i])
1676  memcpy(to[i], from[i], size);
1677  }
1678 }
1679 
1681 {
1682  H264Context *h = avctx->priv_data;
1683 
1684  if (!avctx->internal->is_copy)
1685  return 0;
1686  memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1687  memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1688 
1689  h->rbsp_buffer[0] = NULL;
1690  h->rbsp_buffer[1] = NULL;
1691  h->rbsp_buffer_size[0] = 0;
1692  h->rbsp_buffer_size[1] = 0;
1693  h->context_initialized = 0;
1694 
1695  return 0;
1696 }
1697 
1698 #define copy_fields(to, from, start_field, end_field) \
1699  memcpy(&to->start_field, &from->start_field, \
1700  (char *)&to->end_field - (char *)&to->start_field)
1701 
1702 static int h264_slice_header_init(H264Context *, int);
1703 
1705 
1707  const AVCodecContext *src)
1708 {
1709  H264Context *h = dst->priv_data, *h1 = src->priv_data;
1710  int inited = h->context_initialized, err = 0;
1711  int context_reinitialized = 0;
1712  int i, ret;
1713 
1714  if (dst == src)
1715  return 0;
1716 
1717  if (inited &&
1718  (h->width != h1->width ||
1719  h->height != h1->height ||
1720  h->mb_width != h1->mb_width ||
1721  h->mb_height != h1->mb_height ||
1722  h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1723  h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1724  h->sps.colorspace != h1->sps.colorspace)) {
1725 
1726  /* set bits_per_raw_sample to the previous value. the check for changed
1727  * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1728  * the current value */
1730 
1732 
1733  h->width = h1->width;
1734  h->height = h1->height;
1735  h->mb_height = h1->mb_height;
1736  h->mb_width = h1->mb_width;
1737  h->mb_num = h1->mb_num;
1738  h->mb_stride = h1->mb_stride;
1739  h->b_stride = h1->b_stride;
1740  // SPS/PPS
1741  copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1742  MAX_SPS_COUNT, sizeof(SPS));
1743  h->sps = h1->sps;
1744  copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1745  MAX_PPS_COUNT, sizeof(PPS));
1746  h->pps = h1->pps;
1747 
1748  if ((err = h264_slice_header_init(h, 1)) < 0) {
1749  av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1750  return err;
1751  }
1752  context_reinitialized = 1;
1753 
1754 #if 0
1756  //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1757  h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1758 #endif
1759  }
1760  /* update linesize on resize for h264. The h264 decoder doesn't
1761  * necessarily call ff_MPV_frame_start in the new thread */
1762  h->linesize = h1->linesize;
1763  h->uvlinesize = h1->uvlinesize;
1764 
1765  /* copy block_offset since frame_start may not be called */
1766  memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1767 
1768  if (!inited) {
1769  for (i = 0; i < MAX_SPS_COUNT; i++)
1770  av_freep(h->sps_buffers + i);
1771 
1772  for (i = 0; i < MAX_PPS_COUNT; i++)
1773  av_freep(h->pps_buffers + i);
1774 
1775  av_freep(&h->rbsp_buffer[0]);
1776  av_freep(&h->rbsp_buffer[1]);
1777  memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1778  memcpy(&h->cabac, &h1->cabac,
1779  sizeof(H264Context) - offsetof(H264Context, cabac));
1780  av_assert0((void*)&h->cabac == &h->mb_padding + 1);
1781 
1782  memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1783  memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1784 
1785  memset(&h->er, 0, sizeof(h->er));
1786  memset(&h->me, 0, sizeof(h->me));
1787  memset(&h->mb, 0, sizeof(h->mb));
1788  memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1789  memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1790 
1791  h->avctx = dst;
1792  h->DPB = NULL;
1793  h->qscale_table_pool = NULL;
1794  h->mb_type_pool = NULL;
1795  h->ref_index_pool = NULL;
1796  h->motion_val_pool = NULL;
1797  for (i = 0; i < 2; i++) {
1798  h->rbsp_buffer[i] = NULL;
1799  h->rbsp_buffer_size[i] = 0;
1800  }
1801 
1802  if (h1->context_initialized) {
1803  h->context_initialized = 0;
1804 
1805  memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1807  h->cur_pic.tf.f = &h->cur_pic.f;
1808 
1809  ret = ff_h264_alloc_tables(h);
1810  if (ret < 0) {
1811  av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1812  return ret;
1813  }
1814  ret = context_init(h);
1815  if (ret < 0) {
1816  av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1817  return ret;
1818  }
1819  }
1820 
1821  h->bipred_scratchpad = NULL;
1822  h->edge_emu_buffer = NULL;
1823 
1824  h->thread_context[0] = h;
1825  h->context_initialized = h1->context_initialized;
1826  }
1827 
1828  h->avctx->coded_height = h1->avctx->coded_height;
1829  h->avctx->coded_width = h1->avctx->coded_width;
1830  h->avctx->width = h1->avctx->width;
1831  h->avctx->height = h1->avctx->height;
1832  h->coded_picture_number = h1->coded_picture_number;
1833  h->first_field = h1->first_field;
1834  h->picture_structure = h1->picture_structure;
1835  h->qscale = h1->qscale;
1836  h->droppable = h1->droppable;
1837  h->data_partitioning = h1->data_partitioning;
1838  h->low_delay = h1->low_delay;
1839 
1840  for (i = 0; h->DPB && i < MAX_PICTURE_COUNT; i++) {
1841  unref_picture(h, &h->DPB[i]);
1842  if (h1->DPB && h1->DPB[i].f.data[0] &&
1843  (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1844  return ret;
1845  }
1846 
1847  h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1848  unref_picture(h, &h->cur_pic);
1849  if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1850  return ret;
1851 
1852  h->workaround_bugs = h1->workaround_bugs;
1853  h->low_delay = h1->low_delay;
1854  h->droppable = h1->droppable;
1855 
1856  // extradata/NAL handling
1857  h->is_avc = h1->is_avc;
1858 
1859  // SPS/PPS
1860  copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1861  MAX_SPS_COUNT, sizeof(SPS));
1862  h->sps = h1->sps;
1863  copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1864  MAX_PPS_COUNT, sizeof(PPS));
1865  h->pps = h1->pps;
1866 
1867  // Dequantization matrices
1868  // FIXME these are big - can they be only copied when PPS changes?
1869  copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1870 
1871  for (i = 0; i < 6; i++)
1872  h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1873  (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1874 
1875  for (i = 0; i < 6; i++)
1876  h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1877  (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1878 
1879  h->dequant_coeff_pps = h1->dequant_coeff_pps;
1880 
1881  // POC timing
1882  copy_fields(h, h1, poc_lsb, redundant_pic_count);
1883 
1884  // reference lists
1885  copy_fields(h, h1, short_ref, cabac_init_idc);
1886 
1887  copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1888  copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1889  copy_picture_range(h->delayed_pic, h1->delayed_pic,
1890  MAX_DELAYED_PIC_COUNT + 2, h, h1);
1891 
1892  h->sync = h1->sync;
1893 
1894  if (context_reinitialized)
1896 
1897  if (!h->cur_pic_ptr)
1898  return 0;
1899 
1900  if (!h->droppable) {
1902  h->prev_poc_msb = h->poc_msb;
1903  h->prev_poc_lsb = h->poc_lsb;
1904  }
1906  h->prev_frame_num = h->frame_num;
1908 
1909  return err;
1910 }
1911 
1913 {
1914  Picture *pic;
1915  int i, ret;
1916  const int pixel_shift = h->pixel_shift;
1917  int c[4] = {
1918  1<<(h->sps.bit_depth_luma-1),
1919  1<<(h->sps.bit_depth_chroma-1),
1920  1<<(h->sps.bit_depth_chroma-1),
1921  -1
1922  };
1923 
1924  if (!ff_thread_can_start_frame(h->avctx)) {
1925  av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1926  return -1;
1927  }
1928 
1930  h->cur_pic_ptr = NULL;
1931 
1932  i = find_unused_picture(h);
1933  if (i < 0) {
1934  av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1935  return i;
1936  }
1937  pic = &h->DPB[i];
1938 
1939  pic->reference = h->droppable ? 0 : h->picture_structure;
1942 
1943  /*
1944  * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1945  * in later.
1946  * See decode_nal_units().
1947  */
1948  pic->f.key_frame = 0;
1949  pic->sync = 0;
1950  pic->mmco_reset = 0;
1951 
1952  if ((ret = alloc_picture(h, pic)) < 0)
1953  return ret;
1954  if(!h->sync && !h->avctx->hwaccel &&
1955  !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1956  avpriv_color_frame(&pic->f, c);
1957 
1958  h->cur_pic_ptr = pic;
1959  unref_picture(h, &h->cur_pic);
1960  if (CONFIG_ERROR_RESILIENCE) {
1961  h->er.cur_pic = NULL;
1962  }
1963 
1964  if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1965  return ret;
1966 
1967  if (CONFIG_ERROR_RESILIENCE) {
1968  ff_er_frame_start(&h->er);
1969  h->er.last_pic =
1970  h->er.next_pic = NULL;
1971  }
1972 
1973  assert(h->linesize && h->uvlinesize);
1974 
1975  for (i = 0; i < 16; i++) {
1976  h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1977  h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1978  }
1979  for (i = 0; i < 16; i++) {
1980  h->block_offset[16 + i] =
1981  h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1982  h->block_offset[48 + 16 + i] =
1983  h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1984  }
1985 
1986  // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1987  // h->cur_pic.reference /* || h->contains_intra */ || 1;
1988 
1989  /* We mark the current picture as non-reference after allocating it, so
1990  * that if we break out due to an error it can be released automatically
1991  * in the next ff_MPV_frame_start().
1992  */
1993  h->cur_pic_ptr->reference = 0;
1994 
1995  h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1996 
1997  h->next_output_pic = NULL;
1998 
1999  assert(h->cur_pic_ptr->long_ref == 0);
2000 
2001  return 0;
2002 }
2003 
2004 /**
2005  * Run setup operations that must be run after slice header decoding.
2006  * This includes finding the next displayed frame.
2007  *
2008  * @param h h264 master context
2009  * @param setup_finished enough NALs have been read that we can call
2010  * ff_thread_finish_setup()
2011  */
2012 static void decode_postinit(H264Context *h, int setup_finished)
2013 {
2014  Picture *out = h->cur_pic_ptr;
2015  Picture *cur = h->cur_pic_ptr;
2016  int i, pics, out_of_order, out_idx;
2017 
2018  h->cur_pic_ptr->f.pict_type = h->pict_type;
2019 
2020  if (h->next_output_pic)
2021  return;
2022 
2023  if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2024  /* FIXME: if we have two PAFF fields in one packet, we can't start
2025  * the next thread here. If we have one field per packet, we can.
2026  * The check in decode_nal_units() is not good enough to find this
2027  * yet, so we assume the worst for now. */
2028  // if (setup_finished)
2029  // ff_thread_finish_setup(h->avctx);
2030  return;
2031  }
2032 
2033  cur->f.interlaced_frame = 0;
2034  cur->f.repeat_pict = 0;
2035 
2036  /* Signal interlacing information externally. */
2037  /* Prioritize picture timing SEI information over used
2038  * decoding process if it exists. */
2039 
2040  if (h->sps.pic_struct_present_flag) {
2041  switch (h->sei_pic_struct) {
2042  case SEI_PIC_STRUCT_FRAME:
2043  break;
2046  cur->f.interlaced_frame = 1;
2047  break;
2050  if (FIELD_OR_MBAFF_PICTURE(h))
2051  cur->f.interlaced_frame = 1;
2052  else
2053  // try to flag soft telecine progressive
2055  break;
2058  /* Signal the possibility of telecined film externally
2059  * (pic_struct 5,6). From these hints, let the applications
2060  * decide if they apply deinterlacing. */
2061  cur->f.repeat_pict = 1;
2062  break;
2064  cur->f.repeat_pict = 2;
2065  break;
2067  cur->f.repeat_pict = 4;
2068  break;
2069  }
2070 
2071  if ((h->sei_ct_type & 3) &&
2073  cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2074  } else {
2075  /* Derive interlacing flag from used decoding process. */
2077  }
2079 
2080  if (cur->field_poc[0] != cur->field_poc[1]) {
2081  /* Derive top_field_first from field pocs. */
2082  cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2083  } else {
2084  if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2085  /* Use picture timing SEI information. Even if it is a
2086  * information of a past frame, better than nothing. */
2089  cur->f.top_field_first = 1;
2090  else
2091  cur->f.top_field_first = 0;
2092  } else {
2093  /* Most likely progressive */
2094  cur->f.top_field_first = 0;
2095  }
2096  }
2097 
2098  cur->mmco_reset = h->mmco_reset;
2099  h->mmco_reset = 0;
2100  // FIXME do something with unavailable reference frames
2101 
2102  /* Sort B-frames into display order */
2103 
2107  h->low_delay = 0;
2108  }
2109 
2113  h->low_delay = 0;
2114  }
2115 
2116  for (i = 0; 1; i++) {
2117  if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2118  if(i)
2119  h->last_pocs[i-1] = cur->poc;
2120  break;
2121  } else if(i) {
2122  h->last_pocs[i-1]= h->last_pocs[i];
2123  }
2124  }
2125  out_of_order = MAX_DELAYED_PIC_COUNT - i;
2126  if( cur->f.pict_type == AV_PICTURE_TYPE_B
2128  out_of_order = FFMAX(out_of_order, 1);
2129  if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2130  av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2131  for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2132  h->last_pocs[i] = INT_MIN;
2133  h->last_pocs[0] = cur->poc;
2134  cur->mmco_reset = 1;
2135  } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2136  av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2137  h->avctx->has_b_frames = out_of_order;
2138  h->low_delay = 0;
2139  }
2140 
2141  pics = 0;
2142  while (h->delayed_pic[pics])
2143  pics++;
2144 
2146 
2147  h->delayed_pic[pics++] = cur;
2148  if (cur->reference == 0)
2149  cur->reference = DELAYED_PIC_REF;
2150 
2151  out = h->delayed_pic[0];
2152  out_idx = 0;
2153  for (i = 1; h->delayed_pic[i] &&
2154  !h->delayed_pic[i]->f.key_frame &&
2155  !h->delayed_pic[i]->mmco_reset;
2156  i++)
2157  if (h->delayed_pic[i]->poc < out->poc) {
2158  out = h->delayed_pic[i];
2159  out_idx = i;
2160  }
2161  if (h->avctx->has_b_frames == 0 &&
2162  (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2163  h->next_outputed_poc = INT_MIN;
2164  out_of_order = out->poc < h->next_outputed_poc;
2165 
2166  if (out_of_order || pics > h->avctx->has_b_frames) {
2167  out->reference &= ~DELAYED_PIC_REF;
2168  // for frame threading, the owner must be the second field's thread or
2169  // else the first thread can release the picture and reuse it unsafely
2170  for (i = out_idx; h->delayed_pic[i]; i++)
2171  h->delayed_pic[i] = h->delayed_pic[i + 1];
2172  }
2173  if (!out_of_order && pics > h->avctx->has_b_frames) {
2174  h->next_output_pic = out;
2175  if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2176  h->next_outputed_poc = INT_MIN;
2177  } else
2178  h->next_outputed_poc = out->poc;
2179  } else {
2180  av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2181  }
2182 
2183  if (h->next_output_pic && h->next_output_pic->sync) {
2184  h->sync |= 2;
2185  }
2186 
2187  if (setup_finished && !h->avctx->hwaccel)
2189 }
2190 
2192  uint8_t *src_cb, uint8_t *src_cr,
2193  int linesize, int uvlinesize,
2194  int simple)
2195 {
2196  uint8_t *top_border;
2197  int top_idx = 1;
2198  const int pixel_shift = h->pixel_shift;
2199  int chroma444 = CHROMA444(h);
2200  int chroma422 = CHROMA422(h);
2201 
2202  src_y -= linesize;
2203  src_cb -= uvlinesize;
2204  src_cr -= uvlinesize;
2205 
2206  if (!simple && FRAME_MBAFF(h)) {
2207  if (h->mb_y & 1) {
2208  if (!MB_MBAFF(h)) {
2209  top_border = h->top_borders[0][h->mb_x];
2210  AV_COPY128(top_border, src_y + 15 * linesize);
2211  if (pixel_shift)
2212  AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2213  if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2214  if (chroma444) {
2215  if (pixel_shift) {
2216  AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2217  AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2218  AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2219  AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2220  } else {
2221  AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2222  AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2223  }
2224  } else if (chroma422) {
2225  if (pixel_shift) {
2226  AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2227  AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2228  } else {
2229  AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2230  AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2231  }
2232  } else {
2233  if (pixel_shift) {
2234  AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2235  AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2236  } else {
2237  AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2238  AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2239  }
2240  }
2241  }
2242  }
2243  } else if (MB_MBAFF(h)) {
2244  top_idx = 0;
2245  } else
2246  return;
2247  }
2248 
2249  top_border = h->top_borders[top_idx][h->mb_x];
2250  /* There are two lines saved, the line above the top macroblock
2251  * of a pair, and the line above the bottom macroblock. */
2252  AV_COPY128(top_border, src_y + 16 * linesize);
2253  if (pixel_shift)
2254  AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2255 
2256  if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2257  if (chroma444) {
2258  if (pixel_shift) {
2259  AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2260  AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2261  AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2262  AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2263  } else {
2264  AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2265  AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2266  }
2267  } else if (chroma422) {
2268  if (pixel_shift) {
2269  AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2270  AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2271  } else {
2272  AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2273  AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2274  }
2275  } else {
2276  if (pixel_shift) {
2277  AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2278  AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2279  } else {
2280  AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2281  AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2282  }
2283  }
2284  }
2285 }
2286 
2288  uint8_t *src_cb, uint8_t *src_cr,
2289  int linesize, int uvlinesize,
2290  int xchg, int chroma444,
2291  int simple, int pixel_shift)
2292 {
2293  int deblock_topleft;
2294  int deblock_top;
2295  int top_idx = 1;
2296  uint8_t *top_border_m1;
2297  uint8_t *top_border;
2298 
2299  if (!simple && FRAME_MBAFF(h)) {
2300  if (h->mb_y & 1) {
2301  if (!MB_MBAFF(h))
2302  return;
2303  } else {
2304  top_idx = MB_MBAFF(h) ? 0 : 1;
2305  }
2306  }
2307 
2308  if (h->deblocking_filter == 2) {
2309  deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2310  deblock_top = h->top_type;
2311  } else {
2312  deblock_topleft = (h->mb_x > 0);
2313  deblock_top = (h->mb_y > !!MB_FIELD(h));
2314  }
2315 
2316  src_y -= linesize + 1 + pixel_shift;
2317  src_cb -= uvlinesize + 1 + pixel_shift;
2318  src_cr -= uvlinesize + 1 + pixel_shift;
2319 
2320  top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2321  top_border = h->top_borders[top_idx][h->mb_x];
2322 
2323 #define XCHG(a, b, xchg) \
2324  if (pixel_shift) { \
2325  if (xchg) { \
2326  AV_SWAP64(b + 0, a + 0); \
2327  AV_SWAP64(b + 8, a + 8); \
2328  } else { \
2329  AV_COPY128(b, a); \
2330  } \
2331  } else if (xchg) \
2332  AV_SWAP64(b, a); \
2333  else \
2334  AV_COPY64(b, a);
2335 
2336  if (deblock_top) {
2337  if (deblock_topleft) {
2338  XCHG(top_border_m1 + (8 << pixel_shift),
2339  src_y - (7 << pixel_shift), 1);
2340  }
2341  XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2342  XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2343  if (h->mb_x + 1 < h->mb_width) {
2344  XCHG(h->top_borders[top_idx][h->mb_x + 1],
2345  src_y + (17 << pixel_shift), 1);
2346  }
2347  if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2348  if (chroma444) {
2349  if (deblock_topleft) {
2350  XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2351  XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2352  }
2353  XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2354  XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2355  XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2356  XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2357  if (h->mb_x + 1 < h->mb_width) {
2358  XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2359  XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2360  }
2361  } else {
2362  if (deblock_topleft) {
2363  XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2364  XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2365  }
2366  XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2367  XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2368  }
2369  }
2370  }
2371 }
2372 
2373 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2374  int index)
2375 {
2376  if (high_bit_depth) {
2377  return AV_RN32A(((int32_t *)mb) + index);
2378  } else
2379  return AV_RN16A(mb + index);
2380 }
2381 
2382 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2383  int index, int value)
2384 {
2385  if (high_bit_depth) {
2386  AV_WN32A(((int32_t *)mb) + index, value);
2387  } else
2388  AV_WN16A(mb + index, value);
2389 }
2390 
2392  int mb_type, int is_h264,
2393  int simple,
2394  int transform_bypass,
2395  int pixel_shift,
2396  int *block_offset,
2397  int linesize,
2398  uint8_t *dest_y, int p)
2399 {
2400  void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2401  void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2402  int i;
2403  int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2404  block_offset += 16 * p;
2405  if (IS_INTRA4x4(mb_type)) {
2406  if (IS_8x8DCT(mb_type)) {
2407  if (transform_bypass) {
2408  idct_dc_add =
2410  } else {
2411  idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2413  }
2414  for (i = 0; i < 16; i += 4) {
2415  uint8_t *const ptr = dest_y + block_offset[i];
2416  const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2417  if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2418  h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2419  } else {
2420  const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2421  h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2422  (h->topright_samples_available << i) & 0x4000, linesize);
2423  if (nnz) {
2424  if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2425  idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2426  else
2427  idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2428  }
2429  }
2430  }
2431  } else {
2432  if (transform_bypass) {
2433  idct_dc_add =
2435  } else {
2436  idct_dc_add = h->h264dsp.h264_idct_dc_add;
2438  }
2439  for (i = 0; i < 16; i++) {
2440  uint8_t *const ptr = dest_y + block_offset[i];
2441  const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2442 
2443  if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2444  h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2445  } else {
2446  uint8_t *topright;
2447  int nnz, tr;
2448  uint64_t tr_high;
2449  if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2450  const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2451  av_assert2(h->mb_y || linesize <= block_offset[i]);
2452  if (!topright_avail) {
2453  if (pixel_shift) {
2454  tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2455  topright = (uint8_t *)&tr_high;
2456  } else {
2457  tr = ptr[3 - linesize] * 0x01010101u;
2458  topright = (uint8_t *)&tr;
2459  }
2460  } else
2461  topright = ptr + (4 << pixel_shift) - linesize;
2462  } else
2463  topright = NULL;
2464 
2465  h->hpc.pred4x4[dir](ptr, topright, linesize);
2466  nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2467  if (nnz) {
2468  if (is_h264) {
2469  if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2470  idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2471  else
2472  idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2473  } else if (CONFIG_SVQ3_DECODER)
2474  ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2475  }
2476  }
2477  }
2478  }
2479  } else {
2480  h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2481  if (is_h264) {
2483  if (!transform_bypass)
2484  h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2485  h->mb_luma_dc[p],
2486  h->dequant4_coeff[p][qscale][0]);
2487  else {
2488  static const uint8_t dc_mapping[16] = {
2489  0 * 16, 1 * 16, 4 * 16, 5 * 16,
2490  2 * 16, 3 * 16, 6 * 16, 7 * 16,
2491  8 * 16, 9 * 16, 12 * 16, 13 * 16,
2492  10 * 16, 11 * 16, 14 * 16, 15 * 16
2493  };
2494  for (i = 0; i < 16; i++)
2495  dctcoef_set(h->mb + (p * 256 << pixel_shift),
2496  pixel_shift, dc_mapping[i],
2497  dctcoef_get(h->mb_luma_dc[p],
2498  pixel_shift, i));
2499  }
2500  }
2501  } else if (CONFIG_SVQ3_DECODER)
2502  ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2503  h->mb_luma_dc[p], qscale);
2504  }
2505 }
2506 
2508  int is_h264, int simple,
2509  int transform_bypass,
2510  int pixel_shift,
2511  int *block_offset,
2512  int linesize,
2513  uint8_t *dest_y, int p)
2514 {
2515  void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2516  int i;
2517  block_offset += 16 * p;
2518  if (!IS_INTRA4x4(mb_type)) {
2519  if (is_h264) {
2520  if (IS_INTRA16x16(mb_type)) {
2521  if (transform_bypass) {
2522  if (h->sps.profile_idc == 244 &&
2525  h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2526  h->mb + (p * 256 << pixel_shift),
2527  linesize);
2528  } else {
2529  for (i = 0; i < 16; i++)
2530  if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2531  dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2532  h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2533  h->mb + (i * 16 + p * 256 << pixel_shift),
2534  linesize);
2535  }
2536  } else {
2537  h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2538  h->mb + (p * 256 << pixel_shift),
2539  linesize,
2540  h->non_zero_count_cache + p * 5 * 8);
2541  }
2542  } else if (h->cbp & 15) {
2543  if (transform_bypass) {
2544  const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2547  for (i = 0; i < 16; i += di)
2548  if (h->non_zero_count_cache[scan8[i + p * 16]])
2549  idct_add(dest_y + block_offset[i],
2550  h->mb + (i * 16 + p * 256 << pixel_shift),
2551  linesize);
2552  } else {
2553  if (IS_8x8DCT(mb_type))
2554  h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2555  h->mb + (p * 256 << pixel_shift),
2556  linesize,
2557  h->non_zero_count_cache + p * 5 * 8);
2558  else
2559  h->h264dsp.h264_idct_add16(dest_y, block_offset,
2560  h->mb + (p * 256 << pixel_shift),
2561  linesize,
2562  h->non_zero_count_cache + p * 5 * 8);
2563  }
2564  }
2565  } else if (CONFIG_SVQ3_DECODER) {
2566  for (i = 0; i < 16; i++)
2567  if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2568  // FIXME benchmark weird rule, & below
2569  uint8_t *const ptr = dest_y + block_offset[i];
2570  ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2571  h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2572  }
2573  }
2574  }
2575 }
2576 
2577 #define BITS 8
2578 #define SIMPLE 1
2579 #include "h264_mb_template.c"
2580 
2581 #undef BITS
2582 #define BITS 16
2583 #include "h264_mb_template.c"
2584 
2585 #undef SIMPLE
2586 #define SIMPLE 0
2587 #include "h264_mb_template.c"
2588 
2590 {
2591  const int mb_xy = h->mb_xy;
2592  const int mb_type = h->cur_pic.mb_type[mb_xy];
2593  int is_complex = CONFIG_SMALL || h->is_complex ||
2594  IS_INTRA_PCM(mb_type) || h->qscale == 0;
2595 
2596  if (CHROMA444(h)) {
2597  if (is_complex || h->pixel_shift)
2598  hl_decode_mb_444_complex(h);
2599  else
2600  hl_decode_mb_444_simple_8(h);
2601  } else if (is_complex) {
2602  hl_decode_mb_complex(h);
2603  } else if (h->pixel_shift) {
2604  hl_decode_mb_simple_16(h);
2605  } else
2606  hl_decode_mb_simple_8(h);
2607 }
2608 
2610 {
2611  int list, i;
2612  int luma_def, chroma_def;
2613 
2614  h->use_weight = 0;
2615  h->use_weight_chroma = 0;
2617  if (h->sps.chroma_format_idc)
2619  luma_def = 1 << h->luma_log2_weight_denom;
2620  chroma_def = 1 << h->chroma_log2_weight_denom;
2621 
2622  for (list = 0; list < 2; list++) {
2623  h->luma_weight_flag[list] = 0;
2624  h->chroma_weight_flag[list] = 0;
2625  for (i = 0; i < h->ref_count[list]; i++) {
2626  int luma_weight_flag, chroma_weight_flag;
2627 
2628  luma_weight_flag = get_bits1(&h->gb);
2629  if (luma_weight_flag) {
2630  h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2631  h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2632  if (h->luma_weight[i][list][0] != luma_def ||
2633  h->luma_weight[i][list][1] != 0) {
2634  h->use_weight = 1;
2635  h->luma_weight_flag[list] = 1;
2636  }
2637  } else {
2638  h->luma_weight[i][list][0] = luma_def;
2639  h->luma_weight[i][list][1] = 0;
2640  }
2641 
2642  if (h->sps.chroma_format_idc) {
2643  chroma_weight_flag = get_bits1(&h->gb);
2644  if (chroma_weight_flag) {
2645  int j;
2646  for (j = 0; j < 2; j++) {
2647  h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2648  h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2649  if (h->chroma_weight[i][list][j][0] != chroma_def ||
2650  h->chroma_weight[i][list][j][1] != 0) {
2651  h->use_weight_chroma = 1;
2652  h->chroma_weight_flag[list] = 1;
2653  }
2654  }
2655  } else {
2656  int j;
2657  for (j = 0; j < 2; j++) {
2658  h->chroma_weight[i][list][j][0] = chroma_def;
2659  h->chroma_weight[i][list][j][1] = 0;
2660  }
2661  }
2662  }
2663  }
2665  break;
2666  }
2667  h->use_weight = h->use_weight || h->use_weight_chroma;
2668  return 0;
2669 }
2670 
2671 /**
2672  * Initialize implicit_weight table.
2673  * @param field 0/1 initialize the weight for interlaced MBAFF
2674  * -1 initializes the rest
2675  */
2676 static void implicit_weight_table(H264Context *h, int field)
2677 {
2678  int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2679 
2680  for (i = 0; i < 2; i++) {
2681  h->luma_weight_flag[i] = 0;
2682  h->chroma_weight_flag[i] = 0;
2683  }
2684 
2685  if (field < 0) {
2686  if (h->picture_structure == PICT_FRAME) {
2687  cur_poc = h->cur_pic_ptr->poc;
2688  } else {
2689  cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2690  }
2691  if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2692  h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2693  h->use_weight = 0;
2694  h->use_weight_chroma = 0;
2695  return;
2696  }
2697  ref_start = 0;
2698  ref_count0 = h->ref_count[0];
2699  ref_count1 = h->ref_count[1];
2700  } else {
2701  cur_poc = h->cur_pic_ptr->field_poc[field];
2702  ref_start = 16;
2703  ref_count0 = 16 + 2 * h->ref_count[0];
2704  ref_count1 = 16 + 2 * h->ref_count[1];
2705  }
2706 
2707  h->use_weight = 2;
2708  h->use_weight_chroma = 2;
2709  h->luma_log2_weight_denom = 5;
2710  h->chroma_log2_weight_denom = 5;
2711 
2712  for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2713  int poc0 = h->ref_list[0][ref0].poc;
2714  for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2715  int w = 32;
2716  if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2717  int poc1 = h->ref_list[1][ref1].poc;
2718  int td = av_clip(poc1 - poc0, -128, 127);
2719  if (td) {
2720  int tb = av_clip(cur_poc - poc0, -128, 127);
2721  int tx = (16384 + (FFABS(td) >> 1)) / td;
2722  int dist_scale_factor = (tb * tx + 32) >> 8;
2723  if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2724  w = 64 - dist_scale_factor;
2725  }
2726  }
2727  if (field < 0) {
2728  h->implicit_weight[ref0][ref1][0] =
2729  h->implicit_weight[ref0][ref1][1] = w;
2730  } else {
2731  h->implicit_weight[ref0][ref1][field] = w;
2732  }
2733  }
2734  }
2735 }
2736 
2737 /**
2738  * instantaneous decoder refresh.
2739  */
2740 static void idr(H264Context *h)
2741 {
2742  int i;
2744  h->prev_frame_num = 0;
2745  h->prev_frame_num_offset = 0;
2746  h->prev_poc_msb = 1<<16;
2747  h->prev_poc_lsb = 0;
2748  for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2749  h->last_pocs[i] = INT_MIN;
2750 }
2751 
2752 /* forget old pics after a seek */
2753 static void flush_change(H264Context *h)
2754 {
2755  int i, j;
2756 
2757  h->outputed_poc = h->next_outputed_poc = INT_MIN;
2758  h->prev_interlaced_frame = 1;
2759  idr(h);
2760 
2761  h->prev_frame_num = -1;
2762  if (h->cur_pic_ptr) {
2763  h->cur_pic_ptr->reference = 0;
2764  for (j=i=0; h->delayed_pic[i]; i++)
2765  if (h->delayed_pic[i] != h->cur_pic_ptr)
2766  h->delayed_pic[j++] = h->delayed_pic[i];
2767  h->delayed_pic[j] = NULL;
2768  }
2769  h->first_field = 0;
2770  memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2771  memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2772  memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2773  memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2774  ff_h264_reset_sei(h);
2775  h->recovery_frame= -1;
2776  h->sync= 0;
2777  h->list_count = 0;
2778  h->current_slice = 0;
2779  h->mmco_reset = 1;
2780 }
2781 
2782 /* forget old pics after a seek */
2783 static void flush_dpb(AVCodecContext *avctx)
2784 {
2785  H264Context *h = avctx->priv_data;
2786  int i;
2787 
2788  for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2789  if (h->delayed_pic[i])
2790  h->delayed_pic[i]->reference = 0;
2791  h->delayed_pic[i] = NULL;
2792  }
2793 
2794  flush_change(h);
2795 
2796  if (h->DPB)
2797  for (i = 0; i < MAX_PICTURE_COUNT; i++)
2798  unref_picture(h, &h->DPB[i]);
2799  h->cur_pic_ptr = NULL;
2800  unref_picture(h, &h->cur_pic);
2801 
2802  h->mb_x = h->mb_y = 0;
2803 
2804  h->parse_context.state = -1;
2806  h->parse_context.overread = 0;
2808  h->parse_context.index = 0;
2809  h->parse_context.last_index = 0;
2810 }
2811 
2812 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2813 {
2814  const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2815  int field_poc[2];
2816 
2818  if (h->frame_num < h->prev_frame_num)
2819  h->frame_num_offset += max_frame_num;
2820 
2821  if (h->sps.poc_type == 0) {
2822  const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2823 
2824  if (h->poc_lsb < h->prev_poc_lsb &&
2825  h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2826  h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2827  else if (h->poc_lsb > h->prev_poc_lsb &&
2828  h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2829  h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2830  else
2831  h->poc_msb = h->prev_poc_msb;
2832  field_poc[0] =
2833  field_poc[1] = h->poc_msb + h->poc_lsb;
2834  if (h->picture_structure == PICT_FRAME)
2835  field_poc[1] += h->delta_poc_bottom;
2836  } else if (h->sps.poc_type == 1) {
2837  int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2838  int i;
2839 
2840  if (h->sps.poc_cycle_length != 0)
2841  abs_frame_num = h->frame_num_offset + h->frame_num;
2842  else
2843  abs_frame_num = 0;
2844 
2845  if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2846  abs_frame_num--;
2847 
2848  expected_delta_per_poc_cycle = 0;
2849  for (i = 0; i < h->sps.poc_cycle_length; i++)
2850  // FIXME integrate during sps parse
2851  expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2852 
2853  if (abs_frame_num > 0) {
2854  int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2855  int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2856 
2857  expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2858  for (i = 0; i <= frame_num_in_poc_cycle; i++)
2859  expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2860  } else
2861  expectedpoc = 0;
2862 
2863  if (h->nal_ref_idc == 0)
2864  expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2865 
2866  field_poc[0] = expectedpoc + h->delta_poc[0];
2867  field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2868 
2869  if (h->picture_structure == PICT_FRAME)
2870  field_poc[1] += h->delta_poc[1];
2871  } else {
2872  int poc = 2 * (h->frame_num_offset + h->frame_num);
2873 
2874  if (!h->nal_ref_idc)
2875  poc--;
2876 
2877  field_poc[0] = poc;
2878  field_poc[1] = poc;
2879  }
2880 
2882  pic_field_poc[0] = field_poc[0];
2884  pic_field_poc[1] = field_poc[1];
2885  *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2886 
2887  return 0;
2888 }
2889 
2890 /**
2891  * initialize scan tables
2892  */
2894 {
2895  int i;
2896  for (i = 0; i < 16; i++) {
2897 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2898  h->zigzag_scan[i] = T(zigzag_scan[i]);
2899  h->field_scan[i] = T(field_scan[i]);
2900 #undef T
2901  }
2902  for (i = 0; i < 64; i++) {
2903 #define T(x) (x >> 3) | ((x & 7) << 3)
2904  h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2906  h->field_scan8x8[i] = T(field_scan8x8[i]);
2908 #undef T
2909  }
2910  if (h->sps.transform_bypass) { // FIXME same ugly
2911  memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2912  memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2914  memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2915  memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2917  } else {
2918  memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2919  memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2921  memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2922  memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2924  }
2925 }
2926 
2927 static int field_end(H264Context *h, int in_setup)
2928 {
2929  AVCodecContext *const avctx = h->avctx;
2930  int err = 0;
2931  h->mb_y = 0;
2932 
2933  if (CONFIG_H264_VDPAU_DECODER &&
2934  h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2936 
2937  if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2938  if (!h->droppable) {
2940  h->prev_poc_msb = h->poc_msb;
2941  h->prev_poc_lsb = h->poc_lsb;
2942  }
2944  h->prev_frame_num = h->frame_num;
2946  }
2947 
2948  if (avctx->hwaccel) {
2949  if (avctx->hwaccel->end_frame(avctx) < 0)
2950  av_log(avctx, AV_LOG_ERROR,
2951  "hardware accelerator failed to decode picture\n");
2952  }
2953 
2954  if (CONFIG_H264_VDPAU_DECODER &&
2955  h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2957 
2958  /*
2959  * FIXME: Error handling code does not seem to support interlaced
2960  * when slices span multiple rows
2961  * The ff_er_add_slice calls don't work right for bottom
2962  * fields; they cause massive erroneous error concealing
2963  * Error marking covers both fields (top and bottom).
2964  * This causes a mismatched s->error_count
2965  * and a bad error table. Further, the error count goes to
2966  * INT_MAX when called for bottom field, because mb_y is
2967  * past end by one (callers fault) and resync_mb_y != 0
2968  * causes problems for the first MB line, too.
2969  */
2970  if (CONFIG_ERROR_RESILIENCE &&
2971  !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
2972  h->er.cur_pic = h->cur_pic_ptr;
2973  ff_er_frame_end(&h->er);
2974  }
2975  if (!in_setup && !h->droppable)
2978  emms_c();
2979 
2980  h->current_slice = 0;
2981 
2982  return err;
2983 }
2984 
2985 /**
2986  * Replicate H264 "master" context to thread contexts.
2987  */
2989 {
2990  memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2991  dst->cur_pic_ptr = src->cur_pic_ptr;
2992  dst->cur_pic = src->cur_pic;
2993  dst->linesize = src->linesize;
2994  dst->uvlinesize = src->uvlinesize;
2995  dst->first_field = src->first_field;
2996 
2997  dst->prev_poc_msb = src->prev_poc_msb;
2998  dst->prev_poc_lsb = src->prev_poc_lsb;
3000  dst->prev_frame_num = src->prev_frame_num;
3001  dst->short_ref_count = src->short_ref_count;
3002 
3003  memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
3004  memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3005  memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3006 
3007  memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3008  memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3009 
3010  return 0;
3011 }
3012 
3013 /**
3014  * Compute profile from profile_idc and constraint_set?_flags.
3015  *
3016  * @param sps SPS
3017  *
3018  * @return profile as defined by FF_PROFILE_H264_*
3019  */
3021 {
3022  int profile = sps->profile_idc;
3023 
3024  switch (sps->profile_idc) {
3026  // constraint_set1_flag set to 1
3027  profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3028  break;
3032  // constraint_set3_flag set to 1
3033  profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3034  break;
3035  }
3036 
3037  return profile;
3038 }
3039 
3041 {
3042  if (h->flags & CODEC_FLAG_LOW_DELAY ||
3044  !h->sps.num_reorder_frames)) {
3045  if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3046  av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3047  "Reenabling low delay requires a codec flush.\n");
3048  else
3049  h->low_delay = 1;
3050  }
3051 
3052  if (h->avctx->has_b_frames < 2)
3053  h->avctx->has_b_frames = !h->low_delay;
3054 
3055  if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3057  "Different chroma and luma bit depth");
3058  return AVERROR_PATCHWELCOME;
3059  }
3060 
3061  if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3063  if (h->avctx->codec &&
3064  h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
3065  (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
3067  "VDPAU decoding does not support video colorspace.\n");
3068  return AVERROR_INVALIDDATA;
3069  }
3070  if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
3071  h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
3074  h->pixel_shift = h->sps.bit_depth_luma > 8;
3075 
3077  h->sps.chroma_format_idc);
3081  h->sps.chroma_format_idc);
3082 
3083  if (CONFIG_ERROR_RESILIENCE)
3084  ff_dsputil_init(&h->dsp, h->avctx);
3086  } else {
3087  av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3088  h->sps.bit_depth_luma);
3089  return AVERROR_INVALIDDATA;
3090  }
3091  }
3092  return 0;
3093 }
3094 
3095 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3096 {
3097  switch (h->sps.bit_depth_luma) {
3098  case 9:
3099  if (CHROMA444(h)) {
3100  if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3101  return AV_PIX_FMT_GBRP9;
3102  } else
3103  return AV_PIX_FMT_YUV444P9;
3104  } else if (CHROMA422(h))
3105  return AV_PIX_FMT_YUV422P9;
3106  else
3107  return AV_PIX_FMT_YUV420P9;
3108  break;
3109  case 10:
3110  if (CHROMA444(h)) {
3111  if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3112  return AV_PIX_FMT_GBRP10;
3113  } else
3114  return AV_PIX_FMT_YUV444P10;
3115  } else if (CHROMA422(h))
3116  return AV_PIX_FMT_YUV422P10;
3117  else
3118  return AV_PIX_FMT_YUV420P10;
3119  break;
3120  case 12:
3121  if (CHROMA444(h)) {
3122  if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3123  return AV_PIX_FMT_GBRP12;
3124  } else
3125  return AV_PIX_FMT_YUV444P12;
3126  } else if (CHROMA422(h))
3127  return AV_PIX_FMT_YUV422P12;
3128  else
3129  return AV_PIX_FMT_YUV420P12;
3130  break;
3131  case 14:
3132  if (CHROMA444(h)) {
3133  if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3134  return AV_PIX_FMT_GBRP14;
3135  } else
3136  return AV_PIX_FMT_YUV444P14;
3137  } else if (CHROMA422(h))
3138  return AV_PIX_FMT_YUV422P14;
3139  else
3140  return AV_PIX_FMT_YUV420P14;
3141  break;
3142  case 8:
3143  if (CHROMA444(h)) {
3144  if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3145  av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3146  return AV_PIX_FMT_GBR24P;
3147  } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3148  av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3149  }
3152  } else if (CHROMA422(h)) {
3155  } else {
3156  int i;
3157  const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3158  h->avctx->codec->pix_fmts :
3162 
3163  for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3164  if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3165  return fmt[i];
3166  return ff_thread_get_format(h->avctx, fmt);
3167  }
3168  break;
3169  default:
3171  "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3172  return AVERROR_INVALIDDATA;
3173  }
3174 }
3175 
3176 /* export coded and cropped frame dimensions to AVCodecContext */
3178 {
3179  int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3180  int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3181  av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
3182  av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
3183 
3184  /* handle container cropping */
3185  if (!h->sps.crop &&
3186  FFALIGN(h->avctx->width, 16) == h->width &&
3187  FFALIGN(h->avctx->height, 16) == h->height) {
3188  width = h->avctx->width;
3189  height = h->avctx->height;
3190  }
3191 
3192  if (width <= 0 || height <= 0) {
3193  av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3194  width, height);
3196  return AVERROR_INVALIDDATA;
3197 
3198  av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3199  h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3200  h->sps.crop = 0;
3201 
3202  width = h->width;
3203  height = h->height;
3204  }
3205 
3206  h->avctx->coded_width = h->width;
3207  h->avctx->coded_height = h->height;
3208  h->avctx->width = width;
3209  h->avctx->height = height;
3210 
3211  return 0;
3212 }
3213 
3215 {
3216  int nb_slices = (HAVE_THREADS &&
3218  h->avctx->thread_count : 1;
3219  int i, ret;
3220 
3221  h->avctx->sample_aspect_ratio = h->sps.sar;
3224  &h->chroma_x_shift, &h->chroma_y_shift);
3225 
3226  if (h->sps.timing_info_present_flag) {
3227  int64_t den = h->sps.time_scale;
3228  if (h->x264_build < 44U)
3229  den *= 2;
3231  h->sps.num_units_in_tick, den, 1 << 30);
3232  }
3233 
3235 
3236  if (reinit)
3237  free_tables(h, 0);
3238  h->first_field = 0;
3239  h->prev_interlaced_frame = 1;
3240 
3241  init_scan_tables(h);
3242  ret = ff_h264_alloc_tables(h);
3243  if (ret < 0) {
3245  "Could not allocate memory for h264\n");
3246  return ret;
3247  }
3248 
3249  if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3250  int max_slices;
3251  if (h->mb_height)
3252  max_slices = FFMIN(MAX_THREADS, h->mb_height);
3253  else
3254  max_slices = MAX_THREADS;
3255  av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3256  " reducing to %d\n", nb_slices, max_slices);
3257  nb_slices = max_slices;
3258  }
3259  h->slice_context_count = nb_slices;
3260 
3261  if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3262  ret = context_init(h);
3263  if (ret < 0) {
3264  av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3265  return ret;
3266  }
3267  } else {
3268  for (i = 1; i < h->slice_context_count; i++) {
3269  H264Context *c;
3270  c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3271  c->avctx = h->avctx;
3272  if (CONFIG_ERROR_RESILIENCE) {
3273  c->dsp = h->dsp;
3274  }
3275  c->vdsp = h->vdsp;
3276  c->h264dsp = h->h264dsp;
3277  c->h264qpel = h->h264qpel;
3278  c->h264chroma = h->h264chroma;
3279  c->sps = h->sps;
3280  c->pps = h->pps;
3281  c->pixel_shift = h->pixel_shift;
3283  c->width = h->width;
3284  c->height = h->height;
3285  c->linesize = h->linesize;
3286  c->uvlinesize = h->uvlinesize;
3289  c->qscale = h->qscale;
3290  c->droppable = h->droppable;
3292  c->low_delay = h->low_delay;
3293  c->mb_width = h->mb_width;
3294  c->mb_height = h->mb_height;
3295  c->mb_stride = h->mb_stride;
3296  c->mb_num = h->mb_num;
3297  c->flags = h->flags;
3299  c->pict_type = h->pict_type;
3300 
3301  init_scan_tables(c);
3302  clone_tables(c, h, i);
3303  c->context_initialized = 1;
3304  }
3305 
3306  for (i = 0; i < h->slice_context_count; i++)
3307  if ((ret = context_init(h->thread_context[i])) < 0) {
3308  av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3309  return ret;
3310  }
3311  }
3312 
3313  h->context_initialized = 1;
3314 
3315  return 0;
3316 }
3317 
3319 {
3320  int num_ref_idx_active_override_flag;
3321 
3322  // set defaults, might be overridden a few lines later
3323  h->ref_count[0] = h->pps.ref_count[0];
3324  h->ref_count[1] = h->pps.ref_count[1];
3325 
3326  if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3327  unsigned max[2];
3328  max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3329 
3332  num_ref_idx_active_override_flag = get_bits1(&h->gb);
3333 
3334  if (num_ref_idx_active_override_flag) {
3335  h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3336  if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3337  h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3338  } else
3339  // full range is spec-ok in this case, even for frames
3340  h->ref_count[1] = 1;
3341  }
3342 
3343  if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3344  av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
3345  h->ref_count[0] = h->ref_count[1] = 0;
3346  return AVERROR_INVALIDDATA;
3347  }
3348 
3350  h->list_count = 2;
3351  else
3352  h->list_count = 1;
3353  } else {
3354  h->list_count = 0;
3355  h->ref_count[0] = h->ref_count[1] = 0;
3356  }
3357 
3358  return 0;
3359 }
3360 
3361 /**
3362  * Decode a slice header.
3363  * This will also call ff_MPV_common_init() and frame_start() as needed.
3364  *
3365  * @param h h264context
3366  * @param h0 h264 master context (differs from 'h' when doing sliced based
3367  * parallel decoding)
3368  *
3369  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3370  */
3372 {
3373  unsigned int first_mb_in_slice;
3374  unsigned int pps_id;
3375  int ret;
3376  unsigned int slice_type, tmp, i, j;
3377  int last_pic_structure, last_pic_droppable;
3378  int must_reinit;
3379  int needs_reinit = 0;
3380  int field_pic_flag, bottom_field_flag;
3381 
3384 
3385  first_mb_in_slice = get_ue_golomb_long(&h->gb);
3386 
3387  if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3388  if (h0->current_slice && FIELD_PICTURE(h)) {
3389  field_end(h, 1);
3390  }
3391 
3392  h0->current_slice = 0;
3393  if (!h0->first_field) {
3394  if (h->cur_pic_ptr && !h->droppable) {
3397  }
3398  h->cur_pic_ptr = NULL;
3399  }
3400  }
3401 
3402  slice_type = get_ue_golomb_31(&h->gb);
3403  if (slice_type > 9) {
3405  "slice type too large (%d) at %d %d\n",
3406  slice_type, h->mb_x, h->mb_y);
3407  return AVERROR_INVALIDDATA;
3408  }
3409  if (slice_type > 4) {
3410  slice_type -= 5;
3411  h->slice_type_fixed = 1;
3412  } else
3413  h->slice_type_fixed = 0;
3414 
3415  slice_type = golomb_to_pict_type[slice_type];
3416  h->slice_type = slice_type;
3417  h->slice_type_nos = slice_type & 3;
3418 
3419  // to make a few old functions happy, it's wrong though
3420  h->pict_type = h->slice_type;
3421 
3422  pps_id = get_ue_golomb(&h->gb);
3423  if (pps_id >= MAX_PPS_COUNT) {
3424  av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3425  return AVERROR_INVALIDDATA;
3426  }
3427  if (!h0->pps_buffers[pps_id]) {
3429  "non-existing PPS %u referenced\n",
3430  pps_id);
3431  return AVERROR_INVALIDDATA;
3432  }
3433  h->pps = *h0->pps_buffers[pps_id];
3434 
3435  if (!h0->sps_buffers[h->pps.sps_id]) {
3437  "non-existing SPS %u referenced\n",
3438  h->pps.sps_id);
3439  return AVERROR_INVALIDDATA;
3440  }
3441 
3442  if (h->pps.sps_id != h->current_sps_id ||
3443  h0->sps_buffers[h->pps.sps_id]->new) {
3444  h0->sps_buffers[h->pps.sps_id]->new = 0;
3445 
3446  h->current_sps_id = h->pps.sps_id;
3447  h->sps = *h0->sps_buffers[h->pps.sps_id];
3448 
3449  if (h->mb_width != h->sps.mb_width ||
3450  h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3453  )
3454  needs_reinit = 1;
3455 
3456  if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3460  needs_reinit = 1;
3461  }
3462  if ((ret = h264_set_parameter_from_sps(h)) < 0)
3463  return ret;
3464  }
3465 
3466  h->avctx->profile = ff_h264_get_profile(&h->sps);
3467  h->avctx->level = h->sps.level_idc;
3468  h->avctx->refs = h->sps.ref_frame_count;
3469 
3470  must_reinit = (h->context_initialized &&
3471  ( 16*h->sps.mb_width != h->avctx->coded_width
3472  || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3476  || h->mb_width != h->sps.mb_width
3477  || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3478  ));
3479  if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3480  must_reinit = 1;
3481 
3482  h->mb_width = h->sps.mb_width;
3483  h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3484  h->mb_num = h->mb_width * h->mb_height;
3485  h->mb_stride = h->mb_width + 1;
3486 
3487  h->b_stride = h->mb_width * 4;
3488 
3489  h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3490 
3491  h->width = 16 * h->mb_width;
3492  h->height = 16 * h->mb_height;
3493 
3494  ret = init_dimensions(h);
3495  if (ret < 0)
3496  return ret;
3497 
3500  : AVCOL_RANGE_MPEG;
3502  if (h->avctx->colorspace != h->sps.colorspace)
3503  needs_reinit = 1;
3505  h->avctx->color_trc = h->sps.color_trc;
3506  h->avctx->colorspace = h->sps.colorspace;
3507  }
3508  }
3509 
3510  if (h->context_initialized &&
3511  (h->width != h->avctx->coded_width ||
3512  h->height != h->avctx->coded_height ||
3513  must_reinit ||
3514  needs_reinit)) {
3515  if (h != h0) {
3516  av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3517  "slice %d\n", h0->current_slice + 1);
3518  return AVERROR_INVALIDDATA;
3519  }
3520 
3521  flush_change(h);
3522 
3523  if ((ret = get_pixel_format(h, 1)) < 0)
3524  return ret;
3525  h->avctx->pix_fmt = ret;
3526 
3527  av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3528  "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3529 
3530  if ((ret = h264_slice_header_init(h, 1)) < 0) {
3532  "h264_slice_header_init() failed\n");
3533  return ret;
3534  }
3535  }
3536  if (!h->context_initialized) {
3537  if (h != h0) {
3539  "Cannot (re-)initialize context during parallel decoding.\n");
3540  return AVERROR_PATCHWELCOME;
3541  }
3542 
3543  if ((ret = get_pixel_format(h, 1)) < 0)
3544  return ret;
3545  h->avctx->pix_fmt = ret;
3546 
3547  if ((ret = h264_slice_header_init(h, 0)) < 0) {
3549  "h264_slice_header_init() failed\n");
3550  return ret;
3551  }
3552  }
3553 
3554  if (h == h0 && h->dequant_coeff_pps != pps_id) {
3555  h->dequant_coeff_pps = pps_id;
3557  }
3558 
3559  h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3560 
3561  h->mb_mbaff = 0;
3562  h->mb_aff_frame = 0;
3563  last_pic_structure = h0->picture_structure;
3564  last_pic_droppable = h0->droppable;
3565  h->droppable = h->nal_ref_idc == 0;
3566  if (h->sps.frame_mbs_only_flag) {
3568  } else {
3569  if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3570  av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3571  return -1;
3572  }
3573  field_pic_flag = get_bits1(&h->gb);
3574  if (field_pic_flag) {
3575  bottom_field_flag = get_bits1(&h->gb);
3576  h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3577  } else {
3579  h->mb_aff_frame = h->sps.mb_aff;
3580  }
3581  }
3583 
3584  if (h0->current_slice != 0) {
3585  if (last_pic_structure != h->picture_structure ||
3586  last_pic_droppable != h->droppable) {
3588  "Changing field mode (%d -> %d) between slices is not allowed\n",
3589  last_pic_structure, h->picture_structure);
3590  h->picture_structure = last_pic_structure;
3591  h->droppable = last_pic_droppable;
3592  return AVERROR_INVALIDDATA;
3593  } else if (!h0->cur_pic_ptr) {
3595  "unset cur_pic_ptr on %d. slice\n",
3596  h0->current_slice + 1);
3597  return AVERROR_INVALIDDATA;
3598  }
3599  } else {
3600  /* Shorten frame num gaps so we don't have to allocate reference
3601  * frames just to throw them away */
3602  if (h->frame_num != h->prev_frame_num) {
3603  int unwrap_prev_frame_num = h->prev_frame_num;
3604  int max_frame_num = 1 << h->sps.log2_max_frame_num;
3605 
3606  if (unwrap_prev_frame_num > h->frame_num)
3607  unwrap_prev_frame_num -= max_frame_num;
3608 
3609  if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3610  unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3611  if (unwrap_prev_frame_num < 0)
3612  unwrap_prev_frame_num += max_frame_num;
3613 
3614  h->prev_frame_num = unwrap_prev_frame_num;
3615  }
3616  }
3617 
3618  /* See if we have a decoded first field looking for a pair...
3619  * Here, we're using that to see if we should mark previously
3620  * decode frames as "finished".
3621  * We have to do that before the "dummy" in-between frame allocation,
3622  * since that can modify h->cur_pic_ptr. */
3623  if (h0->first_field) {
3624  assert(h0->cur_pic_ptr);
3625  assert(h0->cur_pic_ptr->f.data[0]);
3626  assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3627 
3628  /* Mark old field/frame as completed */
3629  if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
3630  ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3631  last_pic_structure == PICT_BOTTOM_FIELD);
3632  }
3633 
3634  /* figure out if we have a complementary field pair */
3635  if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3636  /* Previous field is unmatched. Don't display it, but let it
3637  * remain for reference if marked as such. */
3638  if (last_pic_structure != PICT_FRAME) {
3639  ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3640  last_pic_structure == PICT_TOP_FIELD);
3641  }
3642  } else {
3643  if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3644  /* This and previous field were reference, but had
3645  * different frame_nums. Consider this field first in
3646  * pair. Throw away previous field except for reference
3647  * purposes. */
3648  if (last_pic_structure != PICT_FRAME) {
3649  ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3650  last_pic_structure == PICT_TOP_FIELD);
3651  }
3652  } else {
3653  /* Second field in complementary pair */
3654  if (!((last_pic_structure == PICT_TOP_FIELD &&
3656  (last_pic_structure == PICT_BOTTOM_FIELD &&
3659  "Invalid field mode combination %d/%d\n",
3660  last_pic_structure, h->picture_structure);
3661  h->picture_structure = last_pic_structure;
3662  h->droppable = last_pic_droppable;
3663  return AVERROR_INVALIDDATA;
3664  } else if (last_pic_droppable != h->droppable) {
3666  "Found reference and non-reference fields in the same frame, which");
3667  h->picture_structure = last_pic_structure;
3668  h->droppable = last_pic_droppable;
3669  return AVERROR_PATCHWELCOME;
3670  }
3671  }
3672  }
3673  }
3674 
3675  while (h->frame_num != h->prev_frame_num && !h0->first_field &&
3676  h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3677  Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3678  av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3679  h->frame_num, h->prev_frame_num);
3681  for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3682  h->last_pocs[i] = INT_MIN;
3683  ret = h264_frame_start(h);
3684  if (ret < 0)
3685  return ret;
3686  h->prev_frame_num++;
3687  h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3689  ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3690  ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3692  if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3693  return ret;
3695  if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3696  return ret;
3697  /* Error concealment: If a ref is missing, copy the previous ref
3698  * in its place.
3699  * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3700  * many assumptions about there being no actual duplicates.
3701  * FIXME: This does not copy padding for out-of-frame motion
3702  * vectors. Given we are concealing a lost frame, this probably
3703  * is not noticeable by comparison, but it should be fixed. */
3704  if (h->short_ref_count) {
3705  if (prev) {
3706  av_image_copy(h->short_ref[0]->f.data,
3707  h->short_ref[0]->f.linesize,
3708  (const uint8_t **)prev->f.data,
3709  prev->f.linesize,
3710  h->avctx->pix_fmt,
3711  h->mb_width * 16,
3712  h->mb_height * 16);
3713  h->short_ref[0]->poc = prev->poc + 2;
3714  }
3715  h->short_ref[0]->frame_num = h->prev_frame_num;
3716  }
3717  }
3718 
3719  /* See if we have a decoded first field looking for a pair...
3720  * We're using that to see whether to continue decoding in that
3721  * frame, or to allocate a new one. */
3722  if (h0->first_field) {
3723  assert(h0->cur_pic_ptr);
3724  assert(h0->cur_pic_ptr->f.data[0]);
3725  assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3726 
3727  /* figure out if we have a complementary field pair */
3728  if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3729  /* Previous field is unmatched. Don't display it, but let it
3730  * remain for reference if marked as such. */
3731  h0->cur_pic_ptr = NULL;
3732  h0->first_field = FIELD_PICTURE(h);
3733  } else {
3734  if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3735  ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3737  /* This and the previous field had different frame_nums.
3738  * Consider this field first in pair. Throw away previous
3739  * one except for reference purposes. */
3740  h0->first_field = 1;
3741  h0->cur_pic_ptr = NULL;
3742  } else {
3743  /* Second field in complementary pair */
3744  h0->first_field = 0;
3745  }
3746  }
3747  } else {
3748  /* Frame or first field in a potentially complementary pair */
3749  h0->first_field = FIELD_PICTURE(h);
3750  }
3751 
3752  if (!FIELD_PICTURE(h) || h0->first_field) {
3753  if (h264_frame_start(h) < 0) {
3754  h0->first_field = 0;
3755  return AVERROR_INVALIDDATA;
3756  }
3757  } else {
3759  }
3760  /* Some macroblocks can be accessed before they're available in case
3761  * of lost slices, MBAFF or threading. */
3762  if (FIELD_PICTURE(h)) {
3763  for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3764  memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3765  } else {
3766  memset(h->slice_table, -1,
3767  (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3768  }
3769  h0->last_slice_type = -1;
3770  }
3771  if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3772  return ret;
3773 
3774  /* can't be in alloc_tables because linesize isn't known there.
3775  * FIXME: redo bipred weight to not require extra buffer? */
3776  for (i = 0; i < h->slice_context_count; i++)
3777  if (h->thread_context[i]) {
3779  if (ret < 0)
3780  return ret;
3781  }
3782 
3783  h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3784 
3785  av_assert1(h->mb_num == h->mb_width * h->mb_height);
3786  if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3787  first_mb_in_slice >= h->mb_num) {
3788  av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3789  return AVERROR_INVALIDDATA;
3790  }
3791  h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3792  h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3795  h->resync_mb_y = h->mb_y = h->mb_y + 1;
3796  av_assert1(h->mb_y < h->mb_height);
3797 
3798  if (h->picture_structure == PICT_FRAME) {
3799  h->curr_pic_num = h->frame_num;
3800  h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3801  } else {
3802  h->curr_pic_num = 2 * h->frame_num + 1;
3803  h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3804  }
3805 
3806  if (h->nal_unit_type == NAL_IDR_SLICE)
3807  get_ue_golomb(&h->gb); /* idr_pic_id */
3808 
3809  if (h->sps.poc_type == 0) {
3810  h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3811 
3812  if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3813  h->delta_poc_bottom = get_se_golomb(&h->gb);
3814  }
3815 
3816  if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3817  h->delta_poc[0] = get_se_golomb(&h->gb);
3818 
3819  if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3820  h->delta_poc[1] = get_se_golomb(&h->gb);
3821  }
3822 
3824 
3827 
3828  ret = ff_set_ref_count(h);
3829  if (ret < 0)
3830  return ret;
3831 
3832  if (slice_type != AV_PICTURE_TYPE_I &&
3833  (h0->current_slice == 0 ||
3834  slice_type != h0->last_slice_type ||
3835  memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3836 
3838  }
3839 
3840  if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3842  if (ret < 0) {
3843  h->ref_count[1] = h->ref_count[0] = 0;
3844  return ret;
3845  }
3846  }
3847 
3848  if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3849  (h->pps.weighted_bipred_idc == 1 &&
3852  else if (h->pps.weighted_bipred_idc == 2 &&
3854  implicit_weight_table(h, -1);
3855  } else {
3856  h->use_weight = 0;
3857  for (i = 0; i < 2; i++) {
3858  h->luma_weight_flag[i] = 0;
3859  h->chroma_weight_flag[i] = 0;
3860  }
3861  }
3862 
3863  // If frame-mt is enabled, only update mmco tables for the first slice
3864  // in a field. Subsequent slices can temporarily clobber h->mmco_index
3865  // or h->mmco, which will cause ref list mix-ups and decoding errors
3866  // further down the line. This may break decoding if the first slice is
3867  // corrupt, thus we only do this if frame-mt is enabled.
3868  if (h->nal_ref_idc) {
3869  ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3871  h0->current_slice == 0);
3872  if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3873  return AVERROR_INVALIDDATA;
3874  }
3875 
3876  if (FRAME_MBAFF(h)) {
3878 
3880  implicit_weight_table(h, 0);
3881  implicit_weight_table(h, 1);
3882  }
3883  }
3884 
3888 
3889  if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3890  tmp = get_ue_golomb_31(&h->gb);
3891  if (tmp > 2) {
3892  av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3893  return AVERROR_INVALIDDATA;
3894  }
3895  h->cabac_init_idc = tmp;
3896  }
3897 
3898  h->last_qscale_diff = 0;
3899  tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3900  if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3901  av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3902  return AVERROR_INVALIDDATA;
3903  }
3904  h->qscale = tmp;
3905  h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3906  h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3907  // FIXME qscale / qp ... stuff
3908  if (h->slice_type == AV_PICTURE_TYPE_SP)
3909  get_bits1(&h->gb); /* sp_for_switch_flag */
3910  if (h->slice_type == AV_PICTURE_TYPE_SP ||
3912  get_se_golomb(&h->gb); /* slice_qs_delta */
3913 
3914  h->deblocking_filter = 1;
3915  h->slice_alpha_c0_offset = 52;
3916  h->slice_beta_offset = 52;
3918  tmp = get_ue_golomb_31(&h->gb);
3919  if (tmp > 2) {
3921  "deblocking_filter_idc %u out of range\n", tmp);
3922  return AVERROR_INVALIDDATA;
3923  }
3924  h->deblocking_filter = tmp;
3925  if (h->deblocking_filter < 2)
3926  h->deblocking_filter ^= 1; // 1<->0
3927 
3928  if (h->deblocking_filter) {
3929  h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3930  h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3931  if (h->slice_alpha_c0_offset > 104U ||
3932  h->slice_beta_offset > 104U) {
3934  "deblocking filter parameters %d %d out of range\n",
3936  return AVERROR_INVALIDDATA;
3937  }
3938  }
3939  }
3940 
3941  if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3947  h->nal_ref_idc == 0))
3948  h->deblocking_filter = 0;
3949 
3950  if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3951  if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3952  /* Cheat slightly for speed:
3953  * Do not bother to deblock across slices. */
3954  h->deblocking_filter = 2;
3955  } else {
3956  h0->max_contexts = 1;
3957  if (!h0->single_decode_warning) {
3958  av_log(h->avctx, AV_LOG_INFO,
3959  "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3960  h0->single_decode_warning = 1;
3961  }
3962  if (h != h0) {
3964  "Deblocking switched inside frame.\n");
3965  return 1;
3966  }
3967  }
3968  }
3969  h->qp_thresh = 15 + 52 -
3971  FFMAX3(0,
3973  h->pps.chroma_qp_index_offset[1]) +
3974  6 * (h->sps.bit_depth_luma - 8);
3975 
3976  h0->last_slice_type = slice_type;
3977  memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
3978  h->slice_num = ++h0->current_slice;
3979 
3980  if (h->slice_num)
3981  h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
3982  if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
3983  && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
3984  && h->slice_num >= MAX_SLICES) {
3985  //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3986  av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
3987  }
3988 
3989  for (j = 0; j < 2; j++) {
3990  int id_list[16];
3991  int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3992  for (i = 0; i < 16; i++) {
3993  id_list[i] = 60;
3994  if (j < h->list_count && i < h->ref_count[j] &&
3995  h->ref_list[j][i].f.buf[0]) {
3996  int k;
3997  AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
3998  for (k = 0; k < h->short_ref_count; k++)
3999  if (h->short_ref[k]->f.buf[0]->buffer == buf) {
4000  id_list[i] = k;
4001  break;
4002  }
4003  for (k = 0; k < h->long_ref_count; k++)
4004  if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
4005  id_list[i] = h->short_ref_count + k;
4006  break;
4007  }
4008  }
4009  }
4010 
4011  ref2frm[0] =
4012  ref2frm[1] = -1;
4013  for (i = 0; i < 16; i++)
4014  ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
4015  ref2frm[18 + 0] =
4016  ref2frm[18 + 1] = -1;
4017  for (i = 16; i < 48; i++)
4018  ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
4019  (h->ref_list[j][i].reference & 3);
4020  }
4021 
4022  if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
4023  if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
4024  h->er.ref_count = h->ref_count[0];
4025 
4026  if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
4028  "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
4029  h->slice_num,
4030  (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
4031  first_mb_in_slice,
4033  h->slice_type_fixed ? " fix" : "",
4034  h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
4035  pps_id, h->frame_num,
4036  h->cur_pic_ptr->field_poc[0],
4037  h->cur_pic_ptr->field_poc[1],
4038  h->ref_count[0], h->ref_count[1],
4039  h->qscale,
4040  h->deblocking_filter,
4041  h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
4042  h->use_weight,
4043  h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
4044  h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
4045  }
4046 
4047  return 0;
4048 }
4049 
4051 {
4052  switch (h->slice_type) {
4053  case AV_PICTURE_TYPE_P:
4054  return 0;
4055  case AV_PICTURE_TYPE_B:
4056  return 1;
4057  case AV_PICTURE_TYPE_I:
4058  return 2;
4059  case AV_PICTURE_TYPE_SP:
4060  return 3;
4061  case AV_PICTURE_TYPE_SI:
4062  return 4;
4063  default:
4064  return AVERROR_INVALIDDATA;
4065  }
4066 }
4067 
4069  int mb_type, int top_xy,
4070  int left_xy[LEFT_MBS],
4071  int top_type,
4072  int left_type[LEFT_MBS],
4073  int mb_xy, int list)
4074 {
4075  int b_stride = h->b_stride;
4076  int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4077  int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4078  if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4079  if (USES_LIST(top_type, list)) {
4080  const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
4081  const int b8_xy = 4 * top_xy + 2;
4082  int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4083  AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4084  ref_cache[0 - 1 * 8] =
4085  ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4086  ref_cache[2 - 1 * 8] =
4087  ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4088  } else {
4089  AV_ZERO128(mv_dst - 1 * 8);
4090  AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4091  }
4092 
4093  if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4094  if (USES_LIST(left_type[LTOP], list)) {
4095  const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
4096  const int b8_xy = 4 * left_xy[LTOP] + 1;
4097  int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4098  AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4099  AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4100  AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4101  AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4102  ref_cache[-1 + 0] =
4103  ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4104  ref_cache[-1 + 16] =
4105  ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4106  } else {
4107  AV_ZERO32(mv_dst - 1 + 0);
4108  AV_ZERO32(mv_dst - 1 + 8);
4109  AV_ZERO32(mv_dst - 1 + 16);
4110  AV_ZERO32(mv_dst - 1 + 24);
4111  ref_cache[-1 + 0] =
4112  ref_cache[-1 + 8] =
4113  ref_cache[-1 + 16] =
4114  ref_cache[-1 + 24] = LIST_NOT_USED;
4115  }
4116  }
4117  }
4118 
4119  if (!USES_LIST(mb_type, list)) {
4120  fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4121  AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4122  AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4123  AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4124  AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4125  return;
4126  }
4127 
4128  {
4129  int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4130  int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4131  uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4132  uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4133  AV_WN32A(&ref_cache[0 * 8], ref01);
4134  AV_WN32A(&ref_cache[1 * 8], ref01);
4135  AV_WN32A(&ref_cache[2 * 8], ref23);
4136  AV_WN32A(&ref_cache[3 * 8], ref23);
4137  }
4138 
4139  {
4140  int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4141  AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4142  AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4143  AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4144  AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4145  }
4146 }
4147 
4148 /**
4149  *
4150  * @return non zero if the loop filter can be skipped
4151  */
4152 static int fill_filter_caches(H264Context *h, int mb_type)
4153 {
4154  const int mb_xy = h->mb_xy;
4155  int top_xy, left_xy[LEFT_MBS];
4156  int top_type, left_type[LEFT_MBS];
4157  uint8_t *nnz;
4158  uint8_t *nnz_cache;
4159 
4160  top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4161 
4162  /* Wow, what a mess, why didn't they simplify the interlacing & intra
4163  * stuff, I can't imagine that these complex rules are worth it. */
4164 
4165  left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4166  if (FRAME_MBAFF(h)) {
4167  const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4168  const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4169  if (h->mb_y & 1) {
4170  if (left_mb_field_flag != curr_mb_field_flag)
4171  left_xy[LTOP] -= h->mb_stride;
4172  } else {
4173  if (curr_mb_field_flag)
4174  top_xy += h->mb_stride &
4175  (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4176  if (left_mb_field_flag != curr_mb_field_flag)
4177  left_xy[LBOT] += h->mb_stride;
4178  }
4179  }
4180 
4181  h->top_mb_xy = top_xy;
4182  h->left_mb_xy[LTOP] = left_xy[LTOP];
4183  h->left_mb_xy[LBOT] = left_xy[LBOT];
4184  {
4185  /* For sufficiently low qp, filtering wouldn't do anything.
4186  * This is a conservative estimate: could also check beta_offset
4187  * and more accurate chroma_qp. */
4188  int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4189  int qp = h->cur_pic.qscale_table[mb_xy];
4190  if (qp <= qp_thresh &&
4191  (left_xy[LTOP] < 0 ||
4192  ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4193  (top_xy < 0 ||
4194  ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4195  if (!FRAME_MBAFF(h))
4196  return 1;
4197  if ((left_xy[LTOP] < 0 ||
4198  ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4199  (top_xy < h->mb_stride ||
4200  ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4201  return 1;
4202  }
4203  }
4204 
4205  top_type = h->cur_pic.mb_type[top_xy];
4206  left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4207  left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4208  if (h->deblocking_filter == 2) {
4209  if (h->slice_table[top_xy] != h->slice_num)
4210  top_type = 0;
4211  if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4212  left_type[LTOP] = left_type[LBOT] = 0;
4213  } else {
4214  if (h->slice_table[top_xy] == 0xFFFF)
4215  top_type = 0;
4216  if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4217  left_type[LTOP] = left_type[LBOT] = 0;
4218  }
4219  h->top_type = top_type;
4220  h->left_type[LTOP] = left_type[LTOP];
4221  h->left_type[LBOT] = left_type[LBOT];
4222 
4223  if (IS_INTRA(mb_type))
4224  return 0;
4225 
4226  fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4227  top_type, left_type, mb_xy, 0);
4228  if (h->list_count == 2)
4229  fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4230  top_type, left_type, mb_xy, 1);
4231 
4232  nnz = h->non_zero_count[mb_xy];
4233  nnz_cache = h->non_zero_count_cache;
4234  AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4235  AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4236  AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4237  AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4238  h->cbp = h->cbp_table[mb_xy];
4239 
4240  if (top_type) {
4241  nnz = h->non_zero_count[top_xy];
4242  AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4243  }
4244 
4245  if (left_type[LTOP]) {
4246  nnz = h->non_zero_count[left_xy[LTOP]];
4247  nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4248  nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4249  nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4250  nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4251  }
4252 
4253  /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4254  * from what the loop filter needs */
4255  if (!CABAC(h) && h->pps.transform_8x8_mode) {
4256  if (IS_8x8DCT(top_type)) {
4257  nnz_cache[4 + 8 * 0] =
4258  nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4259  nnz_cache[6 + 8 * 0] =
4260  nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4261  }
4262  if (IS_8x8DCT(left_type[LTOP])) {
4263  nnz_cache[3 + 8 * 1] =
4264  nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4265  }
4266  if (IS_8x8DCT(left_type[LBOT])) {
4267  nnz_cache[3 + 8 * 3] =
4268  nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4269  }
4270 
4271  if (IS_8x8DCT(mb_type)) {
4272  nnz_cache[scan8[0]] =
4273  nnz_cache[scan8[1]] =
4274  nnz_cache[scan8[2]] =
4275  nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4276 
4277  nnz_cache[scan8[0 + 4]] =
4278  nnz_cache[scan8[1 + 4]] =
4279  nnz_cache[scan8[2 + 4]] =
4280  nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4281 
4282  nnz_cache[scan8[0 + 8]] =
4283  nnz_cache[scan8[1 + 8]] =
4284  nnz_cache[scan8[2 + 8]] =
4285  nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4286 
4287  nnz_cache[scan8[0 + 12]] =
4288  nnz_cache[scan8[1 + 12]] =
4289  nnz_cache[scan8[2 + 12]] =
4290  nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4291  }
4292  }
4293 
4294  return 0;
4295 }
4296 
4297 static void loop_filter(H264Context *h, int start_x, int end_x)
4298 {
4299  uint8_t *dest_y, *dest_cb, *dest_cr;
4300  int linesize, uvlinesize, mb_x, mb_y;
4301  const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4302  const int old_slice_type = h->slice_type;
4303  const int pixel_shift = h->pixel_shift;
4304  const int block_h = 16 >> h->chroma_y_shift;
4305 
4306  if (h->deblocking_filter) {
4307  for (mb_x = start_x; mb_x < end_x; mb_x++)
4308  for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4309  int mb_xy, mb_type;
4310  mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4311  h->slice_num = h->slice_table[mb_xy];
4312  mb_type = h->cur_pic.mb_type[mb_xy];
4313  h->list_count = h->list_counts[mb_xy];
4314 
4315  if (FRAME_MBAFF(h))
4316  h->mb_mbaff =
4317  h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4318 
4319  h->mb_x = mb_x;
4320  h->mb_y = mb_y;
4321  dest_y = h->cur_pic.f.data[0] +
4322  ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4323  dest_cb = h->cur_pic.f.data[1] +
4324  (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4325  mb_y * h->uvlinesize * block_h;
4326  dest_cr = h->cur_pic.f.data[2] +
4327  (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4328  mb_y * h->uvlinesize * block_h;
4329  // FIXME simplify above
4330 
4331  if (MB_FIELD(h)) {
4332  linesize = h->mb_linesize = h->linesize * 2;
4333  uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4334  if (mb_y & 1) { // FIXME move out of this function?
4335  dest_y -= h->linesize * 15;
4336  dest_cb -= h->uvlinesize * (block_h - 1);
4337  dest_cr -= h->uvlinesize * (block_h - 1);
4338  }
4339  } else {
4340  linesize = h->mb_linesize = h->linesize;
4341  uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4342  }
4343  backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4344  uvlinesize, 0);
4345  if (fill_filter_caches(h, mb_type))
4346  continue;
4347  h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4348  h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4349 
4350  if (FRAME_MBAFF(h)) {
4351  ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4352  linesize, uvlinesize);
4353  } else {
4354  ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4355  dest_cr, linesize, uvlinesize);
4356  }
4357  }
4358  }
4359  h->slice_type = old_slice_type;
4360  h->mb_x = end_x;
4361  h->mb_y = end_mb_y - FRAME_MBAFF(h);
4362  h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4363  h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4364 }
4365 
4367 {
4368  const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4369  int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4370  h->cur_pic.mb_type[mb_xy - 1] :
4371  (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4372  h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4373  h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4374 }
4375 
4376 /**
4377  * Draw edges and report progress for the last MB row.
4378  */
4380 {
4381  int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4382  int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4383  int height = 16 << FRAME_MBAFF(h);
4384  int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4385 
4386  if (h->deblocking_filter) {
4387  if ((top + height) >= pic_height)
4388  height += deblock_border;
4389  top -= deblock_border;
4390  }
4391 
4392  if (top >= pic_height || (top + height) < 0)
4393  return;
4394 
4395  height = FFMIN(height, pic_height - top);
4396  if (top < 0) {
4397  height = top + height;
4398  top = 0;
4399  }
4400 
4401  ff_h264_draw_horiz_band(h, top, height);
4402 
4403  if (h->droppable || h->er.error_occurred)
4404  return;
4405 
4406  ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4408 }
4409 
4410 static void er_add_slice(H264Context *h, int startx, int starty,
4411  int endx, int endy, int status)
4412 {
4413  if (CONFIG_ERROR_RESILIENCE) {
4414  ERContext *er = &h->er;
4415 
4416  ff_er_add_slice(er, startx, starty, endx, endy, status);
4417  }
4418 }
4419 
4420 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4421 {
4422  H264Context *h = *(void **)arg;
4423  int lf_x_start = h->mb_x;
4424 
4425  h->mb_skip_run = -1;
4426 
4427  av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4428 
4430  avctx->codec_id != AV_CODEC_ID_H264 ||
4431  (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4432 
4434  const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
4435  if (start_i) {
4436  int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
4437  prev_status &= ~ VP_START;
4438  if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
4439  h->er.error_occurred = 1;
4440  }
4441  }
4442 
4443  if (h->pps.cabac) {
4444  /* realign */
4445  align_get_bits(&h->gb);
4446 
4447  /* init cabac */
4449  h->gb.buffer + get_bits_count(&h->gb) / 8,
4450  (get_bits_left(&h->gb) + 7) / 8);
4451 
4453 
4454  for (;;) {
4455  // START_TIMER
4456  int ret = ff_h264_decode_mb_cabac(h);
4457  int eos;
4458  // STOP_TIMER("decode_mb_cabac")
4459 
4460  if (ret >= 0)
4462 
4463  // FIXME optimal? or let mb_decode decode 16x32 ?
4464  if (ret >= 0 && FRAME_MBAFF(h)) {
4465  h->mb_y++;
4466 
4467  ret = ff_h264_decode_mb_cabac(h);
4468 
4469  if (ret >= 0)
4471  h->mb_y--;
4472  }
4473  eos = get_cabac_terminate(&h->cabac);
4474 
4475  if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4476  h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4477  er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4478  h->mb_y, ER_MB_END);
4479  if (h->mb_x >= lf_x_start)
4480  loop_filter(h, lf_x_start, h->mb_x + 1);
4481  return 0;
4482  }
4483  if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4484  av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4485  if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4487  "error while decoding MB %d %d, bytestream (%td)\n",
4488  h->mb_x, h->mb_y,
4490  er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4491  h->mb_y, ER_MB_ERROR);
4492  return AVERROR_INVALIDDATA;
4493  }
4494 
4495  if (++h->mb_x >= h->mb_width) {
4496  loop_filter(h, lf_x_start, h->mb_x);
4497  h->mb_x = lf_x_start = 0;
4498  decode_finish_row(h);
4499  ++h->mb_y;
4500  if (FIELD_OR_MBAFF_PICTURE(h)) {
4501  ++h->mb_y;
4502  if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4504  }
4505  }
4506 
4507  if (eos || h->mb_y >= h->mb_height) {
4508  tprintf(h->avctx, "slice end %d %d\n",
4509  get_bits_count(&h->gb), h->gb.size_in_bits);
4510  er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4511  h->mb_y, ER_MB_END);
4512  if (h->mb_x > lf_x_start)
4513  loop_filter(h, lf_x_start, h->mb_x);
4514  return 0;
4515  }
4516  }
4517  } else {
4518  for (;;) {
4519  int ret = ff_h264_decode_mb_cavlc(h);
4520 
4521  if (ret >= 0)
4523 
4524  // FIXME optimal? or let mb_decode decode 16x32 ?
4525  if (ret >= 0 && FRAME_MBAFF(h)) {
4526  h->mb_y++;
4527  ret = ff_h264_decode_mb_cavlc(h);
4528 
4529  if (ret >= 0)
4531  h->mb_y--;
4532  }
4533 
4534  if (ret < 0) {
4536  "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4537  er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4538  h->mb_y, ER_MB_ERROR);
4539  return ret;
4540  }
4541 
4542  if (++h->mb_x >= h->mb_width) {
4543  loop_filter(h, lf_x_start, h->mb_x);
4544  h->mb_x = lf_x_start = 0;
4545  decode_finish_row(h);
4546  ++h->mb_y;
4547  if (FIELD_OR_MBAFF_PICTURE(h)) {
4548  ++h->mb_y;
4549  if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4551  }
4552  if (h->mb_y >= h->mb_height) {
4553  tprintf(h->avctx, "slice end %d %d\n",
4554  get_bits_count(&h->gb), h->gb.size_in_bits);
4555 
4556  if ( get_bits_left(&h->gb) == 0
4557  || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4559  h->mb_x - 1, h->mb_y,
4560  ER_MB_END);
4561 
4562  return 0;
4563  } else {
4565  h->mb_x, h->mb_y,
4566  ER_MB_END);
4567 
4568  return AVERROR_INVALIDDATA;
4569  }
4570  }
4571  }
4572 
4573  if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4574  tprintf(h->avctx, "slice end %d %d\n",
4575  get_bits_count(&h->gb), h->gb.size_in_bits);
4576 
4577  if (get_bits_left(&h->gb) == 0) {
4579  h->mb_x - 1, h->mb_y,
4580  ER_MB_END);
4581  if (h->mb_x > lf_x_start)
4582  loop_filter(h, lf_x_start, h->mb_x);
4583 
4584  return 0;
4585  } else {
4586  er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4587  h->mb_y, ER_MB_ERROR);
4588 
4589  return AVERROR_INVALIDDATA;
4590  }
4591  }
4592  }
4593  }
4594 }
4595 
4596 /**
4597  * Call decode_slice() for each context.
4598  *
4599  * @param h h264 master context
4600  * @param context_count number of contexts to execute
4601  */
4602 static int execute_decode_slices(H264Context *h, int context_count)
4603 {
4604  AVCodecContext *const avctx = h->avctx;
4605  H264Context *hx;
4606  int i;
4607 
4608  av_assert0(h->mb_y < h->mb_height);
4609 
4610  if (h->avctx->hwaccel ||
4611  h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4612  return 0;
4613  if (context_count == 1) {
4614  return decode_slice(avctx, &h);
4615  } else {
4616  av_assert0(context_count > 0);
4617  for (i = 1; i < context_count; i++) {
4618  hx = h->thread_context[i];
4619  if (CONFIG_ERROR_RESILIENCE) {
4620  hx->er.error_count = 0;
4621  }
4622  hx->x264_build = h->x264_build;
4623  }
4624 
4625  avctx->execute(avctx, decode_slice, h->thread_context,
4626  NULL, context_count, sizeof(void *));
4627 
4628  /* pull back stuff from slices to master context */
4629  hx = h->thread_context[context_count - 1];
4630  h->mb_x = hx->mb_x;
4631  h->mb_y = hx->mb_y;
4632  h->droppable = hx->droppable;
4634  if (CONFIG_ERROR_RESILIENCE) {
4635  for (i = 1; i < context_count; i++)
4637  }
4638  }
4639 
4640  return 0;
4641 }
4642 
4643 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
4644 
4645 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4646  int parse_extradata)
4647 {
4648  AVCodecContext *const avctx = h->avctx;
4649  H264Context *hx; ///< thread context
4650  int buf_index;
4651  int context_count;
4652  int next_avc;
4653  int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4654  int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4655  int nal_index;
4656  int idr_cleared=0;
4657  int first_slice = 0;
4658  int ret = 0;
4659 
4660  h->nal_unit_type= 0;
4661 
4662  if(!h->slice_context_count)
4663  h->slice_context_count= 1;
4665  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4666  h->current_slice = 0;
4667  if (!h->first_field)
4668  h->cur_pic_ptr = NULL;
4669  ff_h264_reset_sei(h);
4670  }
4671 
4672  if (h->nal_length_size == 4) {
4673  if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4674  h->is_avc = 0;
4675  }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4676  h->is_avc = 1;
4677  }
4678 
4679  for (; pass <= 1; pass++) {
4680  buf_index = 0;
4681  context_count = 0;
4682  next_avc = h->is_avc ? 0 : buf_size;
4683  nal_index = 0;
4684  for (;;) {
4685  int consumed;
4686  int dst_length;
4687  int bit_length;
4688  const uint8_t *ptr;
4689  int i, nalsize = 0;
4690  int err;
4691 
4692  if (buf_index >= next_avc) {
4693  if (buf_index >= buf_size - h->nal_length_size)
4694  break;
4695  nalsize = 0;
4696  for (i = 0; i < h->nal_length_size; i++)
4697  nalsize = (nalsize << 8) | buf[buf_index++];
4698  if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4700  "AVC: nal size %d\n", nalsize);
4701  break;
4702  }
4703  next_avc = buf_index + nalsize;
4704  } else {
4705  // start code prefix search
4706  for (; buf_index + 3 < next_avc; buf_index++)
4707  // This should always succeed in the first iteration.
4708  if (buf[buf_index] == 0 &&
4709  buf[buf_index + 1] == 0 &&
4710  buf[buf_index + 2] == 1)
4711  break;
4712 
4713  if (buf_index + 3 >= buf_size) {
4714  buf_index = buf_size;
4715  break;
4716  }
4717 
4718  buf_index += 3;
4719  if (buf_index >= next_avc)
4720  continue;
4721  }
4722 
4723  hx = h->thread_context[context_count];
4724 
4725  ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4726  &consumed, next_avc - buf_index);
4727  if (ptr == NULL || dst_length < 0) {
4728  ret = -1;
4729  goto end;
4730  }
4731  i = buf_index + consumed;
4732  if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4733  buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4734  buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4736 
4737  if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4738  while(dst_length > 0 && ptr[dst_length - 1] == 0)
4739  dst_length--;
4740  bit_length = !dst_length ? 0
4741  : (8 * dst_length -
4742  decode_rbsp_trailing(h, ptr + dst_length - 1));
4743 
4744  if (h->avctx->debug & FF_DEBUG_STARTCODE)
4745  av_log(h->avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4746 
4747  if (h->is_avc && (nalsize != consumed) && nalsize)
4749  "AVC: Consumed only %d bytes instead of %d\n",
4750  consumed, nalsize);
4751 
4752  buf_index += consumed;
4753  nal_index++;
4754 
4755  if (pass == 0) {
4756  /* packets can sometimes contain multiple PPS/SPS,
4757  * e.g. two PAFF field pictures in one packet, or a demuxer
4758  * which splits NALs strangely if so, when frame threading we
4759  * can't start the next thread until we've read all of them */
4760  switch (hx->nal_unit_type) {
4761  case NAL_SPS:
4762  case NAL_PPS:
4763  nals_needed = nal_index;
4764  break;
4765  case NAL_DPA:
4766  case NAL_IDR_SLICE:
4767  case NAL_SLICE:
4768  init_get_bits(&hx->gb, ptr, bit_length);
4769  if (!get_ue_golomb(&hx->gb) || !first_slice)
4770  nals_needed = nal_index;
4771  if (!first_slice)
4772  first_slice = hx->nal_unit_type;
4773  }
4774  continue;
4775  }
4776 
4777  if (!first_slice)
4778  switch (hx->nal_unit_type) {
4779  case NAL_DPA:
4780  case NAL_IDR_SLICE:
4781  case NAL_SLICE:
4782  first_slice = hx->nal_unit_type;
4783  }
4784 
4785  if (avctx->skip_frame >= AVDISCARD_NONREF &&
4786  h->nal_ref_idc == 0 &&
4787  h->nal_unit_type != NAL_SEI)
4788  continue;
4789 
4790 again:
4791  /* Ignore per frame NAL unit type during extradata
4792  * parsing. Decoding slices is not possible in codec init
4793  * with frame-mt */
4794  if (parse_extradata) {
4795  switch (hx->nal_unit_type) {
4796  case NAL_IDR_SLICE:
4797  case NAL_SLICE:
4798  case NAL_DPA:
4799  case NAL_DPB:
4800  case NAL_DPC:
4802  "Ignoring NAL %d in global header/extradata\n",
4803  hx->nal_unit_type);
4804  // fall through to next case
4805  case NAL_AUXILIARY_SLICE:
4807  }
4808  }
4809 
4810  err = 0;
4811 
4812  switch (hx->nal_unit_type) {
4813  case NAL_IDR_SLICE:
4814  if (first_slice != NAL_IDR_SLICE) {
4816  "Invalid mix of idr and non-idr slices\n");
4817  ret = -1;
4818  goto end;
4819  }
4820  if(!idr_cleared)
4821  idr(h); // FIXME ensure we don't lose some frames if there is reordering
4822  idr_cleared = 1;
4823  case NAL_SLICE:
4824  init_get_bits(&hx->gb, ptr, bit_length);
4825  hx->intra_gb_ptr =
4826  hx->inter_gb_ptr = &hx->gb;
4827  hx->data_partitioning = 0;
4828 
4829  if ((err = decode_slice_header(hx, h)))
4830  break;
4831 
4833  h->valid_recovery_point = 1;
4834 
4835  if ( h->sei_recovery_frame_cnt >= 0
4836  && ( h->recovery_frame<0
4837  || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
4839  (1 << h->sps.log2_max_frame_num);
4840 
4841  if (!h->valid_recovery_point)
4842  h->recovery_frame = h->frame_num;
4843  }
4844 
4845  h->cur_pic_ptr->f.key_frame |=
4846  (hx->nal_unit_type == NAL_IDR_SLICE);
4847 
4848  if (h->recovery_frame == h->frame_num) {
4849  h->cur_pic_ptr->sync |= 1;
4850  h->recovery_frame = -1;
4851  }
4852 
4853  h->sync |= !!h->cur_pic_ptr->f.key_frame;
4854  h->sync |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4855  h->cur_pic_ptr->sync |= h->sync;
4856 
4857  if (h->current_slice == 1) {
4858  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4859  decode_postinit(h, nal_index >= nals_needed);
4860 
4861  if (h->avctx->hwaccel &&
4862  (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4863  return ret;
4864  if (CONFIG_H264_VDPAU_DECODER &&
4865  h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4867  }
4868 
4869  if (hx->redundant_pic_count == 0 &&
4870  (avctx->skip_frame < AVDISCARD_NONREF ||
4871  hx->nal_ref_idc) &&
4872  (avctx->skip_frame < AVDISCARD_BIDIR ||
4874  (avctx->skip_frame < AVDISCARD_NONKEY ||
4876  avctx->skip_frame < AVDISCARD_ALL) {
4877  if (avctx->hwaccel) {
4878  ret = avctx->hwaccel->decode_slice(avctx,
4879  &buf[buf_index - consumed],
4880  consumed);
4881  if (ret < 0)
4882  return ret;
4883  } else if (CONFIG_H264_VDPAU_DECODER &&
4884  h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4886  start_code,
4887  sizeof(start_code));
4889  &buf[buf_index - consumed],
4890  consumed);
4891  } else
4892  context_count++;
4893  }
4894  break;
4895  case NAL_DPA:
4896  init_get_bits(&hx->gb, ptr, bit_length);
4897  hx->intra_gb_ptr =
4898  hx->inter_gb_ptr = NULL;
4899 
4900  if ((err = decode_slice_header(hx, h)) < 0)
4901  break;
4902 
4903  hx->data_partitioning = 1;
4904  break;
4905  case NAL_DPB:
4906  init_get_bits(&hx->intra_gb, ptr, bit_length);
4907  hx->intra_gb_ptr = &hx->intra_gb;
4908  break;
4909  case NAL_DPC:
4910  init_get_bits(&hx->inter_gb, ptr, bit_length);
4911  hx->inter_gb_ptr = &hx->inter_gb;
4912 
4913  av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
4914  break;
4915 
4916  if (hx->redundant_pic_count == 0 &&
4917  hx->intra_gb_ptr &&
4918  hx->data_partitioning &&
4919  h->cur_pic_ptr && h->context_initialized &&
4920  (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4921  (avctx->skip_frame < AVDISCARD_BIDIR ||
4923  (avctx->skip_frame < AVDISCARD_NONKEY ||
4925  avctx->skip_frame < AVDISCARD_ALL)
4926  context_count++;
4927  break;
4928  case NAL_SEI:
4929  init_get_bits(&h->gb, ptr, bit_length);
4930  ff_h264_decode_sei(h);
4931  break;
4932  case NAL_SPS:
4933  init_get_bits(&h->gb, ptr, bit_length);
4934  if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
4936  "SPS decoding failure, trying again with the complete NAL\n");
4937  if (h->is_avc)
4938  av_assert0(next_avc - buf_index + consumed == nalsize);
4939  if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
4940  break;
4941  init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
4942  8*(next_avc - buf_index + consumed - 1));
4944  }
4945 
4946  break;
4947  case NAL_PPS:
4948  init_get_bits(&h->gb, ptr, bit_length);
4949  ff_h264_decode_picture_parameter_set(h, bit_length);
4950  break;
4951  case NAL_AUD:
4952  case NAL_END_SEQUENCE:
4953  case NAL_END_STREAM:
4954  case NAL_FILLER_DATA:
4955  case NAL_SPS_EXT:
4956  case NAL_AUXILIARY_SLICE:
4957  break;
4958  case NAL_FF_IGNORE:
4959  break;
4960  default:
4961  av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4962  hx->nal_unit_type, bit_length);
4963  }
4964 
4965  if (context_count == h->max_contexts) {
4966  execute_decode_slices(h, context_count);
4967  context_count = 0;
4968  }
4969 
4970  if (err < 0)
4971  av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4972  else if (err == 1) {
4973  /* Slice could not be decoded in parallel mode, copy down
4974  * NAL unit stuff to context 0 and restart. Note that
4975  * rbsp_buffer is not transferred, but since we no longer
4976  * run in parallel mode this should not be an issue. */
4977  h->nal_unit_type = hx->nal_unit_type;
4978  h->nal_ref_idc = hx->nal_ref_idc;
4979  hx = h;
4980  goto again;
4981  }
4982  }
4983  }
4984  if (context_count)
4985  execute_decode_slices(h, context_count);
4986 
4987 end:
4988  /* clean up */
4989  if (h->cur_pic_ptr && !h->droppable) {
4992  }
4993 
4994  return (ret < 0) ? ret : buf_index;
4995 }
4996 
4997 /**
4998  * Return the number of bytes consumed for building the current frame.
4999  */
5000 static int get_consumed_bytes(int pos, int buf_size)
5001 {
5002  if (pos == 0)
5003  pos = 1; // avoid infinite loops (i doubt that is needed but ...)
5004  if (pos + 10 > buf_size)
5005  pos = buf_size; // oops ;)
5006 
5007  return pos;
5008 }
5009 
5011 {
5012  AVFrame *src = &srcp->f;
5013  int i;
5014  int ret = av_frame_ref(dst, src);
5015  if (ret < 0)
5016  return ret;
5017 
5018  av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
5019 
5020  if (!srcp->crop)
5021  return 0;
5022 
5023  for (i = 0; i < 3; i++) {
5024  int hshift = (i > 0) ? h->chroma_x_shift : 0;
5025  int vshift = (i > 0) ? h->chroma_y_shift : 0;
5026  int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
5027  (srcp->crop_top >> vshift) * dst->linesize[i];
5028  dst->data[i] += off;
5029  }
5030  return 0;
5031 }
5032 
5033 static int decode_frame(AVCodecContext *avctx, void *data,
5034  int *got_frame, AVPacket *avpkt)
5035 {
5036  const uint8_t *buf = avpkt->data;
5037  int buf_size = avpkt->size;
5038  H264Context *h = avctx->priv_data;
5039  AVFrame *pict = data;
5040  int buf_index = 0;
5041  Picture *out;
5042  int i, out_idx;
5043  int ret;
5044 
5045  h->flags = avctx->flags;
5046 
5047  /* end of stream, output what is still in the buffers */
5048  if (buf_size == 0) {
5049  out:
5050 
5051  h->cur_pic_ptr = NULL;
5052  h->first_field = 0;
5053 
5054  // FIXME factorize this with the output code below
5055  out = h->delayed_pic[0];
5056  out_idx = 0;
5057  for (i = 1;
5058  h->delayed_pic[i] &&
5059  !h->delayed_pic[i]->f.key_frame &&
5060  !h->delayed_pic[i]->mmco_reset;
5061  i++)
5062  if (h->delayed_pic[i]->poc < out->poc) {
5063  out = h->delayed_pic[i];
5064  out_idx = i;
5065  }
5066 
5067  for (i = out_idx; h->delayed_pic[i]; i++)
5068  h->delayed_pic[i] = h->delayed_pic[i + 1];
5069 
5070  if (out) {
5071  out->reference &= ~DELAYED_PIC_REF;
5072  ret = output_frame(h, pict, out);
5073  if (ret < 0)
5074  return ret;
5075  *got_frame = 1;
5076  }
5077 
5078  return buf_index;
5079  }
5080  if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
5081  int cnt= buf[5]&0x1f;
5082  const uint8_t *p= buf+6;
5083  while(cnt--){
5084  int nalsize= AV_RB16(p) + 2;
5085  if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
5086  goto not_extra;
5087  p += nalsize;
5088  }
5089  cnt = *(p++);
5090  if(!cnt)
5091  goto not_extra;
5092  while(cnt--){
5093  int nalsize= AV_RB16(p) + 2;
5094  if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
5095  goto not_extra;
5096  p += nalsize;
5097  }
5098 
5099  return ff_h264_decode_extradata(h, buf, buf_size);
5100  }
5101 not_extra:
5102 
5103  buf_index = decode_nal_units(h, buf, buf_size, 0);
5104  if (buf_index < 0)
5105  return AVERROR_INVALIDDATA;
5106 
5107  if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
5108  av_assert0(buf_index <= buf_size);
5109  goto out;
5110  }
5111 
5112  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
5113  if (avctx->skip_frame >= AVDISCARD_NONREF ||
5114  buf_size >= 4 && !memcmp("Q264", buf, 4))
5115  return buf_size;
5116  av_log(avctx, AV_LOG_ERROR, "no frame!\n");
5117  return AVERROR_INVALIDDATA;
5118  }
5119 
5120  if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
5121  (h->mb_y >= h->mb_height && h->mb_height)) {
5122  if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
5123  decode_postinit(h, 1);
5124 
5125  field_end(h, 0);
5126 
5127  /* Wait for second field. */
5128  *got_frame = 0;
5129  if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
5130  ret = output_frame(h, pict, h->next_output_pic);
5131  if (ret < 0)
5132  return ret;
5133  *got_frame = 1;
5134  if (CONFIG_MPEGVIDEO) {
5136  &h->low_delay,
5137  h->mb_width, h->mb_height, h->mb_stride, 1);
5138  }
5139  }
5140  }
5141 
5142  assert(pict->data[0] || !*got_frame);
5143 
5144  return get_consumed_bytes(buf_index, buf_size);
5145 }
5146 
5148 {
5149  int i;
5150 
5151  free_tables(h, 1); // FIXME cleanup init stuff perhaps
5152 
5153  for (i = 0; i < MAX_SPS_COUNT; i++)
5154  av_freep(h->sps_buffers + i);
5155 
5156  for (i = 0; i < MAX_PPS_COUNT; i++)
5157  av_freep(h->pps_buffers + i);
5158 }
5159 
5161 {
5162  H264Context *h = avctx->priv_data;
5163 
5166 
5167  unref_picture(h, &h->cur_pic);
5168 
5169  return 0;
5170 }
5171 
5172 static const AVProfile profiles[] = {
5173  { FF_PROFILE_H264_BASELINE, "Baseline" },
5174  { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
5175  { FF_PROFILE_H264_MAIN, "Main" },
5176  { FF_PROFILE_H264_EXTENDED, "Extended" },
5177  { FF_PROFILE_H264_HIGH, "High" },
5178  { FF_PROFILE_H264_HIGH_10, "High 10" },
5179  { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
5180  { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
5181  { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
5182  { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
5183  { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
5184  { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
5185  { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
5186  { FF_PROFILE_UNKNOWN },
5187 };
5188 
5189 static const AVOption h264_options[] = {
5190  {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
5191  {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
5192  {NULL}
5193 };
5194 
5195 static const AVClass h264_class = {
5196  .class_name = "H264 Decoder",
5197  .item_name = av_default_item_name,
5198  .option = h264_options,
5199  .version = LIBAVUTIL_VERSION_INT,
5200 };
5201 
5202 static const AVClass h264_vdpau_class = {
5203  .class_name = "H264 VDPAU Decoder",
5204  .item_name = av_default_item_name,
5205  .option = h264_options,
5206  .version = LIBAVUTIL_VERSION_INT,
5207 };
5208 
5210  .name = "h264",
5211  .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5212  .type = AVMEDIA_TYPE_VIDEO,
5213  .id = AV_CODEC_ID_H264,
5214  .priv_data_size = sizeof(H264Context),
5217  .decode = decode_frame,
5218  .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5221  .flush = flush_dpb,
5223  .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5224  .profiles = NULL_IF_CONFIG_SMALL(profiles),
5225  .priv_class = &h264_class,
5226 };
5227 
5228 #if CONFIG_H264_VDPAU_DECODER
5229 AVCodec ff_h264_vdpau_decoder = {
5230  .name = "h264_vdpau",
5231  .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
5232  .type = AVMEDIA_TYPE_VIDEO,
5233  .id = AV_CODEC_ID_H264,
5234  .priv_data_size = sizeof(H264Context),
5237  .decode = decode_frame,
5238  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5239  .flush = flush_dpb,
5240  .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
5241  AV_PIX_FMT_NONE},
5242  .profiles = NULL_IF_CONFIG_SMALL(profiles),
5243  .priv_class = &h264_vdpau_class,
5244 };
5245 #endif