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