86d453bba7835bedcffbbbaf4f6f37d34fb8bd7c
[libav.git] / libavcodec / h264.c
1 /*
2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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 * Libav 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 Libav; 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 #include "libavutil/avassert.h"
29 #include "libavutil/imgutils.h"
30 #include "internal.h"
31 #include "cabac.h"
32 #include "cabac_functions.h"
33 #include "dsputil.h"
34 #include "error_resilience.h"
35 #include "avcodec.h"
36 #include "mpegvideo.h"
37 #include "h264.h"
38 #include "h264data.h"
39 #include "h264chroma.h"
40 #include "h264_mvpred.h"
41 #include "golomb.h"
42 #include "mathops.h"
43 #include "rectangle.h"
44 #include "svq3.h"
45 #include "thread.h"
46
47 #include <assert.h>
48
49 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
50
51 static const uint8_t rem6[QP_MAX_NUM + 1] = {
52 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
53 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
54 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
55 };
56
57 static const uint8_t div6[QP_MAX_NUM + 1] = {
58 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
59 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
60 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
61 };
62
63 static const uint8_t field_scan[16] = {
64 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
65 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
66 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
67 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
68 };
69
70 static const uint8_t field_scan8x8[64] = {
71 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
72 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
73 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
74 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
75 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
76 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
77 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
78 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
79 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
80 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
81 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
82 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
83 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
84 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
85 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
86 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
87 };
88
89 static const uint8_t field_scan8x8_cavlc[64] = {
90 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
91 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
92 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
93 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
94 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
95 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
96 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
97 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
98 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
99 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
100 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
101 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
102 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
103 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
104 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
105 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
106 };
107
108 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
109 static const uint8_t zigzag_scan8x8_cavlc[64] = {
110 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
111 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
112 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
113 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
114 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
115 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
116 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
117 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
118 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
119 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
120 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
121 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
122 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
123 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
124 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
125 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
126 };
127
128 static const uint8_t dequant4_coeff_init[6][3] = {
129 { 10, 13, 16 },
130 { 11, 14, 18 },
131 { 13, 16, 20 },
132 { 14, 18, 23 },
133 { 16, 20, 25 },
134 { 18, 23, 29 },
135 };
136
137 static const uint8_t dequant8_coeff_init_scan[16] = {
138 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
139 };
140
141 static const uint8_t dequant8_coeff_init[6][6] = {
142 { 20, 18, 32, 19, 25, 24 },
143 { 22, 19, 35, 21, 28, 26 },
144 { 26, 23, 42, 24, 33, 31 },
145 { 28, 25, 45, 26, 35, 33 },
146 { 32, 28, 51, 30, 40, 38 },
147 { 36, 32, 58, 34, 46, 43 },
148 };
149
150 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
151 #if CONFIG_H264_DXVA2_HWACCEL
152 AV_PIX_FMT_DXVA2_VLD,
153 #endif
154 #if CONFIG_H264_VAAPI_HWACCEL
155 AV_PIX_FMT_VAAPI_VLD,
156 #endif
157 #if CONFIG_H264_VDA_HWACCEL
158 AV_PIX_FMT_VDA_VLD,
159 #endif
160 #if CONFIG_H264_VDPAU_HWACCEL
161 AV_PIX_FMT_VDPAU,
162 #endif
163 AV_PIX_FMT_YUV420P,
164 AV_PIX_FMT_NONE
165 };
166
167 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
168 #if CONFIG_H264_DXVA2_HWACCEL
169 AV_PIX_FMT_DXVA2_VLD,
170 #endif
171 #if CONFIG_H264_VAAPI_HWACCEL
172 AV_PIX_FMT_VAAPI_VLD,
173 #endif
174 #if CONFIG_H264_VDA_HWACCEL
175 AV_PIX_FMT_VDA_VLD,
176 #endif
177 #if CONFIG_H264_VDPAU_HWACCEL
178 AV_PIX_FMT_VDPAU,
179 #endif
180 AV_PIX_FMT_YUVJ420P,
181 AV_PIX_FMT_NONE
182 };
183
184 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
185 int (*mv)[2][4][2],
186 int mb_x, int mb_y, int mb_intra, int mb_skipped)
187 {
188 H264Context *h = opaque;
189
190 h->mb_x = mb_x;
191 h->mb_y = mb_y;
192 h->mb_xy = mb_x + mb_y * h->mb_stride;
193 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
194 assert(ref >= 0);
195 /* FIXME: It is possible albeit uncommon that slice references
196 * differ between slices. We take the easy approach and ignore
197 * it for now. If this turns out to have any relevance in
198 * practice then correct remapping should be added. */
199 if (ref >= h->ref_count[0])
200 ref = 0;
201 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
202 2, 2, 2, ref, 1);
203 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
204 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
205 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
206 assert(!FRAME_MBAFF(h));
207 ff_h264_hl_decode_mb(h);
208 }
209
210 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
211 {
212 AVCodecContext *avctx = h->avctx;
213 Picture *cur = &h->cur_pic;
214 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
215 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
216 int vshift = desc->log2_chroma_h;
217 const int field_pic = h->picture_structure != PICT_FRAME;
218 if (field_pic) {
219 height <<= 1;
220 y <<= 1;
221 }
222
223 height = FFMIN(height, avctx->height - y);
224
225 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
226 return;
227
228 if (avctx->draw_horiz_band) {
229 AVFrame *src;
230 int offset[AV_NUM_DATA_POINTERS];
231 int i;
232
233 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
234 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
235 src = &cur->f;
236 else if (last)
237 src = &last->f;
238 else
239 return;
240
241 offset[0] = y * src->linesize[0];
242 offset[1] =
243 offset[2] = (y >> vshift) * src->linesize[1];
244 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
245 offset[i] = 0;
246
247 emms_c();
248
249 avctx->draw_horiz_band(avctx, src, offset,
250 y, h->picture_structure, height);
251 }
252 }
253
254 static void unref_picture(H264Context *h, Picture *pic)
255 {
256 int off = offsetof(Picture, tf) + sizeof(pic->tf);
257 int i;
258
259 if (!pic->f.buf[0])
260 return;
261
262 ff_thread_release_buffer(h->avctx, &pic->tf);
263 av_buffer_unref(&pic->hwaccel_priv_buf);
264
265 av_buffer_unref(&pic->qscale_table_buf);
266 av_buffer_unref(&pic->mb_type_buf);
267 for (i = 0; i < 2; i++) {
268 av_buffer_unref(&pic->motion_val_buf[i]);
269 av_buffer_unref(&pic->ref_index_buf[i]);
270 }
271
272 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
273 }
274
275 static void release_unused_pictures(H264Context *h, int remove_current)
276 {
277 int i;
278
279 /* release non reference frames */
280 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
281 if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
282 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
283 unref_picture(h, &h->DPB[i]);
284 }
285 }
286 }
287
288 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
289 {
290 int ret, i;
291
292 av_assert0(!dst->f.buf[0]);
293 av_assert0(src->f.buf[0]);
294
295 src->tf.f = &src->f;
296 dst->tf.f = &dst->f;
297 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
298 if (ret < 0)
299 goto fail;
300
301 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
302 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
303 if (!dst->qscale_table_buf || !dst->mb_type_buf)
304 goto fail;
305 dst->qscale_table = src->qscale_table;
306 dst->mb_type = src->mb_type;
307
308 for (i = 0; i < 2; i++) {
309 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
310 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
311 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
312 goto fail;
313 dst->motion_val[i] = src->motion_val[i];
314 dst->ref_index[i] = src->ref_index[i];
315 }
316
317 if (src->hwaccel_picture_private) {
318 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
319 if (!dst->hwaccel_priv_buf)
320 goto fail;
321 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
322 }
323
324 for (i = 0; i < 2; i++)
325 dst->field_poc[i] = src->field_poc[i];
326
327 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
328 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
329
330 dst->poc = src->poc;
331 dst->frame_num = src->frame_num;
332 dst->mmco_reset = src->mmco_reset;
333 dst->pic_id = src->pic_id;
334 dst->long_ref = src->long_ref;
335 dst->mbaff = src->mbaff;
336 dst->field_picture = src->field_picture;
337 dst->needs_realloc = src->needs_realloc;
338 dst->reference = src->reference;
339 dst->recovered = src->recovered;
340
341 return 0;
342 fail:
343 unref_picture(h, dst);
344 return ret;
345 }
346
347 static int alloc_scratch_buffers(H264Context *h, int linesize)
348 {
349 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
350
351 if (h->bipred_scratchpad)
352 return 0;
353
354 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
355 // edge emu needs blocksize + filter length - 1
356 // (= 21x21 for h264)
357 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
358 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
359
360 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
361 av_freep(&h->bipred_scratchpad);
362 av_freep(&h->edge_emu_buffer);
363 av_freep(&h->me.scratchpad);
364 return AVERROR(ENOMEM);
365 }
366
367 h->me.temp = h->me.scratchpad;
368
369 return 0;
370 }
371
372 static int init_table_pools(H264Context *h)
373 {
374 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
375 const int mb_array_size = h->mb_stride * h->mb_height;
376 const int b4_stride = h->mb_width * 4 + 1;
377 const int b4_array_size = b4_stride * h->mb_height * 4;
378
379 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
380 av_buffer_allocz);
381 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
382 sizeof(uint32_t), av_buffer_allocz);
383 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
384 sizeof(int16_t), av_buffer_allocz);
385 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
386
387 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
388 !h->ref_index_pool) {
389 av_buffer_pool_uninit(&h->qscale_table_pool);
390 av_buffer_pool_uninit(&h->mb_type_pool);
391 av_buffer_pool_uninit(&h->motion_val_pool);
392 av_buffer_pool_uninit(&h->ref_index_pool);
393 return AVERROR(ENOMEM);
394 }
395
396 return 0;
397 }
398
399 static int alloc_picture(H264Context *h, Picture *pic)
400 {
401 int i, ret = 0;
402
403 av_assert0(!pic->f.data[0]);
404
405 pic->tf.f = &pic->f;
406 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
407 AV_GET_BUFFER_FLAG_REF : 0);
408 if (ret < 0)
409 goto fail;
410
411 h->linesize = pic->f.linesize[0];
412 h->uvlinesize = pic->f.linesize[1];
413
414 if (h->avctx->hwaccel) {
415 const AVHWAccel *hwaccel = h->avctx->hwaccel;
416 av_assert0(!pic->hwaccel_picture_private);
417 if (hwaccel->priv_data_size) {
418 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
419 if (!pic->hwaccel_priv_buf)
420 return AVERROR(ENOMEM);
421 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
422 }
423 }
424
425 if (!h->qscale_table_pool) {
426 ret = init_table_pools(h);
427 if (ret < 0)
428 goto fail;
429 }
430
431 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
432 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
433 if (!pic->qscale_table_buf || !pic->mb_type_buf)
434 goto fail;
435
436 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
437 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
438
439 for (i = 0; i < 2; i++) {
440 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
441 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
442 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
443 goto fail;
444
445 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
446 pic->ref_index[i] = pic->ref_index_buf[i]->data;
447 }
448
449 return 0;
450 fail:
451 unref_picture(h, pic);
452 return (ret < 0) ? ret : AVERROR(ENOMEM);
453 }
454
455 static inline int pic_is_unused(H264Context *h, Picture *pic)
456 {
457 if (!pic->f.buf[0])
458 return 1;
459 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
460 return 1;
461 return 0;
462 }
463
464 static int find_unused_picture(H264Context *h)
465 {
466 int i;
467
468 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
469 if (pic_is_unused(h, &h->DPB[i]))
470 break;
471 }
472 if (i == MAX_PICTURE_COUNT)
473 return AVERROR_INVALIDDATA;
474
475 if (h->DPB[i].needs_realloc) {
476 h->DPB[i].needs_realloc = 0;
477 unref_picture(h, &h->DPB[i]);
478 }
479
480 return i;
481 }
482
483 /**
484 * Check if the top & left blocks are available if needed and
485 * change the dc mode so it only uses the available blocks.
486 */
487 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
488 {
489 static const int8_t top[12] = {
490 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
491 };
492 static const int8_t left[12] = {
493 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
494 };
495 int i;
496
497 if (!(h->top_samples_available & 0x8000)) {
498 for (i = 0; i < 4; i++) {
499 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
500 if (status < 0) {
501 av_log(h->avctx, AV_LOG_ERROR,
502 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
503 status, h->mb_x, h->mb_y);
504 return AVERROR_INVALIDDATA;
505 } else if (status) {
506 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
507 }
508 }
509 }
510
511 if ((h->left_samples_available & 0x8888) != 0x8888) {
512 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
513 for (i = 0; i < 4; i++)
514 if (!(h->left_samples_available & mask[i])) {
515 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
516 if (status < 0) {
517 av_log(h->avctx, AV_LOG_ERROR,
518 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
519 status, h->mb_x, h->mb_y);
520 return AVERROR_INVALIDDATA;
521 } else if (status) {
522 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
523 }
524 }
525 }
526
527 return 0;
528 } // FIXME cleanup like ff_h264_check_intra_pred_mode
529
530 /**
531 * Check if the top & left blocks are available if needed and
532 * change the dc mode so it only uses the available blocks.
533 */
534 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
535 {
536 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
537 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
538
539 if (mode > 6U) {
540 av_log(h->avctx, AV_LOG_ERROR,
541 "out of range intra chroma pred mode at %d %d\n",
542 h->mb_x, h->mb_y);
543 return AVERROR_INVALIDDATA;
544 }
545
546 if (!(h->top_samples_available & 0x8000)) {
547 mode = top[mode];
548 if (mode < 0) {
549 av_log(h->avctx, AV_LOG_ERROR,
550 "top block unavailable for requested intra mode at %d %d\n",
551 h->mb_x, h->mb_y);
552 return AVERROR_INVALIDDATA;
553 }
554 }
555
556 if ((h->left_samples_available & 0x8080) != 0x8080) {
557 mode = left[mode];
558 if (is_chroma && (h->left_samples_available & 0x8080)) {
559 // mad cow disease mode, aka MBAFF + constrained_intra_pred
560 mode = ALZHEIMER_DC_L0T_PRED8x8 +
561 (!(h->left_samples_available & 0x8000)) +
562 2 * (mode == DC_128_PRED8x8);
563 }
564 if (mode < 0) {
565 av_log(h->avctx, AV_LOG_ERROR,
566 "left block unavailable for requested intra mode at %d %d\n",
567 h->mb_x, h->mb_y);
568 return AVERROR_INVALIDDATA;
569 }
570 }
571
572 return mode;
573 }
574
575 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
576 int *dst_length, int *consumed, int length)
577 {
578 int i, si, di;
579 uint8_t *dst;
580 int bufidx;
581
582 // src[0]&0x80; // forbidden bit
583 h->nal_ref_idc = src[0] >> 5;
584 h->nal_unit_type = src[0] & 0x1F;
585
586 src++;
587 length--;
588
589 #define STARTCODE_TEST \
590 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
591 if (src[i + 2] != 3) { \
592 /* startcode, so we must be past the end */ \
593 length = i; \
594 } \
595 break; \
596 }
597
598 #if HAVE_FAST_UNALIGNED
599 #define FIND_FIRST_ZERO \
600 if (i > 0 && !src[i]) \
601 i--; \
602 while (src[i]) \
603 i++
604
605 #if HAVE_FAST_64BIT
606 for (i = 0; i + 1 < length; i += 9) {
607 if (!((~AV_RN64A(src + i) &
608 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
609 0x8000800080008080ULL))
610 continue;
611 FIND_FIRST_ZERO;
612 STARTCODE_TEST;
613 i -= 7;
614 }
615 #else
616 for (i = 0; i + 1 < length; i += 5) {
617 if (!((~AV_RN32A(src + i) &
618 (AV_RN32A(src + i) - 0x01000101U)) &
619 0x80008080U))
620 continue;
621 FIND_FIRST_ZERO;
622 STARTCODE_TEST;
623 i -= 3;
624 }
625 #endif
626 #else
627 for (i = 0; i + 1 < length; i += 2) {
628 if (src[i])
629 continue;
630 if (i > 0 && src[i - 1] == 0)
631 i--;
632 STARTCODE_TEST;
633 }
634 #endif
635
636 if (i >= length - 1) { // no escaped 0
637 *dst_length = length;
638 *consumed = length + 1; // +1 for the header
639 return src;
640 }
641
642 // use second escape buffer for inter data
643 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
644 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
645 length + FF_INPUT_BUFFER_PADDING_SIZE);
646 dst = h->rbsp_buffer[bufidx];
647
648 if (dst == NULL)
649 return NULL;
650
651 memcpy(dst, src, i);
652 si = di = i;
653 while (si + 2 < length) {
654 // remove escapes (very rare 1:2^22)
655 if (src[si + 2] > 3) {
656 dst[di++] = src[si++];
657 dst[di++] = src[si++];
658 } else if (src[si] == 0 && src[si + 1] == 0) {
659 if (src[si + 2] == 3) { // escape
660 dst[di++] = 0;
661 dst[di++] = 0;
662 si += 3;
663 continue;
664 } else // next start code
665 goto nsc;
666 }
667
668 dst[di++] = src[si++];
669 }
670 while (si < length)
671 dst[di++] = src[si++];
672
673 nsc:
674 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
675
676 *dst_length = di;
677 *consumed = si + 1; // +1 for the header
678 /* FIXME store exact number of bits in the getbitcontext
679 * (it is needed for decoding) */
680 return dst;
681 }
682
683 /**
684 * Identify the exact end of the bitstream
685 * @return the length of the trailing, or 0 if damaged
686 */
687 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
688 {
689 int v = *src;
690 int r;
691
692 tprintf(h->avctx, "rbsp trailing %X\n", v);
693
694 for (r = 1; r < 9; r++) {
695 if (v & 1)
696 return r;
697 v >>= 1;
698 }
699 return 0;
700 }
701
702 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
703 int height, int y_offset, int list)
704 {
705 int raw_my = h->mv_cache[list][scan8[n]][1];
706 int filter_height_up = (raw_my & 3) ? 2 : 0;
707 int filter_height_down = (raw_my & 3) ? 3 : 0;
708 int full_my = (raw_my >> 2) + y_offset;
709 int top = full_my - filter_height_up;
710 int bottom = full_my + filter_height_down + height;
711
712 return FFMAX(abs(top), bottom);
713 }
714
715 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
716 int height, int y_offset, int list0,
717 int list1, int *nrefs)
718 {
719 int my;
720
721 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
722
723 if (list0) {
724 int ref_n = h->ref_cache[0][scan8[n]];
725 Picture *ref = &h->ref_list[0][ref_n];
726
727 // Error resilience puts the current picture in the ref list.
728 // Don't try to wait on these as it will cause a deadlock.
729 // Fields can wait on each other, though.
730 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
731 (ref->reference & 3) != h->picture_structure) {
732 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
733 if (refs[0][ref_n] < 0)
734 nrefs[0] += 1;
735 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
736 }
737 }
738
739 if (list1) {
740 int ref_n = h->ref_cache[1][scan8[n]];
741 Picture *ref = &h->ref_list[1][ref_n];
742
743 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
744 (ref->reference & 3) != h->picture_structure) {
745 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
746 if (refs[1][ref_n] < 0)
747 nrefs[1] += 1;
748 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
749 }
750 }
751 }
752
753 /**
754 * Wait until all reference frames are available for MC operations.
755 *
756 * @param h the H264 context
757 */
758 static void await_references(H264Context *h)
759 {
760 const int mb_xy = h->mb_xy;
761 const int mb_type = h->cur_pic.mb_type[mb_xy];
762 int refs[2][48];
763 int nrefs[2] = { 0 };
764 int ref, list;
765
766 memset(refs, -1, sizeof(refs));
767
768 if (IS_16X16(mb_type)) {
769 get_lowest_part_y(h, refs, 0, 16, 0,
770 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
771 } else if (IS_16X8(mb_type)) {
772 get_lowest_part_y(h, refs, 0, 8, 0,
773 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
774 get_lowest_part_y(h, refs, 8, 8, 8,
775 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
776 } else if (IS_8X16(mb_type)) {
777 get_lowest_part_y(h, refs, 0, 16, 0,
778 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
779 get_lowest_part_y(h, refs, 4, 16, 0,
780 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
781 } else {
782 int i;
783
784 assert(IS_8X8(mb_type));
785
786 for (i = 0; i < 4; i++) {
787 const int sub_mb_type = h->sub_mb_type[i];
788 const int n = 4 * i;
789 int y_offset = (i & 2) << 2;
790
791 if (IS_SUB_8X8(sub_mb_type)) {
792 get_lowest_part_y(h, refs, n, 8, y_offset,
793 IS_DIR(sub_mb_type, 0, 0),
794 IS_DIR(sub_mb_type, 0, 1),
795 nrefs);
796 } else if (IS_SUB_8X4(sub_mb_type)) {
797 get_lowest_part_y(h, refs, n, 4, y_offset,
798 IS_DIR(sub_mb_type, 0, 0),
799 IS_DIR(sub_mb_type, 0, 1),
800 nrefs);
801 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
802 IS_DIR(sub_mb_type, 0, 0),
803 IS_DIR(sub_mb_type, 0, 1),
804 nrefs);
805 } else if (IS_SUB_4X8(sub_mb_type)) {
806 get_lowest_part_y(h, refs, n, 8, y_offset,
807 IS_DIR(sub_mb_type, 0, 0),
808 IS_DIR(sub_mb_type, 0, 1),
809 nrefs);
810 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
811 IS_DIR(sub_mb_type, 0, 0),
812 IS_DIR(sub_mb_type, 0, 1),
813 nrefs);
814 } else {
815 int j;
816 assert(IS_SUB_4X4(sub_mb_type));
817 for (j = 0; j < 4; j++) {
818 int sub_y_offset = y_offset + 2 * (j & 2);
819 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
820 IS_DIR(sub_mb_type, 0, 0),
821 IS_DIR(sub_mb_type, 0, 1),
822 nrefs);
823 }
824 }
825 }
826 }
827
828 for (list = h->list_count - 1; list >= 0; list--)
829 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
830 int row = refs[list][ref];
831 if (row >= 0) {
832 Picture *ref_pic = &h->ref_list[list][ref];
833 int ref_field = ref_pic->reference - 1;
834 int ref_field_picture = ref_pic->field_picture;
835 int pic_height = 16 * h->mb_height >> ref_field_picture;
836
837 row <<= MB_MBAFF(h);
838 nrefs[list]--;
839
840 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
841 ff_thread_await_progress(&ref_pic->tf,
842 FFMIN((row >> 1) - !(row & 1),
843 pic_height - 1),
844 1);
845 ff_thread_await_progress(&ref_pic->tf,
846 FFMIN((row >> 1), pic_height - 1),
847 0);
848 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
849 ff_thread_await_progress(&ref_pic->tf,
850 FFMIN(row * 2 + ref_field,
851 pic_height - 1),
852 0);
853 } else if (FIELD_PICTURE(h)) {
854 ff_thread_await_progress(&ref_pic->tf,
855 FFMIN(row, pic_height - 1),
856 ref_field);
857 } else {
858 ff_thread_await_progress(&ref_pic->tf,
859 FFMIN(row, pic_height - 1),
860 0);
861 }
862 }
863 }
864 }
865
866 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
867 int n, int square, int height,
868 int delta, int list,
869 uint8_t *dest_y, uint8_t *dest_cb,
870 uint8_t *dest_cr,
871 int src_x_offset, int src_y_offset,
872 qpel_mc_func *qpix_op,
873 h264_chroma_mc_func chroma_op,
874 int pixel_shift, int chroma_idc)
875 {
876 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
877 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
878 const int luma_xy = (mx & 3) + ((my & 3) << 2);
879 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
880 uint8_t *src_y = pic->f.data[0] + offset;
881 uint8_t *src_cb, *src_cr;
882 int extra_width = 0;
883 int extra_height = 0;
884 int emu = 0;
885 const int full_mx = mx >> 2;
886 const int full_my = my >> 2;
887 const int pic_width = 16 * h->mb_width;
888 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
889 int ysh;
890
891 if (mx & 7)
892 extra_width -= 3;
893 if (my & 7)
894 extra_height -= 3;
895
896 if (full_mx < 0 - extra_width ||
897 full_my < 0 - extra_height ||
898 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
899 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
900 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
901 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
902 h->mb_linesize, h->mb_linesize,
903 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
904 full_my - 2, pic_width, pic_height);
905 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
906 emu = 1;
907 }
908
909 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
910 if (!square)
911 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
912
913 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
914 return;
915
916 if (chroma_idc == 3 /* yuv444 */) {
917 src_cb = pic->f.data[1] + offset;
918 if (emu) {
919 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
920 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
921 h->mb_linesize, h->mb_linesize,
922 16 + 5, 16 + 5 /*FIXME*/,
923 full_mx - 2, full_my - 2,
924 pic_width, pic_height);
925 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
926 }
927 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
928 if (!square)
929 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
930
931 src_cr = pic->f.data[2] + offset;
932 if (emu) {
933 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
934 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
935 h->mb_linesize, h->mb_linesize,
936 16 + 5, 16 + 5 /*FIXME*/,
937 full_mx - 2, full_my - 2,
938 pic_width, pic_height);
939 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
940 }
941 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
942 if (!square)
943 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
944 return;
945 }
946
947 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
948 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
949 // chroma offset when predicting from a field of opposite parity
950 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
951 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
952 }
953
954 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
955 (my >> ysh) * h->mb_uvlinesize;
956 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
957 (my >> ysh) * h->mb_uvlinesize;
958
959 if (emu) {
960 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
961 h->mb_uvlinesize, h->mb_uvlinesize,
962 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
963 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
964 src_cb = h->edge_emu_buffer;
965 }
966 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
967 height >> (chroma_idc == 1 /* yuv420 */),
968 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
969
970 if (emu) {
971 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
972 h->mb_uvlinesize, h->mb_uvlinesize,
973 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
974 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
975 src_cr = h->edge_emu_buffer;
976 }
977 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
978 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
979 }
980
981 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
982 int height, int delta,
983 uint8_t *dest_y, uint8_t *dest_cb,
984 uint8_t *dest_cr,
985 int x_offset, int y_offset,
986 qpel_mc_func *qpix_put,
987 h264_chroma_mc_func chroma_put,
988 qpel_mc_func *qpix_avg,
989 h264_chroma_mc_func chroma_avg,
990 int list0, int list1,
991 int pixel_shift, int chroma_idc)
992 {
993 qpel_mc_func *qpix_op = qpix_put;
994 h264_chroma_mc_func chroma_op = chroma_put;
995
996 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
997 if (chroma_idc == 3 /* yuv444 */) {
998 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
999 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1000 } else if (chroma_idc == 2 /* yuv422 */) {
1001 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1002 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1003 } else { /* yuv420 */
1004 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1005 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1006 }
1007 x_offset += 8 * h->mb_x;
1008 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1009
1010 if (list0) {
1011 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1012 mc_dir_part(h, ref, n, square, height, delta, 0,
1013 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1014 qpix_op, chroma_op, pixel_shift, chroma_idc);
1015
1016 qpix_op = qpix_avg;
1017 chroma_op = chroma_avg;
1018 }
1019
1020 if (list1) {
1021 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1022 mc_dir_part(h, ref, n, square, height, delta, 1,
1023 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1024 qpix_op, chroma_op, pixel_shift, chroma_idc);
1025 }
1026 }
1027
1028 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1029 int height, int delta,
1030 uint8_t *dest_y, uint8_t *dest_cb,
1031 uint8_t *dest_cr,
1032 int x_offset, int y_offset,
1033 qpel_mc_func *qpix_put,
1034 h264_chroma_mc_func chroma_put,
1035 h264_weight_func luma_weight_op,
1036 h264_weight_func chroma_weight_op,
1037 h264_biweight_func luma_weight_avg,
1038 h264_biweight_func chroma_weight_avg,
1039 int list0, int list1,
1040 int pixel_shift, int chroma_idc)
1041 {
1042 int chroma_height;
1043
1044 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1045 if (chroma_idc == 3 /* yuv444 */) {
1046 chroma_height = height;
1047 chroma_weight_avg = luma_weight_avg;
1048 chroma_weight_op = luma_weight_op;
1049 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1050 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1051 } else if (chroma_idc == 2 /* yuv422 */) {
1052 chroma_height = height;
1053 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1054 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1055 } else { /* yuv420 */
1056 chroma_height = height >> 1;
1057 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1058 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1059 }
1060 x_offset += 8 * h->mb_x;
1061 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1062
1063 if (list0 && list1) {
1064 /* don't optimize for luma-only case, since B-frames usually
1065 * use implicit weights => chroma too. */
1066 uint8_t *tmp_cb = h->bipred_scratchpad;
1067 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1068 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1069 int refn0 = h->ref_cache[0][scan8[n]];
1070 int refn1 = h->ref_cache[1][scan8[n]];
1071
1072 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1073 dest_y, dest_cb, dest_cr,
1074 x_offset, y_offset, qpix_put, chroma_put,
1075 pixel_shift, chroma_idc);
1076 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1077 tmp_y, tmp_cb, tmp_cr,
1078 x_offset, y_offset, qpix_put, chroma_put,
1079 pixel_shift, chroma_idc);
1080
1081 if (h->use_weight == 2) {
1082 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1083 int weight1 = 64 - weight0;
1084 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1085 height, 5, weight0, weight1, 0);
1086 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1087 chroma_height, 5, weight0, weight1, 0);
1088 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1089 chroma_height, 5, weight0, weight1, 0);
1090 } else {
1091 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1092 h->luma_log2_weight_denom,
1093 h->luma_weight[refn0][0][0],
1094 h->luma_weight[refn1][1][0],
1095 h->luma_weight[refn0][0][1] +
1096 h->luma_weight[refn1][1][1]);
1097 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1098 h->chroma_log2_weight_denom,
1099 h->chroma_weight[refn0][0][0][0],
1100 h->chroma_weight[refn1][1][0][0],
1101 h->chroma_weight[refn0][0][0][1] +
1102 h->chroma_weight[refn1][1][0][1]);
1103 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1104 h->chroma_log2_weight_denom,
1105 h->chroma_weight[refn0][0][1][0],
1106 h->chroma_weight[refn1][1][1][0],
1107 h->chroma_weight[refn0][0][1][1] +
1108 h->chroma_weight[refn1][1][1][1]);
1109 }
1110 } else {
1111 int list = list1 ? 1 : 0;
1112 int refn = h->ref_cache[list][scan8[n]];
1113 Picture *ref = &h->ref_list[list][refn];
1114 mc_dir_part(h, ref, n, square, height, delta, list,
1115 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1116 qpix_put, chroma_put, pixel_shift, chroma_idc);
1117
1118 luma_weight_op(dest_y, h->mb_linesize, height,
1119 h->luma_log2_weight_denom,
1120 h->luma_weight[refn][list][0],
1121 h->luma_weight[refn][list][1]);
1122 if (h->use_weight_chroma) {
1123 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1124 h->chroma_log2_weight_denom,
1125 h->chroma_weight[refn][list][0][0],
1126 h->chroma_weight[refn][list][0][1]);
1127 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1128 h->chroma_log2_weight_denom,
1129 h->chroma_weight[refn][list][1][0],
1130 h->chroma_weight[refn][list][1][1]);
1131 }
1132 }
1133 }
1134
1135 static av_always_inline void prefetch_motion(H264Context *h, int list,
1136 int pixel_shift, int chroma_idc)
1137 {
1138 /* fetch pixels for estimated mv 4 macroblocks ahead
1139 * optimized for 64byte cache lines */
1140 const int refn = h->ref_cache[list][scan8[0]];
1141 if (refn >= 0) {
1142 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1143 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1144 uint8_t **src = h->ref_list[list][refn].f.data;
1145 int off = (mx << pixel_shift) +
1146 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1147 (64 << pixel_shift);
1148 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1149 if (chroma_idc == 3 /* yuv444 */) {
1150 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1151 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1152 } else {
1153 off = ((mx >> 1) << pixel_shift) +
1154 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
1155 (64 << pixel_shift);
1156 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1157 }
1158 }
1159 }
1160
1161 static void free_tables(H264Context *h, int free_rbsp)
1162 {
1163 int i;
1164 H264Context *hx;
1165
1166 av_freep(&h->intra4x4_pred_mode);
1167 av_freep(&h->chroma_pred_mode_table);
1168 av_freep(&h->cbp_table);
1169 av_freep(&h->mvd_table[0]);
1170 av_freep(&h->mvd_table[1]);
1171 av_freep(&h->direct_table);
1172 av_freep(&h->non_zero_count);
1173 av_freep(&h->slice_table_base);
1174 h->slice_table = NULL;
1175 av_freep(&h->list_counts);
1176
1177 av_freep(&h->mb2b_xy);
1178 av_freep(&h->mb2br_xy);
1179
1180 av_buffer_pool_uninit(&h->qscale_table_pool);
1181 av_buffer_pool_uninit(&h->mb_type_pool);
1182 av_buffer_pool_uninit(&h->motion_val_pool);
1183 av_buffer_pool_uninit(&h->ref_index_pool);
1184
1185 if (free_rbsp && h->DPB) {
1186 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1187 unref_picture(h, &h->DPB[i]);
1188 av_freep(&h->DPB);
1189 } else if (h->DPB) {
1190 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1191 h->DPB[i].needs_realloc = 1;
1192 }
1193
1194 h->cur_pic_ptr = NULL;
1195
1196 for (i = 0; i < MAX_THREADS; i++) {
1197 hx = h->thread_context[i];
1198 if (!hx)
1199 continue;
1200 av_freep(&hx->top_borders[1]);
1201 av_freep(&hx->top_borders[0]);
1202 av_freep(&hx->bipred_scratchpad);
1203 av_freep(&hx->edge_emu_buffer);
1204 av_freep(&hx->dc_val_base);
1205 av_freep(&hx->me.scratchpad);
1206 av_freep(&hx->er.mb_index2xy);
1207 av_freep(&hx->er.error_status_table);
1208 av_freep(&hx->er.er_temp_buffer);
1209 av_freep(&hx->er.mbintra_table);
1210 av_freep(&hx->er.mbskip_table);
1211
1212 if (free_rbsp) {
1213 av_freep(&hx->rbsp_buffer[1]);
1214 av_freep(&hx->rbsp_buffer[0]);
1215 hx->rbsp_buffer_size[0] = 0;
1216 hx->rbsp_buffer_size[1] = 0;
1217 }
1218 if (i)
1219 av_freep(&h->thread_context[i]);
1220 }
1221 }
1222
1223 static void init_dequant8_coeff_table(H264Context *h)
1224 {
1225 int i, j, q, x;
1226 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1227
1228 for (i = 0; i < 6; i++) {
1229 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1230 for (j = 0; j < i; j++)
1231 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1232 64 * sizeof(uint8_t))) {
1233 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1234 break;
1235 }
1236 if (j < i)
1237 continue;
1238
1239 for (q = 0; q < max_qp + 1; q++) {
1240 int shift = div6[q];
1241 int idx = rem6[q];
1242 for (x = 0; x < 64; x++)
1243 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1244 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1245 h->pps.scaling_matrix8[i][x]) << shift;
1246 }
1247 }
1248 }
1249
1250 static void init_dequant4_coeff_table(H264Context *h)
1251 {
1252 int i, j, q, x;
1253 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1254 for (i = 0; i < 6; i++) {
1255 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1256 for (j = 0; j < i; j++)
1257 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1258 16 * sizeof(uint8_t))) {
1259 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1260 break;
1261 }
1262 if (j < i)
1263 continue;
1264
1265 for (q = 0; q < max_qp + 1; q++) {
1266 int shift = div6[q] + 2;
1267 int idx = rem6[q];
1268 for (x = 0; x < 16; x++)
1269 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1270 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1271 h->pps.scaling_matrix4[i][x]) << shift;
1272 }
1273 }
1274 }
1275
1276 static void init_dequant_tables(H264Context *h)
1277 {
1278 int i, x;
1279 init_dequant4_coeff_table(h);
1280 if (h->pps.transform_8x8_mode)
1281 init_dequant8_coeff_table(h);
1282 if (h->sps.transform_bypass) {
1283 for (i = 0; i < 6; i++)
1284 for (x = 0; x < 16; x++)
1285 h->dequant4_coeff[i][0][x] = 1 << 6;
1286 if (h->pps.transform_8x8_mode)
1287 for (i = 0; i < 6; i++)
1288 for (x = 0; x < 64; x++)
1289 h->dequant8_coeff[i][0][x] = 1 << 6;
1290 }
1291 }
1292
1293 int ff_h264_alloc_tables(H264Context *h)
1294 {
1295 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1296 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
1297 int x, y, i;
1298
1299 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1300 row_mb_num * 8 * sizeof(uint8_t), fail)
1301 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1302 big_mb_num * 48 * sizeof(uint8_t), fail)
1303 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1304 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1305 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1306 big_mb_num * sizeof(uint16_t), fail)
1307 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1308 big_mb_num * sizeof(uint8_t), fail)
1309 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1310 16 * row_mb_num * sizeof(uint8_t), fail);
1311 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1312 16 * row_mb_num * sizeof(uint8_t), fail);
1313 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1314 4 * big_mb_num * sizeof(uint8_t), fail);
1315 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1316 big_mb_num * sizeof(uint8_t), fail)
1317
1318 memset(h->slice_table_base, -1,
1319 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1320 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1321
1322 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1323 big_mb_num * sizeof(uint32_t), fail);
1324 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1325 big_mb_num * sizeof(uint32_t), fail);
1326 for (y = 0; y < h->mb_height; y++)
1327 for (x = 0; x < h->mb_width; x++) {
1328 const int mb_xy = x + y * h->mb_stride;
1329 const int b_xy = 4 * x + 4 * y * h->b_stride;
1330
1331 h->mb2b_xy[mb_xy] = b_xy;
1332 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1333 }
1334
1335 if (!h->dequant4_coeff[0])
1336 init_dequant_tables(h);
1337
1338 if (!h->DPB) {
1339 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1340 if (!h->DPB)
1341 return AVERROR(ENOMEM);
1342 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1343 avcodec_get_frame_defaults(&h->DPB[i].f);
1344 avcodec_get_frame_defaults(&h->cur_pic.f);
1345 }
1346
1347 return 0;
1348
1349 fail:
1350 free_tables(h, 1);
1351 return AVERROR(ENOMEM);
1352 }
1353
1354 /**
1355 * Mimic alloc_tables(), but for every context thread.
1356 */
1357 static void clone_tables(H264Context *dst, H264Context *src, int i)
1358 {
1359 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1360 dst->non_zero_count = src->non_zero_count;
1361 dst->slice_table = src->slice_table;
1362 dst->cbp_table = src->cbp_table;
1363 dst->mb2b_xy = src->mb2b_xy;
1364 dst->mb2br_xy = src->mb2br_xy;
1365 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1366 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1367 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1368 dst->direct_table = src->direct_table;
1369 dst->list_counts = src->list_counts;
1370 dst->DPB = src->DPB;
1371 dst->cur_pic_ptr = src->cur_pic_ptr;
1372 dst->cur_pic = src->cur_pic;
1373 dst->bipred_scratchpad = NULL;
1374 dst->edge_emu_buffer = NULL;
1375 dst->me.scratchpad = NULL;
1376 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1377 src->sps.chroma_format_idc);
1378 }
1379
1380 /**
1381 * Init context
1382 * Allocate buffers which are not shared amongst multiple threads.
1383 */
1384 static int context_init(H264Context *h)
1385 {
1386 ERContext *er = &h->er;
1387 int mb_array_size = h->mb_height * h->mb_stride;
1388 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1389 int c_size = h->mb_stride * (h->mb_height + 1);
1390 int yc_size = y_size + 2 * c_size;
1391 int x, y, i;
1392
1393 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1394 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1395 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1396 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1397
1398 h->ref_cache[0][scan8[5] + 1] =
1399 h->ref_cache[0][scan8[7] + 1] =
1400 h->ref_cache[0][scan8[13] + 1] =
1401 h->ref_cache[1][scan8[5] + 1] =
1402 h->ref_cache[1][scan8[7] + 1] =
1403 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1404
1405 if (CONFIG_ERROR_RESILIENCE) {
1406 /* init ER */
1407 er->avctx = h->avctx;
1408 er->dsp = &h->dsp;
1409 er->decode_mb = h264_er_decode_mb;
1410 er->opaque = h;
1411 er->quarter_sample = 1;
1412
1413 er->mb_num = h->mb_num;
1414 er->mb_width = h->mb_width;
1415 er->mb_height = h->mb_height;
1416 er->mb_stride = h->mb_stride;
1417 er->b8_stride = h->mb_width * 2 + 1;
1418
1419 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1420 fail); // error ressilience code looks cleaner with this
1421 for (y = 0; y < h->mb_height; y++)
1422 for (x = 0; x < h->mb_width; x++)
1423 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1424
1425 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1426 h->mb_stride + h->mb_width;
1427
1428 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1429 mb_array_size * sizeof(uint8_t), fail);
1430
1431 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1432 memset(er->mbintra_table, 1, mb_array_size);
1433
1434 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1435
1436 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1437 fail);
1438
1439 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1440 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1441 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1442 er->dc_val[2] = er->dc_val[1] + c_size;
1443 for (i = 0; i < yc_size; i++)
1444 h->dc_val_base[i] = 1024;
1445 }
1446
1447 return 0;
1448
1449 fail:
1450 return AVERROR(ENOMEM); // free_tables will clean up for us
1451 }
1452
1453 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1454 int parse_extradata);
1455
1456 int ff_h264_decode_extradata(H264Context *h)
1457 {
1458 AVCodecContext *avctx = h->avctx;
1459 int ret;
1460
1461 if (avctx->extradata[0] == 1) {
1462 int i, cnt, nalsize;
1463 unsigned char *p = avctx->extradata;
1464
1465 h->is_avc = 1;
1466
1467 if (avctx->extradata_size < 7) {
1468 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1469 return AVERROR_INVALIDDATA;
1470 }
1471 /* sps and pps in the avcC always have length coded with 2 bytes,
1472 * so put a fake nal_length_size = 2 while parsing them */
1473 h->nal_length_size = 2;
1474 // Decode sps from avcC
1475 cnt = *(p + 5) & 0x1f; // Number of sps
1476 p += 6;
1477 for (i = 0; i < cnt; i++) {
1478 nalsize = AV_RB16(p) + 2;
1479 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1480 return AVERROR_INVALIDDATA;
1481 ret = decode_nal_units(h, p, nalsize, 1);
1482 if (ret < 0) {
1483 av_log(avctx, AV_LOG_ERROR,
1484 "Decoding sps %d from avcC failed\n", i);
1485 return ret;
1486 }
1487 p += nalsize;
1488 }
1489 // Decode pps from avcC
1490 cnt = *(p++); // Number of pps
1491 for (i = 0; i < cnt; i++) {
1492 nalsize = AV_RB16(p) + 2;
1493 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1494 return AVERROR_INVALIDDATA;
1495 ret = decode_nal_units(h, p, nalsize, 1);
1496 if (ret < 0) {
1497 av_log(avctx, AV_LOG_ERROR,
1498 "Decoding pps %d from avcC failed\n", i);
1499 return ret;
1500 }
1501 p += nalsize;
1502 }
1503 // Now store right nal length size, that will be used to parse all other nals
1504 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1505 } else {
1506 h->is_avc = 0;
1507 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
1508 if (ret < 0)
1509 return ret;
1510 }
1511 return 0;
1512 }
1513
1514 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1515 {
1516 H264Context *h = avctx->priv_data;
1517 int i;
1518 int ret;
1519
1520 h->avctx = avctx;
1521
1522 h->bit_depth_luma = 8;
1523 h->chroma_format_idc = 1;
1524
1525 ff_h264dsp_init(&h->h264dsp, 8, 1);
1526 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1527 ff_h264qpel_init(&h->h264qpel, 8);
1528 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1529
1530 h->dequant_coeff_pps = -1;
1531
1532 /* needed so that IDCT permutation is known early */
1533 if (CONFIG_ERROR_RESILIENCE)
1534 ff_dsputil_init(&h->dsp, h->avctx);
1535 ff_videodsp_init(&h->vdsp, 8);
1536
1537 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1538 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1539
1540 h->picture_structure = PICT_FRAME;
1541 h->slice_context_count = 1;
1542 h->workaround_bugs = avctx->workaround_bugs;
1543 h->flags = avctx->flags;
1544
1545 /* set defaults */
1546 // s->decode_mb = ff_h263_decode_mb;
1547 if (!avctx->has_b_frames)
1548 h->low_delay = 1;
1549
1550 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1551
1552 ff_h264_decode_init_vlc();
1553
1554 ff_init_cabac_states();
1555
1556 h->pixel_shift = 0;
1557 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1558
1559 h->thread_context[0] = h;
1560 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1561 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1562 h->last_pocs[i] = INT_MIN;
1563 h->prev_poc_msb = 1 << 16;
1564 h->x264_build = -1;
1565 ff_h264_reset_sei(h);
1566 h->recovery_frame = -1;
1567 h->frame_recovered = 0;
1568 if (avctx->codec_id == AV_CODEC_ID_H264) {
1569 if (avctx->ticks_per_frame == 1)
1570 h->avctx->time_base.den *= 2;
1571 avctx->ticks_per_frame = 2;
1572 }
1573
1574 if (avctx->extradata_size > 0 && avctx->extradata) {
1575 ret = ff_h264_decode_extradata(h);
1576 if (ret < 0)
1577 return ret;
1578 }
1579
1580 if (h->sps.bitstream_restriction_flag &&
1581 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1582 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1583 h->low_delay = 0;
1584 }
1585
1586 avctx->internal->allocate_progress = 1;
1587
1588 return 0;
1589 }
1590
1591 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1592 #undef REBASE_PICTURE
1593 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1594 ((pic && pic >= old_ctx->DPB && \
1595 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1596 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1597
1598 static void copy_picture_range(Picture **to, Picture **from, int count,
1599 H264Context *new_base,
1600 H264Context *old_base)
1601 {
1602 int i;
1603
1604 for (i = 0; i < count; i++) {
1605 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1606 IN_RANGE(from[i], old_base->DPB,
1607 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1608 !from[i]));
1609 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1610 }
1611 }
1612
1613 static int copy_parameter_set(void **to, void **from, int count, int size)
1614 {
1615 int i;
1616
1617 for (i = 0; i < count; i++) {
1618 if (to[i] && !from[i]) {
1619 av_freep(&to[i]);
1620 } else if (from[i] && !to[i]) {
1621 to[i] = av_malloc(size);
1622 if (!to[i])
1623 return AVERROR(ENOMEM);
1624 }
1625
1626 if (from[i])
1627 memcpy(to[i], from[i], size);
1628 }
1629
1630 return 0;
1631 }
1632
1633 static int decode_init_thread_copy(AVCodecContext *avctx)
1634 {
1635 H264Context *h = avctx->priv_data;
1636
1637 if (!avctx->internal->is_copy)
1638 return 0;
1639 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1640 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1641
1642 h->context_initialized = 0;
1643
1644 return 0;
1645 }
1646
1647 #define copy_fields(to, from, start_field, end_field) \
1648 memcpy(&to->start_field, &from->start_field, \
1649 (char *)&to->end_field - (char *)&to->start_field)
1650
1651 static int h264_slice_header_init(H264Context *, int);
1652
1653 static int h264_set_parameter_from_sps(H264Context *h);
1654
1655 static int decode_update_thread_context(AVCodecContext *dst,
1656 const AVCodecContext *src)
1657 {
1658 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1659 int inited = h->context_initialized, err = 0;
1660 int context_reinitialized = 0;
1661 int i, ret;
1662
1663 if (dst == src || !h1->context_initialized)
1664 return 0;
1665
1666 if (inited &&
1667 (h->width != h1->width ||
1668 h->height != h1->height ||
1669 h->mb_width != h1->mb_width ||
1670 h->mb_height != h1->mb_height ||
1671 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1672 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1673 h->sps.colorspace != h1->sps.colorspace)) {
1674
1675 /* set bits_per_raw_sample to the previous value. the check for changed
1676 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1677 * the current value */
1678 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1679
1680 av_freep(&h->bipred_scratchpad);
1681
1682 h->width = h1->width;
1683 h->height = h1->height;
1684 h->mb_height = h1->mb_height;
1685 h->mb_width = h1->mb_width;
1686 h->mb_num = h1->mb_num;
1687 h->mb_stride = h1->mb_stride;
1688 h->b_stride = h1->b_stride;
1689
1690 if ((err = h264_slice_header_init(h, 1)) < 0) {
1691 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1692 return err;
1693 }
1694 context_reinitialized = 1;
1695
1696 /* update linesize on resize. The decoder doesn't
1697 * necessarily call h264_frame_start in the new thread */
1698 h->linesize = h1->linesize;
1699 h->uvlinesize = h1->uvlinesize;
1700
1701 /* copy block_offset since frame_start may not be called */
1702 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1703 }
1704
1705 if (!inited) {
1706 for (i = 0; i < MAX_SPS_COUNT; i++)
1707 av_freep(h->sps_buffers + i);
1708
1709 for (i = 0; i < MAX_PPS_COUNT; i++)
1710 av_freep(h->pps_buffers + i);
1711
1712 memcpy(h, h1, sizeof(*h1));
1713 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1714 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1715 memset(&h->er, 0, sizeof(h->er));
1716 memset(&h->me, 0, sizeof(h->me));
1717 memset(&h->mb, 0, sizeof(h->mb));
1718 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1719 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1720 h->context_initialized = 0;
1721
1722 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1723 avcodec_get_frame_defaults(&h->cur_pic.f);
1724 h->cur_pic.tf.f = &h->cur_pic.f;
1725
1726 h->avctx = dst;
1727 h->DPB = NULL;
1728 h->qscale_table_pool = NULL;
1729 h->mb_type_pool = NULL;
1730 h->ref_index_pool = NULL;
1731 h->motion_val_pool = NULL;
1732
1733 ret = ff_h264_alloc_tables(h);
1734 if (ret < 0) {
1735 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1736 return ret;
1737 }
1738 ret = context_init(h);
1739 if (ret < 0) {
1740 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1741 return ret;
1742 }
1743
1744 for (i = 0; i < 2; i++) {
1745 h->rbsp_buffer[i] = NULL;
1746 h->rbsp_buffer_size[i] = 0;
1747 }
1748 h->bipred_scratchpad = NULL;
1749 h->edge_emu_buffer = NULL;
1750
1751 h->thread_context[0] = h;
1752
1753 h->context_initialized = 1;
1754 }
1755
1756 h->avctx->coded_height = h1->avctx->coded_height;
1757 h->avctx->coded_width = h1->avctx->coded_width;
1758 h->avctx->width = h1->avctx->width;
1759 h->avctx->height = h1->avctx->height;
1760 h->coded_picture_number = h1->coded_picture_number;
1761 h->first_field = h1->first_field;
1762 h->picture_structure = h1->picture_structure;
1763 h->qscale = h1->qscale;
1764 h->droppable = h1->droppable;
1765 h->data_partitioning = h1->data_partitioning;
1766 h->low_delay = h1->low_delay;
1767
1768 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1769 unref_picture(h, &h->DPB[i]);
1770 if (h1->DPB[i].f.buf[0] &&
1771 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1772 return ret;
1773 }
1774
1775 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1776 unref_picture(h, &h->cur_pic);
1777 if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1778 return ret;
1779
1780 h->workaround_bugs = h1->workaround_bugs;
1781 h->low_delay = h1->low_delay;
1782 h->droppable = h1->droppable;
1783
1784 /* frame_start may not be called for the next thread (if it's decoding
1785 * a bottom field) so this has to be allocated here */
1786 err = alloc_scratch_buffers(h, h1->linesize);
1787 if (err < 0)
1788 return err;
1789
1790 // extradata/NAL handling
1791 h->is_avc = h1->is_avc;
1792
1793 // SPS/PPS
1794 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1795 (void **)h1->sps_buffers,
1796 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1797 return ret;
1798 h->sps = h1->sps;
1799 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1800 (void **)h1->pps_buffers,
1801 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1802 return ret;
1803 h->pps = h1->pps;
1804
1805 // Dequantization matrices
1806 // FIXME these are big - can they be only copied when PPS changes?
1807 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1808
1809 for (i = 0; i < 6; i++)
1810 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1811 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1812
1813 for (i = 0; i < 6; i++)
1814 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1815 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1816
1817 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1818
1819 // POC timing
1820 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1821
1822 // reference lists
1823 copy_fields(h, h1, short_ref, cabac_init_idc);
1824
1825 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1826 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1827 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1828 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1829
1830 h->last_slice_type = h1->last_slice_type;
1831
1832 if (context_reinitialized)
1833 h264_set_parameter_from_sps(h);
1834
1835 if (!h->cur_pic_ptr)
1836 return 0;
1837
1838 if (!h->droppable) {
1839 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1840 h->prev_poc_msb = h->poc_msb;
1841 h->prev_poc_lsb = h->poc_lsb;
1842 }
1843 h->prev_frame_num_offset = h->frame_num_offset;
1844 h->prev_frame_num = h->frame_num;
1845 h->outputed_poc = h->next_outputed_poc;
1846
1847 h->recovery_frame = h1->recovery_frame;
1848 h->frame_recovered = h1->frame_recovered;
1849
1850 return err;
1851 }
1852
1853 static int h264_frame_start(H264Context *h)
1854 {
1855 Picture *pic;
1856 int i, ret;
1857 const int pixel_shift = h->pixel_shift;
1858
1859 release_unused_pictures(h, 1);
1860 h->cur_pic_ptr = NULL;
1861
1862 i = find_unused_picture(h);
1863 if (i < 0) {
1864 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1865 return i;
1866 }
1867 pic = &h->DPB[i];
1868
1869 pic->reference = h->droppable ? 0 : h->picture_structure;
1870 pic->f.coded_picture_number = h->coded_picture_number++;
1871 pic->field_picture = h->picture_structure != PICT_FRAME;
1872 /*
1873 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1874 * in later.
1875 * See decode_nal_units().
1876 */
1877 pic->f.key_frame = 0;
1878 pic->mmco_reset = 0;
1879 pic->recovered = 0;
1880
1881 if ((ret = alloc_picture(h, pic)) < 0)
1882 return ret;
1883
1884 h->cur_pic_ptr = pic;
1885 unref_picture(h, &h->cur_pic);
1886 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1887 return ret;
1888
1889 if (CONFIG_ERROR_RESILIENCE)
1890 ff_er_frame_start(&h->er);
1891
1892 assert(h->linesize && h->uvlinesize);
1893
1894 for (i = 0; i < 16; i++) {
1895 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1896 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1897 }
1898 for (i = 0; i < 16; i++) {
1899 h->block_offset[16 + i] =
1900 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1901 h->block_offset[48 + 16 + i] =
1902 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1903 }
1904
1905 /* can't be in alloc_tables because linesize isn't known there.
1906 * FIXME: redo bipred weight to not require extra buffer? */
1907 for (i = 0; i < h->slice_context_count; i++)
1908 if (h->thread_context[i]) {
1909 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1910 if (ret < 0)
1911 return ret;
1912 }
1913
1914 /* Some macroblocks can be accessed before they're available in case
1915 * of lost slices, MBAFF or threading. */
1916 memset(h->slice_table, -1,
1917 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1918
1919 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1920 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1921
1922 /* We mark the current picture as non-reference after allocating it, so
1923 * that if we break out due to an error it can be released automatically
1924 * in the next ff_MPV_frame_start().
1925 */
1926 h->cur_pic_ptr->reference = 0;
1927
1928 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1929
1930 h->next_output_pic = NULL;
1931
1932 assert(h->cur_pic_ptr->long_ref == 0);
1933
1934 return 0;
1935 }
1936
1937 /**
1938 * Run setup operations that must be run after slice header decoding.
1939 * This includes finding the next displayed frame.
1940 *
1941 * @param h h264 master context
1942 * @param setup_finished enough NALs have been read that we can call
1943 * ff_thread_finish_setup()
1944 */
1945 static void decode_postinit(H264Context *h, int setup_finished)
1946 {
1947 Picture *out = h->cur_pic_ptr;
1948 Picture *cur = h->cur_pic_ptr;
1949 int i, pics, out_of_order, out_idx;
1950 int invalid = 0, cnt = 0;
1951
1952 h->cur_pic_ptr->f.pict_type = h->pict_type;
1953
1954 if (h->next_output_pic)
1955 return;
1956
1957 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1958 /* FIXME: if we have two PAFF fields in one packet, we can't start
1959 * the next thread here. If we have one field per packet, we can.
1960 * The check in decode_nal_units() is not good enough to find this
1961 * yet, so we assume the worst for now. */
1962 // if (setup_finished)
1963 // ff_thread_finish_setup(h->avctx);
1964 return;
1965 }
1966
1967 cur->f.interlaced_frame = 0;
1968 cur->f.repeat_pict = 0;
1969
1970 /* Signal interlacing information externally. */
1971 /* Prioritize picture timing SEI information over used
1972 * decoding process if it exists. */
1973
1974 if (h->sps.pic_struct_present_flag) {
1975 switch (h->sei_pic_struct) {
1976 case SEI_PIC_STRUCT_FRAME:
1977 break;
1978 case SEI_PIC_STRUCT_TOP_FIELD:
1979 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1980 cur->f.interlaced_frame = 1;
1981 break;
1982 case SEI_PIC_STRUCT_TOP_BOTTOM:
1983 case SEI_PIC_STRUCT_BOTTOM_TOP:
1984 if (FIELD_OR_MBAFF_PICTURE(h))
1985 cur->f.interlaced_frame = 1;
1986 else
1987 // try to flag soft telecine progressive
1988 cur->f.interlaced_frame = h->prev_interlaced_frame;
1989 break;
1990 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1991 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1992 /* Signal the possibility of telecined film externally
1993 * (pic_struct 5,6). From these hints, let the applications
1994 * decide if they apply deinterlacing. */
1995 cur->f.repeat_pict = 1;
1996 break;
1997 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1998 cur->f.repeat_pict = 2;
1999 break;
2000 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2001 cur->f.repeat_pict = 4;
2002 break;
2003 }
2004
2005 if ((h->sei_ct_type & 3) &&
2006 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2007 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2008 } else {
2009 /* Derive interlacing flag from used decoding process. */
2010 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2011 }
2012 h->prev_interlaced_frame = cur->f.interlaced_frame;
2013
2014 if (cur->field_poc[0] != cur->field_poc[1]) {
2015 /* Derive top_field_first from field pocs. */
2016 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2017 } else {
2018 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2019 /* Use picture timing SEI information. Even if it is a
2020 * information of a past frame, better than nothing. */
2021 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2022 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2023 cur->f.top_field_first = 1;
2024 else
2025 cur->f.top_field_first = 0;
2026 } else {
2027 /* Most likely progressive */
2028 cur->f.top_field_first = 0;
2029 }
2030 }
2031
2032 // FIXME do something with unavailable reference frames
2033
2034 /* Sort B-frames into display order */
2035
2036 if (h->sps.bitstream_restriction_flag &&
2037 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2038 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2039 h->low_delay = 0;
2040 }
2041
2042 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2043 !h->sps.bitstream_restriction_flag) {
2044 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2045 h->low_delay = 0;
2046 }
2047
2048 pics = 0;
2049 while (h->delayed_pic[pics])
2050 pics++;
2051
2052 assert(pics <= MAX_DELAYED_PIC_COUNT);
2053
2054 h->delayed_pic[pics++] = cur;
2055 if (cur->reference == 0)
2056 cur->reference = DELAYED_PIC_REF;
2057
2058 /* Frame reordering. This code takes pictures from coding order and sorts
2059 * them by their incremental POC value into display order. It supports POC
2060 * gaps, MMCO reset codes and random resets.
2061 * A "display group" can start either with a IDR frame (f.key_frame = 1),
2062 * and/or can be closed down with a MMCO reset code. In sequences where
2063 * there is no delay, we can't detect that (since the frame was already
2064 * output to the user), so we also set h->mmco_reset to detect the MMCO
2065 * reset code.
2066 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
2067 * we increase the delay between input and output. All frames affected by
2068 * the lag (e.g. those that should have been output before another frame
2069 * that we already returned to the user) will be dropped. This is a bug
2070 * that we will fix later. */
2071 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2072 cnt += out->poc < h->last_pocs[i];
2073 invalid += out->poc == INT_MIN;
2074 }
2075 if (!h->mmco_reset && !cur->f.key_frame &&
2076 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
2077 h->mmco_reset = 2;
2078 if (pics > 1)
2079 h->delayed_pic[pics - 2]->mmco_reset = 2;
2080 }
2081 if (h->mmco_reset || cur->f.key_frame) {
2082 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2083 h->last_pocs[i] = INT_MIN;
2084 cnt = 0;
2085 invalid = MAX_DELAYED_PIC_COUNT;
2086 }
2087 out = h->delayed_pic[0];
2088 out_idx = 0;
2089 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
2090 h->delayed_pic[i] &&
2091 !h->delayed_pic[i - 1]->mmco_reset &&
2092 !h->delayed_pic[i]->f.key_frame;
2093 i++)
2094 if (h->delayed_pic[i]->poc < out->poc) {
2095 out = h->delayed_pic[i];
2096 out_idx = i;
2097 }
2098 if (h->avctx->has_b_frames == 0 &&
2099 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
2100 h->next_outputed_poc = INT_MIN;
2101 out_of_order = !out->f.key_frame && !h->mmco_reset &&
2102 (out->poc < h->next_outputed_poc);
2103
2104 if (h->sps.bitstream_restriction_flag &&
2105 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
2106 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
2107 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
2108 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
2109 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
2110 }
2111 h->low_delay = 0;
2112 } else if (h->low_delay &&
2113 ((h->next_outputed_poc != INT_MIN &&
2114 out->poc > h->next_outputed_poc + 2) ||
2115 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
2116 h->low_delay = 0;
2117 h->avctx->has_b_frames++;
2118 }
2119
2120 if (pics > h->avctx->has_b_frames) {
2121 out->reference &= ~DELAYED_PIC_REF;
2122 // for frame threading, the owner must be the second field's thread or
2123 // else the first thread can release the picture and reuse it unsafely
2124 for (i = out_idx; h->delayed_pic[i]; i++)
2125 h->delayed_pic[i] = h->delayed_pic[i + 1];
2126 }
2127 memmove(h->last_pocs, &h->last_pocs[1],
2128 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
2129 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
2130 if (!out_of_order && pics > h->avctx->has_b_frames) {
2131 h->next_output_pic = out;
2132 if (out->mmco_reset) {
2133 if (out_idx > 0) {
2134 h->next_outputed_poc = out->poc;
2135 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
2136 } else {
2137 h->next_outputed_poc = INT_MIN;
2138 }
2139 } else {
2140 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
2141 h->next_outputed_poc = INT_MIN;
2142 } else {
2143 h->next_outputed_poc = out->poc;
2144 }
2145 }
2146 h->mmco_reset = 0;
2147 } else {
2148 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
2149 }
2150
2151 if (h->next_output_pic) {
2152 if (h->next_output_pic->recovered) {
2153 // We have reached an recovery point and all frames after it in
2154 // display order are "recovered".
2155 h->frame_recovered |= FRAME_RECOVERED_SEI;
2156 }
2157 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2158 }
2159
2160 if (setup_finished && !h->avctx->hwaccel)
2161 ff_thread_finish_setup(h->avctx);
2162 }
2163
2164 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2165 uint8_t *src_cb, uint8_t *src_cr,
2166 int linesize, int uvlinesize,
2167 int simple)
2168 {
2169 uint8_t *top_border;
2170 int top_idx = 1;
2171 const int pixel_shift = h->pixel_shift;
2172 int chroma444 = CHROMA444(h);
2173 int chroma422 = CHROMA422(h);
2174
2175 src_y -= linesize;
2176 src_cb -= uvlinesize;
2177 src_cr -= uvlinesize;
2178
2179 if (!simple && FRAME_MBAFF(h)) {
2180 if (h->mb_y & 1) {
2181 if (!MB_MBAFF(h)) {
2182 top_border = h->top_borders[0][h->mb_x];
2183 AV_COPY128(top_border, src_y + 15 * linesize);
2184 if (pixel_shift)
2185 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2186 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2187 if (chroma444) {
2188 if (pixel_shift) {
2189 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2190 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2191 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2192 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2193 } else {
2194 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2195 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2196 }
2197 } else if (chroma422) {
2198 if (pixel_shift) {
2199 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2200 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2201 } else {
2202 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2203 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2204 }
2205 } else {
2206 if (pixel_shift) {
2207 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2208 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2209 } else {
2210 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2211 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2212 }
2213 }
2214 }
2215 }
2216 } else if (MB_MBAFF(h)) {
2217 top_idx = 0;
2218 } else
2219 return;
2220 }
2221
2222 top_border = h->top_borders[top_idx][h->mb_x];
2223 /* There are two lines saved, the line above the top macroblock
2224 * of a pair, and the line above the bottom macroblock. */
2225 AV_COPY128(top_border, src_y + 16 * linesize);
2226 if (pixel_shift)
2227 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2228
2229 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2230 if (chroma444) {
2231 if (pixel_shift) {
2232 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2233 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2234 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2235 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2236 } else {
2237 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2238 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2239 }
2240 } else if (chroma422) {
2241 if (pixel_shift) {
2242 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2243 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2244 } else {
2245 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2246 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2247 }
2248 } else {
2249 if (pixel_shift) {
2250 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2251 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2252 } else {
2253 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2254 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2255 }
2256 }
2257 }
2258 }
2259
2260 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2261 uint8_t *src_cb, uint8_t *src_cr,
2262 int linesize, int uvlinesize,
2263 int xchg, int chroma444,
2264 int simple, int pixel_shift)
2265 {
2266 int deblock_topleft;
2267 int deblock_top;
2268 int top_idx = 1;
2269 uint8_t *top_border_m1;
2270 uint8_t *top_border;
2271
2272 if (!simple && FRAME_MBAFF(h)) {
2273 if (h->mb_y & 1) {
2274 if (!MB_MBAFF(h))
2275 return;
2276 } else {
2277 top_idx = MB_MBAFF(h) ? 0 : 1;
2278 }
2279 }
2280
2281 if (h->deblocking_filter == 2) {
2282 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2283 deblock_top = h->top_type;
2284 } else {
2285 deblock_topleft = (h->mb_x > 0);
2286 deblock_top = (h->mb_y > !!MB_FIELD(h));
2287 }
2288
2289 src_y -= linesize + 1 + pixel_shift;
2290 src_cb -= uvlinesize + 1 + pixel_shift;
2291 src_cr -= uvlinesize + 1 + pixel_shift;
2292
2293 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2294 top_border = h->top_borders[top_idx][h->mb_x];
2295
2296 #define XCHG(a, b, xchg) \
2297 if (pixel_shift) { \
2298 if (xchg) { \
2299 AV_SWAP64(b + 0, a + 0); \
2300 AV_SWAP64(b + 8, a + 8); \
2301 } else { \
2302 AV_COPY128(b, a); \
2303 } \
2304 } else if (xchg) \
2305 AV_SWAP64(b, a); \
2306 else \
2307 AV_COPY64(b, a);
2308
2309 if (deblock_top) {
2310 if (deblock_topleft) {
2311 XCHG(top_border_m1 + (8 << pixel_shift),
2312 src_y - (7 << pixel_shift), 1);
2313 }
2314 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2315 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2316 if (h->mb_x + 1 < h->mb_width) {
2317 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2318 src_y + (17 << pixel_shift), 1);
2319 }
2320 }
2321 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2322 if (chroma444) {
2323 if (deblock_topleft) {
2324 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2325 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2326 }
2327 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2328 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2329 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2330 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2331 if (h->mb_x + 1 < h->mb_width) {
2332 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2333 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2334 }
2335 } else {
2336 if (deblock_top) {
2337 if (deblock_topleft) {
2338 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2339 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2340 }
2341 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2342 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2343 }
2344 }
2345 }
2346 }
2347
2348 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2349 int index)
2350 {
2351 if (high_bit_depth) {
2352 return AV_RN32A(((int32_t *)mb) + index);
2353 } else
2354 return AV_RN16A(mb + index);
2355 }
2356
2357 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2358 int index, int value)
2359 {
2360 if (high_bit_depth) {
2361 AV_WN32A(((int32_t *)mb) + index, value);
2362 } else
2363 AV_WN16A(mb + index, value);
2364 }
2365
2366 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2367 int mb_type, int is_h264,
2368 int simple,
2369 int transform_bypass,
2370 int pixel_shift,
2371 int *block_offset,
2372 int linesize,
2373 uint8_t *dest_y, int p)
2374 {
2375 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2376 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2377 int i;
2378 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2379 block_offset += 16 * p;
2380 if (IS_INTRA4x4(mb_type)) {
2381 if (IS_8x8DCT(mb_type)) {
2382 if (transform_bypass) {
2383 idct_dc_add =
2384 idct_add = h->h264dsp.h264_add_pixels8_clear;
2385 } else {
2386 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2387 idct_add = h->h264dsp.h264_idct8_add;
2388 }
2389 for (i = 0; i < 16; i += 4) {
2390 uint8_t *const ptr = dest_y + block_offset[i];
2391 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2392 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2393 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2394 } else {
2395 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2396 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2397 (h->topright_samples_available << i) & 0x4000, linesize);
2398 if (nnz) {
2399 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2400 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2401 else
2402 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2403 }
2404 }
2405 }
2406 } else {
2407 if (transform_bypass) {
2408 idct_dc_add =
2409 idct_add = h->h264dsp.h264_add_pixels4_clear;
2410 } else {
2411 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2412 idct_add = h->h264dsp.h264_idct_add;
2413 }
2414 for (i = 0; i < 16; i++) {
2415 uint8_t *const ptr = dest_y + block_offset[i];
2416 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2417
2418 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2419 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2420 } else {
2421 uint8_t *topright;
2422 int nnz, tr;
2423 uint64_t tr_high;
2424 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2425 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2426 assert(h->mb_y || linesize <= block_offset[i]);
2427 if (!topright_avail) {
2428 if (pixel_shift) {
2429 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2430 topright = (uint8_t *)&tr_high;
2431 } else {
2432 tr = ptr[3 - linesize] * 0x01010101u;
2433 topright = (uint8_t *)&tr;
2434 }
2435 } else
2436 topright = ptr + (4 << pixel_shift) - linesize;
2437 } else
2438 topright = NULL;
2439
2440 h->hpc.pred4x4[dir](ptr, topright, linesize);
2441 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2442 if (nnz) {
2443 if (is_h264) {
2444 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2445 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2446 else
2447 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2448 } else if (CONFIG_SVQ3_DECODER)
2449 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2450 }
2451 }
2452 }
2453 }
2454 } else {
2455 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2456 if (is_h264) {
2457 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2458 if (!transform_bypass)
2459 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2460 h->mb_luma_dc[p],
2461 h->dequant4_coeff[p][qscale][0]);
2462 else {
2463 static const uint8_t dc_mapping[16] = {
2464 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2465 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2466 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2467 10 * 16, 11 * 16, 14 * 16, 15 * 16
2468 };
2469 for (i = 0; i < 16; i++)
2470 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2471 pixel_shift, dc_mapping[i],
2472 dctcoef_get(h->mb_luma_dc[p],
2473 pixel_shift, i));
2474 }
2475 }
2476 } else if (CONFIG_SVQ3_DECODER)
2477 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2478 h->mb_luma_dc[p], qscale);
2479 }
2480 }
2481
2482 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2483 int is_h264, int simple,
2484 int transform_bypass,
2485 int pixel_shift,
2486 int *block_offset,
2487 int linesize,
2488 uint8_t *dest_y, int p)
2489 {
2490 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2491 int i;
2492 block_offset += 16 * p;
2493 if (!IS_INTRA4x4(mb_type)) {
2494 if (is_h264) {
2495 if (IS_INTRA16x16(mb_type)) {
2496 if (transform_bypass) {
2497 if (h->sps.profile_idc == 244 &&
2498 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2499 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2500 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2501 h->mb + (p * 256 << pixel_shift),
2502 linesize);
2503 } else {
2504 for (i = 0; i < 16; i++)
2505 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2506 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2507 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2508 h->mb + (i * 16 + p * 256 << pixel_shift),
2509 linesize);
2510 }
2511 } else {
2512 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2513 h->mb + (p * 256 << pixel_shift),
2514 linesize,
2515 h->non_zero_count_cache + p * 5 * 8);
2516 }
2517 } else if (h->cbp & 15) {
2518 if (transform_bypass) {
2519 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2520 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2521 : h->h264dsp.h264_add_pixels4_clear;
2522 for (i = 0; i < 16; i += di)
2523 if (h->non_zero_count_cache[scan8[i + p * 16]])
2524 idct_add(dest_y + block_offset[i],
2525 h->mb + (i * 16 + p * 256 << pixel_shift),
2526 linesize);
2527 } else {
2528 if (IS_8x8DCT(mb_type))
2529 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2530 h->mb + (p * 256 << pixel_shift),
2531 linesize,
2532 h->non_zero_count_cache + p * 5 * 8);
2533 else
2534 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2535 h->mb + (p * 256 << pixel_shift),
2536 linesize,
2537 h->non_zero_count_cache + p * 5 * 8);
2538 }
2539 }
2540 } else if (CONFIG_SVQ3_DECODER) {
2541 for (i = 0; i < 16; i++)
2542 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2543 // FIXME benchmark weird rule, & below
2544 uint8_t *const ptr = dest_y + block_offset[i];
2545 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2546 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2547 }
2548 }
2549 }
2550 }
2551
2552 #define BITS 8
2553 #define SIMPLE 1
2554 #include "h264_mb_template.c"
2555
2556 #undef BITS
2557 #define BITS 16
2558 #include "h264_mb_template.c"
2559
2560 #undef SIMPLE
2561 #define SIMPLE 0
2562 #include "h264_mb_template.c"
2563
2564 void ff_h264_hl_decode_mb(H264Context *h)
2565 {
2566 const int mb_xy = h->mb_xy;
2567 const int mb_type = h->cur_pic.mb_type[mb_xy];
2568 int is_complex = CONFIG_SMALL || h->is_complex ||
2569 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2570
2571 if (CHROMA444(h)) {
2572 if (is_complex || h->pixel_shift)
2573 hl_decode_mb_444_complex(h);
2574 else
2575 hl_decode_mb_444_simple_8(h);
2576 } else if (is_complex) {
2577 hl_decode_mb_complex(h);
2578 } else if (h->pixel_shift) {
2579 hl_decode_mb_simple_16(h);
2580 } else
2581 hl_decode_mb_simple_8(h);
2582 }
2583
2584 int ff_pred_weight_table(H264Context *h)
2585 {
2586 int list, i;
2587 int luma_def, chroma_def;
2588
2589 h->use_weight = 0;
2590 h->use_weight_chroma = 0;
2591 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2592 if (h->sps.chroma_format_idc)
2593 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2594 luma_def = 1 << h->luma_log2_weight_denom;
2595 chroma_def = 1 << h->chroma_log2_weight_denom;
2596
2597 for (list = 0; list < 2; list++) {
2598 h->luma_weight_flag[list] = 0;
2599 h->chroma_weight_flag[list] = 0;
2600 for (i = 0; i < h->ref_count[list]; i++) {
2601 int luma_weight_flag, chroma_weight_flag;
2602
2603 luma_weight_flag = get_bits1(&h->gb);
2604 if (luma_weight_flag) {
2605 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2606 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2607 if (h->luma_weight[i][list][0] != luma_def ||
2608 h->luma_weight[i][list][1] != 0) {
2609 h->use_weight = 1;
2610 h->luma_weight_flag[list] = 1;
2611 }
2612 } else {
2613 h->luma_weight[i][list][0] = luma_def;
2614 h->luma_weight[i][list][1] = 0;
2615 }
2616
2617 if (h->sps.chroma_format_idc) {
2618 chroma_weight_flag = get_bits1(&h->gb);
2619 if (chroma_weight_flag) {
2620 int j;
2621 for (j = 0; j < 2; j++) {
2622 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2623 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2624 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2625 h->chroma_weight[i][list][j][1] != 0) {
2626 h->use_weight_chroma = 1;
2627 h->chroma_weight_flag[list] = 1;
2628 }
2629 }
2630 } else {
2631 int j;
2632 for (j = 0; j < 2; j++) {
2633 h->chroma_weight[i][list][j][0] = chroma_def;
2634 h->chroma_weight[i][list][j][1] = 0;
2635 }
2636 }
2637 }
2638 }
2639 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2640 break;
2641 }
2642 h->use_weight = h->use_weight || h->use_weight_chroma;
2643 return 0;
2644 }
2645
2646 /**
2647 * Initialize implicit_weight table.
2648 * @param field 0/1 initialize the weight for interlaced MBAFF
2649 * -1 initializes the rest
2650 */
2651 static void implicit_weight_table(H264Context *h, int field)
2652 {
2653 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2654
2655 for (i = 0; i < 2; i++) {
2656 h->luma_weight_flag[i] = 0;
2657 h->chroma_weight_flag[i] = 0;
2658 }
2659
2660 if (field < 0) {
2661 if (h->picture_structure == PICT_FRAME) {
2662 cur_poc = h->cur_pic_ptr->poc;
2663 } else {
2664 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2665 }
2666 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2667 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2668 h->use_weight = 0;
2669 h->use_weight_chroma = 0;
2670 return;
2671 }
2672 ref_start = 0;
2673 ref_count0 = h->ref_count[0];
2674 ref_count1 = h->ref_count[1];
2675 } else {
2676 cur_poc = h->cur_pic_ptr->field_poc[field];
2677 ref_start = 16;
2678 ref_count0 = 16 + 2 * h->ref_count[0];
2679 ref_count1 = 16 + 2 * h->ref_count[1];
2680 }
2681
2682 h->use_weight = 2;
2683 h->use_weight_chroma = 2;
2684 h->luma_log2_weight_denom = 5;
2685 h->chroma_log2_weight_denom = 5;
2686
2687 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2688 int poc0 = h->ref_list[0][ref0].poc;
2689 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2690 int w = 32;
2691 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2692 int poc1 = h->ref_list[1][ref1].poc;
2693 int td = av_clip(poc1 - poc0, -128, 127);
2694 if (td) {
2695 int tb = av_clip(cur_poc - poc0, -128, 127);
2696 int tx = (16384 + (FFABS(td) >> 1)) / td;
2697 int dist_scale_factor = (tb * tx + 32) >> 8;
2698 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2699 w = 64 - dist_scale_factor;
2700 }
2701 }
2702 if (field < 0) {
2703 h->implicit_weight[ref0][ref1][0] =
2704 h->implicit_weight[ref0][ref1][1] = w;
2705 } else {
2706 h->implicit_weight[ref0][ref1][field] = w;
2707 }
2708 }
2709 }
2710 }
2711
2712 /**
2713 * instantaneous decoder refresh.
2714 */
2715 static void idr(H264Context *h)
2716 {
2717 ff_h264_remove_all_refs(h);
2718 h->prev_frame_num = 0;
2719 h->prev_frame_num_offset = 0;
2720 h->prev_poc_msb =
2721 h->prev_poc_lsb = 0;
2722 }
2723
2724 /* forget old pics after a seek */
2725 static void flush_change(H264Context *h)
2726 {
2727 int i;
2728 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2729 h->last_pocs[i] = INT_MIN;
2730 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2731 h->prev_interlaced_frame = 1;
2732 idr(h);
2733 if (h->cur_pic_ptr)
2734 h->cur_pic_ptr->reference = 0;
2735 h->first_field = 0;
2736 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2737 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2738 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2739 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2740 ff_h264_reset_sei(h);
2741 h->recovery_frame = -1;
2742 h->frame_recovered = 0;
2743 }
2744
2745 /* forget old pics after a seek */
2746 static void flush_dpb(AVCodecContext *avctx)
2747 {
2748 H264Context *h = avctx->priv_data;
2749 int i;
2750
2751 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2752 if (h->delayed_pic[i])
2753 h->delayed_pic[i]->reference = 0;
2754 h->delayed_pic[i] = NULL;
2755 }
2756
2757 flush_change(h);
2758
2759 if (h->DPB)
2760 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2761 unref_picture(h, &h->DPB[i]);
2762 h->cur_pic_ptr = NULL;
2763 unref_picture(h, &h->cur_pic);
2764
2765 h->mb_x = h->mb_y = 0;
2766
2767 h->parse_context.state = -1;
2768 h->parse_context.frame_start_found = 0;
2769 h->parse_context.overread = 0;
2770 h->parse_context.overread_index = 0;
2771 h->parse_context.index = 0;
2772 h->parse_context.last_index = 0;
2773
2774 free_tables(h, 1);
2775 h->context_initialized = 0;
2776 }
2777
2778 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2779 {
2780 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2781 int field_poc[2];
2782
2783 h->frame_num_offset = h->prev_frame_num_offset;
2784 if (h->frame_num < h->prev_frame_num)
2785 h->frame_num_offset += max_frame_num;
2786
2787 if (h->sps.poc_type == 0) {
2788 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2789
2790 if (h->poc_lsb < h->prev_poc_lsb &&
2791 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2792 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2793 else if (h->poc_lsb > h->prev_poc_lsb &&
2794 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2795 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2796 else
2797 h->poc_msb = h->prev_poc_msb;
2798 field_poc[0] =
2799 field_poc[1] = h->poc_msb + h->poc_lsb;
2800 if (h->picture_structure == PICT_FRAME)
2801 field_poc[1] += h->delta_poc_bottom;
2802 } else if (h->sps.poc_type == 1) {
2803 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2804 int i;
2805
2806 if (h->sps.poc_cycle_length != 0)
2807 abs_frame_num = h->frame_num_offset + h->frame_num;
2808 else
2809 abs_frame_num = 0;
2810
2811 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2812 abs_frame_num--;
2813
2814 expected_delta_per_poc_cycle = 0;
2815 for (i = 0; i < h->sps.poc_cycle_length; i++)
2816 // FIXME integrate during sps parse
2817 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2818
2819 if (abs_frame_num > 0) {
2820 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2821 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2822
2823 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2824 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2825 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2826 } else
2827 expectedpoc = 0;
2828
2829 if (h->nal_ref_idc == 0)
2830 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2831
2832 field_poc[0] = expectedpoc + h->delta_poc[0];
2833 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2834
2835 if (h->picture_structure == PICT_FRAME)
2836 field_poc[1] += h->delta_poc[1];
2837 } else {
2838 int poc = 2 * (h->frame_num_offset + h->frame_num);
2839
2840 if (!h->nal_ref_idc)
2841 poc--;
2842
2843 field_poc[0] = poc;
2844 field_poc[1] = poc;
2845 }
2846
2847 if (h->picture_structure != PICT_BOTTOM_FIELD)
2848 pic_field_poc[0] = field_poc[0];
2849 if (h->picture_structure != PICT_TOP_FIELD)
2850 pic_field_poc[1] = field_poc[1];
2851 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2852
2853 return 0;
2854 }
2855
2856 /**
2857 * initialize scan tables
2858 */
2859 static void init_scan_tables(H264Context *h)
2860 {
2861 int i;
2862 for (i = 0; i < 16; i++) {
2863 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2864 h->zigzag_scan[i] = T(zigzag_scan[i]);
2865 h->field_scan[i] = T(field_scan[i]);
2866 #undef T
2867 }
2868 for (i = 0; i < 64; i++) {
2869 #define T(x) (x >> 3) | ((x & 7) << 3)
2870 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2871 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2872 h->field_scan8x8[i] = T(field_scan8x8[i]);
2873 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2874 #undef T
2875 }
2876 if (h->sps.transform_bypass) { // FIXME same ugly
2877 h->zigzag_scan_q0 = zigzag_scan;
2878 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2879 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2880 h->field_scan_q0 = field_scan;
2881 h->field_scan8x8_q0 = field_scan8x8;
2882 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2883 } else {
2884 h->zigzag_scan_q0 = h->zigzag_scan;
2885 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2886 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2887 h->field_scan_q0 = h->field_scan;
2888 h->field_scan8x8_q0 = h->field_scan8x8;
2889 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2890 }
2891 }
2892
2893 static int field_end(H264Context *h, int in_setup)
2894 {
2895 AVCodecContext *const avctx = h->avctx;
2896 int err = 0;
2897 h->mb_y = 0;
2898
2899 if (!in_setup && !h->droppable)
2900 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2901 h->picture_structure == PICT_BOTTOM_FIELD);
2902
2903 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2904 if (!h->droppable) {
2905 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2906 h->prev_poc_msb = h->poc_msb;
2907 h->prev_poc_lsb = h->poc_lsb;
2908 }
2909 h->prev_frame_num_offset = h->frame_num_offset;
2910 h->prev_frame_num = h->frame_num;
2911 h->outputed_poc = h->next_outputed_poc;
2912 }
2913
2914 if (avctx->hwaccel) {
2915 if (avctx->hwaccel->end_frame(avctx) < 0)
2916 av_log(avctx, AV_LOG_ERROR,
2917 "hardware accelerator failed to decode picture\n");
2918 }
2919
2920 /*
2921 * FIXME: Error handling code does not seem to support interlaced
2922 * when slices span multiple rows
2923 * The ff_er_add_slice calls don't work right for bottom
2924 * fields; they cause massive erroneous error concealing
2925 * Error marking covers both fields (top and bottom).
2926 * This causes a mismatched s->error_count
2927 * and a bad error table. Further, the error count goes to
2928 * INT_MAX when called for bottom field, because mb_y is
2929 * past end by one (callers fault) and resync_mb_y != 0
2930 * causes problems for the first MB line, too.
2931 */
2932 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h)) {
2933 h->er.cur_pic = h->cur_pic_ptr;
2934 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2935 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2936 ff_er_frame_end(&h->er);
2937 }
2938 emms_c();
2939
2940 h->current_slice = 0;
2941
2942 return err;
2943 }
2944
2945 /**
2946 * Replicate H264 "master" context to thread contexts.
2947 */
2948 static int clone_slice(H264Context *dst, H264Context *src)
2949 {
2950 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2951 dst->cur_pic_ptr = src->cur_pic_ptr;
2952 dst->cur_pic = src->cur_pic;
2953 dst->linesize = src->linesize;
2954 dst->uvlinesize = src->uvlinesize;
2955 dst->first_field = src->first_field;
2956
2957 dst->prev_poc_msb = src->prev_poc_msb;
2958 dst->prev_poc_lsb = src->prev_poc_lsb;
2959 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2960 dst->prev_frame_num = src->prev_frame_num;
2961 dst->short_ref_count = src->short_ref_count;
2962
2963 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2964 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2965 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2966
2967 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2968 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2969
2970 return 0;
2971 }
2972
2973 /**
2974 * Compute profile from profile_idc and constraint_set?_flags.
2975 *
2976 * @param sps SPS
2977 *
2978 * @return profile as defined by FF_PROFILE_H264_*
2979 */
2980 int ff_h264_get_profile(SPS *sps)
2981 {
2982 int profile = sps->profile_idc;
2983
2984 switch (sps->profile_idc) {
2985 case FF_PROFILE_H264_BASELINE:
2986 // constraint_set1_flag set to 1
2987 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2988 break;
2989 case FF_PROFILE_H264_HIGH_10:
2990 case FF_PROFILE_H264_HIGH_422:
2991 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2992 // constraint_set3_flag set to 1
2993 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2994 break;
2995 }
2996
2997 return profile;
2998 }
2999
3000 static int h264_set_parameter_from_sps(H264Context *h)
3001 {
3002 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3003 (h->sps.bitstream_restriction_flag &&
3004 !h->sps.num_reorder_frames)) {
3005 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3006 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3007 "Reenabling low delay requires a codec flush.\n");
3008 else
3009 h->low_delay = 1;
3010 }
3011
3012 if (h->avctx->has_b_frames < 2)
3013 h->avctx->has_b_frames = !h->low_delay;
3014
3015 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3016 avpriv_request_sample(h->avctx,
3017 "Different chroma and luma bit depth");
3018 return AVERROR_PATCHWELCOME;
3019 }
3020
3021 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3022 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3023 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3024 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3025 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3026 h->pixel_shift = h->sps.bit_depth_luma > 8;
3027
3028 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3029 h->sps.chroma_format_idc);
3030 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3031 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3032 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3033 h->sps.chroma_format_idc);
3034 if (CONFIG_ERROR_RESILIENCE)
3035 ff_dsputil_init(&h->dsp, h->avctx);
3036 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3037 } else {
3038 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3039 h->sps.bit_depth_luma);
3040 return AVERROR_INVALIDDATA;
3041 }
3042 }
3043 return 0;
3044 }
3045
3046 static enum AVPixelFormat get_pixel_format(H264Context *h)
3047 {
3048 switch (h->sps.bit_depth_luma) {
3049 case 9:
3050 if (CHROMA444(h)) {
3051 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3052 return AV_PIX_FMT_GBRP9;
3053 } else
3054 return AV_PIX_FMT_YUV444P9;
3055 } else if (CHROMA422(h))
3056 return AV_PIX_FMT_YUV422P9;
3057 else
3058 return AV_PIX_FMT_YUV420P9;
3059 break;
3060 case 10:
3061 if (CHROMA444(h)) {
3062 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3063 return AV_PIX_FMT_GBRP10;
3064 } else
3065 return AV_PIX_FMT_YUV444P10;
3066 } else if (CHROMA422(h))
3067 return AV_PIX_FMT_YUV422P10;
3068 else
3069 return AV_PIX_FMT_YUV420P10;
3070 break;
3071 case 8:
3072 if (CHROMA444(h)) {
3073 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3074 return AV_PIX_FMT_GBRP;
3075 } else
3076 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3077 : AV_PIX_FMT_YUV444P;
3078 } else if (CHROMA422(h)) {
3079 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3080 : AV_PIX_FMT_YUV422P;
3081 } else {
3082 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
3083 h->avctx->codec->pix_fmts :
3084 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3085 h264_hwaccel_pixfmt_list_jpeg_420 :
3086 h264_hwaccel_pixfmt_list_420);
3087 }
3088 break;
3089 default:
3090 av_log(h->avctx, AV_LOG_ERROR,
3091 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3092 return AVERROR_INVALIDDATA;
3093 }
3094 }
3095
3096 /* export coded and cropped frame dimensions to AVCodecContext */
3097 static int init_dimensions(H264Context *h)
3098 {
3099 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3100 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3101
3102 /* handle container cropping */
3103 if (!h->sps.crop &&
3104 FFALIGN(h->avctx->width, 16) == h->width &&
3105 FFALIGN(h->avctx->height, 16) == h->height) {
3106 width = h->avctx->width;
3107 height = h->avctx->height;
3108 }
3109
3110 if (width <= 0 || height <= 0) {
3111 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3112 width, height);
3113 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3114 return AVERROR_INVALIDDATA;
3115
3116 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3117 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3118 h->sps.crop = 0;
3119
3120 width = h->width;
3121 height = h->height;
3122 }
3123
3124 h->avctx->coded_width = h->width;
3125 h->avctx->coded_height = h->height;
3126 h->avctx->width = width;
3127 h->avctx->height = height;
3128
3129 return 0;
3130 }
3131
3132 static int h264_slice_header_init(H264Context *h, int reinit)
3133 {
3134 int nb_slices = (HAVE_THREADS &&
3135 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3136 h->avctx->thread_count : 1;
3137 int i, ret;
3138
3139 h->avctx->sample_aspect_ratio = h->sps.sar;
3140 av_assert0(h->avctx->sample_aspect_ratio.den);
3141 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3142 &h->chroma_x_shift, &h->chroma_y_shift);
3143
3144 if (h->sps.timing_info_present_flag) {
3145 int64_t den = h->sps.time_scale;
3146 if (h->x264_build < 44U)
3147 den *= 2;
3148 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3149 h->sps.num_units_in_tick, den, 1 << 30);
3150 }
3151
3152 h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3153
3154 if (reinit)
3155 free_tables(h, 0);
3156 h->first_field = 0;
3157 h->prev_interlaced_frame = 1;
3158
3159 init_scan_tables(h);
3160 ret = ff_h264_alloc_tables(h);
3161 if (ret < 0) {
3162 av_log(h->avctx, AV_LOG_ERROR,
3163 "Could not allocate memory for h264\n");
3164 return ret;
3165 }
3166
3167 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3168 int max_slices;
3169 if (h->mb_height)
3170 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3171 else
3172 max_slices = MAX_THREADS;
3173 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3174 " reducing to %d\n", nb_slices, max_slices);
3175 nb_slices = max_slices;
3176 }
3177 h->slice_context_count = nb_slices;
3178
3179 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3180 ret = context_init(h);
3181 if (ret < 0) {
3182 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3183 return ret;
3184 }
3185 } else {
3186 for (i = 1; i < h->slice_context_count; i++) {
3187 H264Context *c;
3188 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3189 if (!c)
3190 return AVERROR(ENOMEM);
3191 c->avctx = h->avctx;
3192 c->dsp = h->dsp;
3193 c->vdsp = h->vdsp;
3194 c->h264dsp = h->h264dsp;
3195 c->h264qpel = h->h264qpel;
3196 c->h264chroma = h->h264chroma;
3197 c->sps = h->sps;
3198 c->pps = h->pps;
3199 c->pixel_shift = h->pixel_shift;
3200 c->width = h->width;
3201 c->height = h->height;
3202 c->linesize = h->linesize;
3203 c->uvlinesize = h->uvlinesize;
3204 c->chroma_x_shift = h->chroma_x_shift;
3205 c->chroma_y_shift = h->chroma_y_shift;
3206 c->qscale = h->qscale;
3207 c->droppable = h->droppable;
3208 c->data_partitioning = h->data_partitioning;
3209 c->low_delay = h->low_delay;
3210 c->mb_width = h->mb_width;
3211 c->mb_height = h->mb_height;
3212 c->mb_stride = h->mb_stride;
3213 c->mb_num = h->mb_num;
3214 c->flags = h->flags;
3215 c->workaround_bugs = h->workaround_bugs;
3216 c->pict_type = h->pict_type;
3217
3218 init_scan_tables(c);
3219 clone_tables(c, h, i);
3220 c->context_initialized = 1;
3221 }
3222
3223 for (i = 0; i < h->slice_context_count; i++)
3224 if ((ret = context_init(h->thread_context[i])) < 0) {
3225 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3226 return ret;
3227 }
3228 }
3229
3230 h->context_initialized = 1;
3231
3232 return 0;
3233 }
3234