f1f5fc05f9c000f7dc51354a5eb69ddba57c3eae
[libav.git] / libavcodec / h264_slice.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 / MPEG-4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
26 */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/stereo3d.h"
32 #include "libavutil/timer.h"
33 #include "internal.h"
34 #include "cabac.h"
35 #include "cabac_functions.h"
36 #include "error_resilience.h"
37 #include "golomb_legacy.h"
38 #include "avcodec.h"
39 #include "h264.h"
40 #include "h264dec.h"
41 #include "h264data.h"
42 #include "h264chroma.h"
43 #include "h264_mvpred.h"
44 #include "h264_ps.h"
45 #include "mathops.h"
46 #include "mpegutils.h"
47 #include "rectangle.h"
48 #include "thread.h"
49
50 static const uint8_t field_scan[16] = {
51 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
52 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
53 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
54 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
55 };
56
57 static const uint8_t field_scan8x8[64] = {
58 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
59 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
60 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
61 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
62 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
63 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
64 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
65 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
66 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
67 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
68 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
69 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
70 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
71 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
72 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
73 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
74 };
75
76 static const uint8_t field_scan8x8_cavlc[64] = {
77 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
78 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
79 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
80 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
81 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
82 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
83 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
84 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
85 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
86 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
87 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
88 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
89 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
90 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
91 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
92 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
93 };
94
95 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
96 static const uint8_t zigzag_scan8x8_cavlc[64] = {
97 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
98 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
99 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
100 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
101 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
102 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
103 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
104 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
105 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
106 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
107 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
108 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
109 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
110 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
111 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
112 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
113 };
114
115 static void release_unused_pictures(H264Context *h, int remove_current)
116 {
117 int i;
118
119 /* release non reference frames */
120 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
121 if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
122 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
123 ff_h264_unref_picture(h, &h->DPB[i]);
124 }
125 }
126 }
127
128 static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
129 {
130 const H264Context *h = sl->h264;
131 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
132
133 av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
134 // edge emu needs blocksize + filter length - 1
135 // (= 21x21 for H.264)
136 av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
137
138 av_fast_malloc(&sl->top_borders[0], &sl->top_borders_allocated[0],
139 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
140 av_fast_malloc(&sl->top_borders[1], &sl->top_borders_allocated[1],
141 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
142
143 if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
144 !sl->top_borders[0] || !sl->top_borders[1]) {
145 av_freep(&sl->bipred_scratchpad);
146 av_freep(&sl->edge_emu_buffer);
147 av_freep(&sl->top_borders[0]);
148 av_freep(&sl->top_borders[1]);
149
150 sl->bipred_scratchpad_allocated = 0;
151 sl->edge_emu_buffer_allocated = 0;
152 sl->top_borders_allocated[0] = 0;
153 sl->top_borders_allocated[1] = 0;
154 return AVERROR(ENOMEM);
155 }
156
157 return 0;
158 }
159
160 static int init_table_pools(H264Context *h)
161 {
162 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
163 const int mb_array_size = h->mb_stride * h->mb_height;
164 const int b4_stride = h->mb_width * 4 + 1;
165 const int b4_array_size = b4_stride * h->mb_height * 4;
166
167 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
168 av_buffer_allocz);
169 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
170 sizeof(uint32_t), av_buffer_allocz);
171 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
172 sizeof(int16_t), av_buffer_allocz);
173 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
174
175 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
176 !h->ref_index_pool) {
177 av_buffer_pool_uninit(&h->qscale_table_pool);
178 av_buffer_pool_uninit(&h->mb_type_pool);
179 av_buffer_pool_uninit(&h->motion_val_pool);
180 av_buffer_pool_uninit(&h->ref_index_pool);
181 return AVERROR(ENOMEM);
182 }
183
184 return 0;
185 }
186
187 static int alloc_picture(H264Context *h, H264Picture *pic)
188 {
189 int i, ret = 0;
190
191 av_assert0(!pic->f->data[0]);
192
193 pic->tf.f = pic->f;
194 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
195 AV_GET_BUFFER_FLAG_REF : 0);
196 if (ret < 0)
197 goto fail;
198
199 if (h->avctx->hwaccel) {
200 const AVHWAccel *hwaccel = h->avctx->hwaccel;
201 av_assert0(!pic->hwaccel_picture_private);
202 if (hwaccel->frame_priv_data_size) {
203 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
204 if (!pic->hwaccel_priv_buf)
205 return AVERROR(ENOMEM);
206 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
207 }
208 }
209
210 if (!h->qscale_table_pool) {
211 ret = init_table_pools(h);
212 if (ret < 0)
213 goto fail;
214 }
215
216 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
217 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
218 if (!pic->qscale_table_buf || !pic->mb_type_buf)
219 goto fail;
220
221 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
222 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
223
224 for (i = 0; i < 2; i++) {
225 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
226 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
227 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
228 goto fail;
229
230 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
231 pic->ref_index[i] = pic->ref_index_buf[i]->data;
232 }
233
234 return 0;
235 fail:
236 ff_h264_unref_picture(h, pic);
237 return (ret < 0) ? ret : AVERROR(ENOMEM);
238 }
239
240 static inline int pic_is_unused(H264Context *h, H264Picture *pic)
241 {
242 if (!pic->f->buf[0])
243 return 1;
244 return 0;
245 }
246
247 static int find_unused_picture(H264Context *h)
248 {
249 int i;
250
251 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
252 if (pic_is_unused(h, &h->DPB[i]))
253 break;
254 }
255 if (i == H264_MAX_PICTURE_COUNT)
256 return AVERROR_INVALIDDATA;
257
258 return i;
259 }
260
261 static int initialize_cur_frame(H264Context *h)
262 {
263 H264Picture *cur;
264 int ret;
265
266 release_unused_pictures(h, 1);
267 ff_h264_unref_picture(h, &h->cur_pic);
268 h->cur_pic_ptr = NULL;
269
270 ret = find_unused_picture(h);
271 if (ret < 0) {
272 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
273 return ret;
274 }
275 cur = &h->DPB[ret];
276
277 ret = alloc_picture(h, cur);
278 if (ret < 0)
279 return ret;
280
281 ret = ff_h264_ref_picture(h, &h->cur_pic, cur);
282 if (ret < 0)
283 return ret;
284 h->cur_pic_ptr = cur;
285
286 return 0;
287 }
288
289 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
290
291 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
292 ((pic && pic >= old_ctx->DPB && \
293 pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
294 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
295
296 static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
297 H264Context *new_base,
298 H264Context *old_base)
299 {
300 int i;
301
302 for (i = 0; i < count; i++) {
303 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
304 IN_RANGE(from[i], old_base->DPB,
305 sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
306 !from[i]));
307 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
308 }
309 }
310
311 static int h264_slice_header_init(H264Context *h);
312
313 int ff_h264_update_thread_context(AVCodecContext *dst,
314 const AVCodecContext *src)
315 {
316 H264Context *h = dst->priv_data, *h1 = src->priv_data;
317 int inited = h->context_initialized, err = 0;
318 int need_reinit = 0;
319 int i, ret;
320
321 if (dst == src || !h1->context_initialized)
322 return 0;
323
324 if (!h1->ps.sps)
325 return AVERROR_INVALIDDATA;
326
327 if (inited &&
328 (h->width != h1->width ||
329 h->height != h1->height ||
330 h->mb_width != h1->mb_width ||
331 h->mb_height != h1->mb_height ||
332 !h->ps.sps ||
333 h->ps.sps->bit_depth_luma != h1->ps.sps->bit_depth_luma ||
334 h->ps.sps->chroma_format_idc != h1->ps.sps->chroma_format_idc ||
335 h->ps.sps->colorspace != h1->ps.sps->colorspace)) {
336 need_reinit = 1;
337 }
338
339 // SPS/PPS
340 for (i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++) {
341 av_buffer_unref(&h->ps.sps_list[i]);
342 if (h1->ps.sps_list[i]) {
343 h->ps.sps_list[i] = av_buffer_ref(h1->ps.sps_list[i]);
344 if (!h->ps.sps_list[i])
345 return AVERROR(ENOMEM);
346 }
347 }
348 for (i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++) {
349 av_buffer_unref(&h->ps.pps_list[i]);
350 if (h1->ps.pps_list[i]) {
351 h->ps.pps_list[i] = av_buffer_ref(h1->ps.pps_list[i]);
352 if (!h->ps.pps_list[i])
353 return AVERROR(ENOMEM);
354 }
355 }
356
357 h->ps.sps = h1->ps.sps;
358
359 if (need_reinit || !inited) {
360 h->width = h1->width;
361 h->height = h1->height;
362 h->mb_height = h1->mb_height;
363 h->mb_width = h1->mb_width;
364 h->mb_num = h1->mb_num;
365 h->mb_stride = h1->mb_stride;
366 h->b_stride = h1->b_stride;
367
368 if ((err = h264_slice_header_init(h)) < 0) {
369 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
370 return err;
371 }
372
373 /* copy block_offset since frame_start may not be called */
374 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
375 }
376
377 h->avctx->coded_height = h1->avctx->coded_height;
378 h->avctx->coded_width = h1->avctx->coded_width;
379 h->avctx->width = h1->avctx->width;
380 h->avctx->height = h1->avctx->height;
381 h->width_from_caller = h1->width_from_caller;
382 h->height_from_caller = h1->height_from_caller;
383 h->coded_picture_number = h1->coded_picture_number;
384 h->first_field = h1->first_field;
385 h->picture_structure = h1->picture_structure;
386 h->mb_aff_frame = h1->mb_aff_frame;
387 h->droppable = h1->droppable;
388
389 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
390 ff_h264_unref_picture(h, &h->DPB[i]);
391 if (h1->DPB[i].f->buf[0] &&
392 (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
393 return ret;
394 }
395
396 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
397 ff_h264_unref_picture(h, &h->cur_pic);
398 if (h1->cur_pic.f->buf[0]) {
399 ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
400 if (ret < 0)
401 return ret;
402 }
403
404 h->enable_er = h1->enable_er;
405 h->workaround_bugs = h1->workaround_bugs;
406 h->droppable = h1->droppable;
407
408 // extradata/NAL handling
409 h->is_avc = h1->is_avc;
410 h->nal_length_size = h1->nal_length_size;
411
412 memcpy(&h->poc, &h1->poc, sizeof(h->poc));
413
414 memcpy(h->short_ref, h1->short_ref, sizeof(h->short_ref));
415 memcpy(h->long_ref, h1->long_ref, sizeof(h->long_ref));
416 memcpy(h->delayed_pic, h1->delayed_pic, sizeof(h->delayed_pic));
417 memcpy(h->last_pocs, h1->last_pocs, sizeof(h->last_pocs));
418
419 h->next_outputed_poc = h1->next_outputed_poc;
420
421 memcpy(h->mmco, h1->mmco, sizeof(h->mmco));
422 h->nb_mmco = h1->nb_mmco;
423 h->mmco_reset = h1->mmco_reset;
424 h->explicit_ref_marking = h1->explicit_ref_marking;
425 h->long_ref_count = h1->long_ref_count;
426 h->short_ref_count = h1->short_ref_count;
427
428 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
429 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
430 copy_picture_range(h->delayed_pic, h1->delayed_pic,
431 MAX_DELAYED_PIC_COUNT + 2, h, h1);
432
433 if (!h->cur_pic_ptr)
434 return 0;
435
436 if (!h->droppable) {
437 err = ff_h264_execute_ref_pic_marking(h);
438 h->poc.prev_poc_msb = h->poc.poc_msb;
439 h->poc.prev_poc_lsb = h->poc.poc_lsb;
440 }
441 h->poc.prev_frame_num_offset = h->poc.frame_num_offset;
442 h->poc.prev_frame_num = h->poc.frame_num;
443
444 h->recovery_frame = h1->recovery_frame;
445 h->frame_recovered = h1->frame_recovered;
446
447 return err;
448 }
449
450 static int h264_frame_start(H264Context *h)
451 {
452 H264Picture *pic;
453 int i, ret;
454 const int pixel_shift = h->pixel_shift;
455
456 ret = initialize_cur_frame(h);
457 if (ret < 0)
458 return ret;
459
460 pic = h->cur_pic_ptr;
461 pic->reference = h->droppable ? 0 : h->picture_structure;
462 pic->f->coded_picture_number = h->coded_picture_number++;
463 pic->field_picture = h->picture_structure != PICT_FRAME;
464 pic->frame_num = h->poc.frame_num;
465 /*
466 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
467 * in later.
468 * See decode_nal_units().
469 */
470 pic->f->key_frame = 0;
471 pic->mmco_reset = 0;
472 pic->recovered = 0;
473
474 pic->f->pict_type = h->slice_ctx[0].slice_type;
475
476 pic->f->crop_left = h->crop_left;
477 pic->f->crop_right = h->crop_right;
478 pic->f->crop_top = h->crop_top;
479 pic->f->crop_bottom = h->crop_bottom;
480
481 if (CONFIG_ERROR_RESILIENCE && h->enable_er)
482 ff_er_frame_start(&h->slice_ctx[0].er);
483
484 for (i = 0; i < 16; i++) {
485 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
486 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
487 }
488 for (i = 0; i < 16; i++) {
489 h->block_offset[16 + i] =
490 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
491 h->block_offset[48 + 16 + i] =
492 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
493 }
494
495 /* Some macroblocks can be accessed before they're available in case
496 * of lost slices, MBAFF or threading. */
497 memset(h->slice_table, -1,
498 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
499
500 /* We mark the current picture as non-reference after allocating it, so
501 * that if we break out due to an error it can be released automatically
502 * in the next ff_mpv_frame_start().
503 */
504 h->cur_pic_ptr->reference = 0;
505
506 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
507
508 h->postpone_filter = 0;
509
510 h->mb_aff_frame = h->ps.sps->mb_aff && (h->picture_structure == PICT_FRAME);
511
512 assert(h->cur_pic_ptr->long_ref == 0);
513
514 return 0;
515 }
516
517 static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
518 uint8_t *src_y,
519 uint8_t *src_cb, uint8_t *src_cr,
520 int linesize, int uvlinesize,
521 int simple)
522 {
523 uint8_t *top_border;
524 int top_idx = 1;
525 const int pixel_shift = h->pixel_shift;
526 int chroma444 = CHROMA444(h);
527 int chroma422 = CHROMA422(h);
528
529 src_y -= linesize;
530 src_cb -= uvlinesize;
531 src_cr -= uvlinesize;
532
533 if (!simple && FRAME_MBAFF(h)) {
534 if (sl->mb_y & 1) {
535 if (!MB_MBAFF(sl)) {
536 top_border = sl->top_borders[0][sl->mb_x];
537 AV_COPY128(top_border, src_y + 15 * linesize);
538 if (pixel_shift)
539 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
540 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
541 if (chroma444) {
542 if (pixel_shift) {
543 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
544 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
545 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
546 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
547 } else {
548 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
549 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
550 }
551 } else if (chroma422) {
552 if (pixel_shift) {
553 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
554 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
555 } else {
556 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
557 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
558 }
559 } else {
560 if (pixel_shift) {
561 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
562 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
563 } else {
564 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
565 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
566 }
567 }
568 }
569 }
570 } else if (MB_MBAFF(sl)) {
571 top_idx = 0;
572 } else
573 return;
574 }
575
576 top_border = sl->top_borders[top_idx][sl->mb_x];
577 /* There are two lines saved, the line above the top macroblock
578 * of a pair, and the line above the bottom macroblock. */
579 AV_COPY128(top_border, src_y + 16 * linesize);
580 if (pixel_shift)
581 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
582
583 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
584 if (chroma444) {
585 if (pixel_shift) {
586 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
587 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
588 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
589 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
590 } else {
591 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
592 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
593 }
594 } else if (chroma422) {
595 if (pixel_shift) {
596 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
597 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
598 } else {
599 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
600 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
601 }
602 } else {
603 if (pixel_shift) {
604 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
605 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
606 } else {
607 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
608 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
609 }
610 }
611 }
612 }
613
614 /**
615 * Initialize implicit_weight table.
616 * @param field 0/1 initialize the weight for interlaced MBAFF
617 * -1 initializes the rest
618 */
619 static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
620 {
621 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
622
623 for (i = 0; i < 2; i++) {
624 sl->pwt.luma_weight_flag[i] = 0;
625 sl->pwt.chroma_weight_flag[i] = 0;
626 }
627
628 if (field < 0) {
629 if (h->picture_structure == PICT_FRAME) {
630 cur_poc = h->cur_pic_ptr->poc;
631 } else {
632 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
633 }
634 if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
635 sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
636 sl->pwt.use_weight = 0;
637 sl->pwt.use_weight_chroma = 0;
638 return;
639 }
640 ref_start = 0;
641 ref_count0 = sl->ref_count[0];
642 ref_count1 = sl->ref_count[1];
643 } else {
644 cur_poc = h->cur_pic_ptr->field_poc[field];
645 ref_start = 16;
646 ref_count0 = 16 + 2 * sl->ref_count[0];
647 ref_count1 = 16 + 2 * sl->ref_count[1];
648 }
649
650 sl->pwt.use_weight = 2;
651 sl->pwt.use_weight_chroma = 2;
652 sl->pwt.luma_log2_weight_denom = 5;
653 sl->pwt.chroma_log2_weight_denom = 5;
654
655 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
656 int poc0 = sl->ref_list[0][ref0].poc;
657 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
658 int w = 32;
659 if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
660 int poc1 = sl->ref_list[1][ref1].poc;
661 int td = av_clip_int8(poc1 - poc0);
662 if (td) {
663 int tb = av_clip_int8(cur_poc - poc0);
664 int tx = (16384 + (FFABS(td) >> 1)) / td;
665 int dist_scale_factor = (tb * tx + 32) >> 8;
666 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
667 w = 64 - dist_scale_factor;
668 }
669 }
670 if (field < 0) {
671 sl->pwt.implicit_weight[ref0][ref1][0] =
672 sl->pwt.implicit_weight[ref0][ref1][1] = w;
673 } else {
674 sl->pwt.implicit_weight[ref0][ref1][field] = w;
675 }
676 }
677 }
678 }
679
680 /**
681 * initialize scan tables
682 */
683 static void init_scan_tables(H264Context *h)
684 {
685 int i;
686 for (i = 0; i < 16; i++) {
687 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
688 h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
689 h->field_scan[i] = TRANSPOSE(field_scan[i]);
690 #undef TRANSPOSE
691 }
692 for (i = 0; i < 64; i++) {
693 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
694 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
695 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
696 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
697 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
698 #undef TRANSPOSE
699 }
700 if (h->ps.sps->transform_bypass) { // FIXME same ugly
701 h->zigzag_scan_q0 = ff_zigzag_scan;
702 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
703 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
704 h->field_scan_q0 = field_scan;
705 h->field_scan8x8_q0 = field_scan8x8;
706 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
707 } else {
708 h->zigzag_scan_q0 = h->zigzag_scan;
709 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
710 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
711 h->field_scan_q0 = h->field_scan;
712 h->field_scan8x8_q0 = h->field_scan8x8;
713 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
714 }
715 }
716
717 static enum AVPixelFormat get_pixel_format(H264Context *h)
718 {
719 #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
720 CONFIG_H264_D3D11VA_HWACCEL + \
721 CONFIG_H264_VAAPI_HWACCEL + \
722 (CONFIG_H264_VDA_HWACCEL * 2) + \
723 CONFIG_H264_VDPAU_HWACCEL)
724 enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
725 const enum AVPixelFormat *choices = pix_fmts;
726
727 switch (h->ps.sps->bit_depth_luma) {
728 case 9:
729 if (CHROMA444(h)) {
730 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
731 *fmt++ = AV_PIX_FMT_GBRP9;
732 } else
733 *fmt++ = AV_PIX_FMT_YUV444P9;
734 } else if (CHROMA422(h))
735 *fmt++ = AV_PIX_FMT_YUV422P9;
736 else
737 *fmt++ = AV_PIX_FMT_YUV420P9;
738 break;
739 case 10:
740 if (CHROMA444(h)) {
741 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
742 *fmt++ = AV_PIX_FMT_GBRP10;
743 } else
744 *fmt++ = AV_PIX_FMT_YUV444P10;
745 } else if (CHROMA422(h))
746 *fmt++ = AV_PIX_FMT_YUV422P10;
747 else
748 *fmt++ = AV_PIX_FMT_YUV420P10;
749 break;
750 case 8:
751 #if CONFIG_H264_VDPAU_HWACCEL
752 *fmt++ = AV_PIX_FMT_VDPAU;
753 #endif
754 if (CHROMA444(h)) {
755 if (h->avctx->colorspace == AVCOL_SPC_RGB)
756 *fmt++ = AV_PIX_FMT_GBRP;
757 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
758 *fmt++ = AV_PIX_FMT_YUVJ444P;
759 else
760 *fmt++ = AV_PIX_FMT_YUV444P;
761 } else if (CHROMA422(h)) {
762 if (h->avctx->color_range == AVCOL_RANGE_JPEG)
763 *fmt++ = AV_PIX_FMT_YUVJ422P;
764 else
765 *fmt++ = AV_PIX_FMT_YUV422P;
766 } else {
767 #if CONFIG_H264_DXVA2_HWACCEL
768 *fmt++ = AV_PIX_FMT_DXVA2_VLD;
769 #endif
770 #if CONFIG_H264_D3D11VA_HWACCEL
771 *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
772 #endif
773 #if CONFIG_H264_VAAPI_HWACCEL
774 *fmt++ = AV_PIX_FMT_VAAPI;
775 #endif
776 #if CONFIG_H264_VDA_HWACCEL
777 *fmt++ = AV_PIX_FMT_VDA_VLD;
778 *fmt++ = AV_PIX_FMT_VDA;
779 #endif
780 if (h->avctx->codec->pix_fmts)
781 choices = h->avctx->codec->pix_fmts;
782 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
783 *fmt++ = AV_PIX_FMT_YUVJ420P;
784 else
785 *fmt++ = AV_PIX_FMT_YUV420P;
786 }
787 break;
788 default:
789 av_log(h->avctx, AV_LOG_ERROR,
790 "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
791 return AVERROR_INVALIDDATA;
792 }
793
794 *fmt = AV_PIX_FMT_NONE;
795
796 return ff_get_format(h->avctx, choices);
797 }
798
799 /* export coded and cropped frame dimensions to AVCodecContext */
800 static int init_dimensions(H264Context *h)
801 {
802 SPS *sps = h->ps.sps;
803 int cr = sps->crop_right;
804 int cl = sps->crop_left;
805 int ct = sps->crop_top;
806 int cb = sps->crop_bottom;
807 int width = h->width - (cr + cl);
808 int height = h->height - (ct + cb);
809
810 /* handle container cropping */
811 if (h->width_from_caller > 0 && h->height_from_caller > 0 &&
812 !sps->crop_top && !sps->crop_left &&
813 FFALIGN(h->width_from_caller, 16) == FFALIGN(width, 16) &&
814 FFALIGN(h->height_from_caller, 16) == FFALIGN(height, 16)) {
815 width = h->width_from_caller;
816 height = h->height_from_caller;
817 cl = 0;
818 ct = 0;
819 cr = h->width - width;
820 cb = h->height - height;
821 } else {
822 h->width_from_caller = 0;
823 h->height_from_caller = 0;
824 }
825
826 h->avctx->coded_width = h->width;
827 h->avctx->coded_height = h->height;
828 h->avctx->width = width;
829 h->avctx->height = height;
830 h->crop_right = cr;
831 h->crop_left = cl;
832 h->crop_top = ct;
833 h->crop_bottom = cb;
834
835 return 0;
836 }
837
838 static int h264_slice_header_init(H264Context *h)
839 {
840 const SPS *sps = h->ps.sps;
841 int i, ret;
842
843 ff_set_sar(h->avctx, sps->sar);
844 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
845 &h->chroma_x_shift, &h->chroma_y_shift);
846
847 if (sps->timing_info_present_flag) {
848 int64_t den = sps->time_scale;
849 if (h->sei.unregistered.x264_build < 44U)
850 den *= 2;
851 av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
852 sps->num_units_in_tick, den, 1 << 30);
853 }
854
855 ff_h264_free_tables(h);
856
857 h->first_field = 0;
858 h->prev_interlaced_frame = 1;
859
860 init_scan_tables(h);
861 ret = ff_h264_alloc_tables(h);
862 if (ret < 0) {
863 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
864 return ret;
865 }
866
867 if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 10) {
868 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
869 sps->bit_depth_luma);
870 return AVERROR_INVALIDDATA;
871 }
872
873 h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
874 h->pixel_shift = sps->bit_depth_luma > 8;
875 h->chroma_format_idc = sps->chroma_format_idc;
876 h->bit_depth_luma = sps->bit_depth_luma;
877
878 ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
879 sps->chroma_format_idc);
880 ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
881 ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
882 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
883 sps->chroma_format_idc);
884 ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
885
886 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
887 ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
888 if (ret < 0) {
889 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
890 return ret;
891 }
892 } else {
893 for (i = 0; i < h->nb_slice_ctx; i++) {
894 H264SliceContext *sl = &h->slice_ctx[i];
895
896 sl->h264 = h;
897 sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
898 sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
899 sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
900
901 if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
902 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
903 return ret;
904 }
905 }
906 }
907
908 h->context_initialized = 1;
909
910 return 0;
911 }
912
913 static int h264_init_ps(H264Context *h, const H264SliceContext *sl)
914 {
915 const SPS *sps;
916 int needs_reinit = 0, ret;
917
918 h->ps.pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
919 if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
920 h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;
921
922 if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
923 h->chroma_format_idc != h->ps.sps->chroma_format_idc)
924 needs_reinit = 1;
925 }
926 sps = h->ps.sps;
927
928 h->avctx->profile = ff_h264_get_profile(sps);
929 h->avctx->level = sps->level_idc;
930 h->avctx->refs = sps->ref_frame_count;
931
932 if (h->mb_width != sps->mb_width ||
933 h->mb_height != sps->mb_height)
934 needs_reinit = 1;
935
936 h->mb_width = sps->mb_width;
937 h->mb_height = sps->mb_height;
938 h->mb_num = h->mb_width * h->mb_height;
939 h->mb_stride = h->mb_width + 1;
940
941 h->b_stride = h->mb_width * 4;
942
943 h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
944
945 h->width = 16 * h->mb_width;
946 h->height = 16 * h->mb_height;
947
948 ret = init_dimensions(h);
949 if (ret < 0)
950 return ret;
951
952 if (sps->video_signal_type_present_flag) {
953 h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG
954 : AVCOL_RANGE_MPEG;
955 if (sps->colour_description_present_flag) {
956 if (h->avctx->colorspace != sps->colorspace)
957 needs_reinit = 1;
958 h->avctx->color_primaries = sps->color_primaries;
959 h->avctx->color_trc = sps->color_trc;
960 h->avctx->colorspace = sps->colorspace;
961 }
962 }
963
964 if (!h->context_initialized || needs_reinit) {
965 h->context_initialized = 0;
966 if (sl != h->slice_ctx) {
967 av_log(h->avctx, AV_LOG_ERROR,
968 "changing width %d -> %d / height %d -> %d on "
969 "slice %d\n",
970 h->width, h->avctx->coded_width,
971 h->height, h->avctx->coded_height,
972 h->current_slice + 1);
973 return AVERROR_INVALIDDATA;
974 }
975
976 ff_h264_flush_change(h);
977
978 if ((ret = get_pixel_format(h)) < 0)
979 return ret;
980 h->avctx->pix_fmt = ret;
981
982 av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
983 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
984
985 if ((ret = h264_slice_header_init(h)) < 0) {
986 av_log(h->avctx, AV_LOG_ERROR,
987 "h264_slice_header_init() failed\n");
988 return ret;
989 }
990 }
991
992 return 0;
993 }
994
995 static int h264_export_frame_props(H264Context *h)
996 {
997 const SPS *sps = h->ps.sps;
998 H264Picture *cur = h->cur_pic_ptr;
999
1000 cur->f->interlaced_frame = 0;
1001 cur->f->repeat_pict = 0;
1002
1003 /* Signal interlacing information externally. */
1004 /* Prioritize picture timing SEI information over used
1005 * decoding process if it exists. */
1006
1007 if (sps->pic_struct_present_flag) {
1008 H264SEIPictureTiming *pt = &h->sei.picture_timing;
1009 switch (pt->pic_struct) {
1010 case SEI_PIC_STRUCT_FRAME:
1011 break;
1012 case SEI_PIC_STRUCT_TOP_FIELD:
1013 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1014 cur->f->interlaced_frame = 1;
1015 break;
1016 case SEI_PIC_STRUCT_TOP_BOTTOM:
1017 case SEI_PIC_STRUCT_BOTTOM_TOP:
1018 if (FIELD_OR_MBAFF_PICTURE(h))
1019 cur->f->interlaced_frame = 1;
1020 else
1021 // try to flag soft telecine progressive
1022 cur->f->interlaced_frame = h->prev_interlaced_frame;
1023 break;
1024 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1025 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1026 /* Signal the possibility of telecined film externally
1027 * (pic_struct 5,6). From these hints, let the applications
1028 * decide if they apply deinterlacing. */
1029 cur->f->repeat_pict = 1;
1030 break;
1031 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1032 cur->f->repeat_pict = 2;
1033 break;
1034 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1035 cur->f->repeat_pict = 4;
1036 break;
1037 }
1038
1039 if ((pt->ct_type & 3) &&
1040 pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1041 cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
1042 } else {
1043 /* Derive interlacing flag from used decoding process. */
1044 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
1045 }
1046 h->prev_interlaced_frame = cur->f->interlaced_frame;
1047
1048 if (cur->field_poc[0] != cur->field_poc[1]) {
1049 /* Derive top_field_first from field pocs. */
1050 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1051 } else {
1052 if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
1053 /* Use picture timing SEI information. Even if it is a
1054 * information of a past frame, better than nothing. */
1055 if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1056 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1057 cur->f->top_field_first = 1;
1058 else
1059 cur->f->top_field_first = 0;
1060 } else {
1061 /* Most likely progressive */
1062 cur->f->top_field_first = 0;
1063 }
1064 }
1065
1066 if (h->sei.frame_packing.present &&
1067 h->sei.frame_packing.arrangement_type >= 0 &&
1068 h->sei.frame_packing.arrangement_type <= 6 &&
1069 h->sei.frame_packing.content_interpretation_type > 0 &&
1070 h->sei.frame_packing.content_interpretation_type < 3) {
1071 H264SEIFramePacking *fp = &h->sei.frame_packing;
1072 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
1073 if (!stereo)
1074 return AVERROR(ENOMEM);
1075
1076 switch (fp->arrangement_type) {
1077 case 0:
1078 stereo->type = AV_STEREO3D_CHECKERBOARD;
1079 break;
1080 case 1:
1081 stereo->type = AV_STEREO3D_COLUMNS;
1082 break;
1083 case 2:
1084 stereo->type = AV_STEREO3D_LINES;
1085 break;
1086 case 3:
1087 if (fp->quincunx_subsampling)
1088 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
1089 else
1090 stereo->type = AV_STEREO3D_SIDEBYSIDE;
1091 break;
1092 case 4:
1093 stereo->type = AV_STEREO3D_TOPBOTTOM;
1094 break;
1095 case 5:
1096 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
1097 break;
1098 case 6:
1099 stereo->type = AV_STEREO3D_2D;
1100 break;
1101 }
1102
1103 if (fp->content_interpretation_type == 2)
1104 stereo->flags = AV_STEREO3D_FLAG_INVERT;
1105 }
1106
1107 if (h->sei.display_orientation.present &&
1108 (h->sei.display_orientation.anticlockwise_rotation ||
1109 h->sei.display_orientation.hflip ||
1110 h->sei.display_orientation.vflip)) {
1111 H264SEIDisplayOrientation *o = &h->sei.display_orientation;
1112 double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
1113 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
1114 AV_FRAME_DATA_DISPLAYMATRIX,
1115 sizeof(int32_t) * 9);
1116 if (!rotation)
1117 return AVERROR(ENOMEM);
1118
1119 av_display_rotation_set((int32_t *)rotation->data, angle);
1120 av_display_matrix_flip((int32_t *)rotation->data,
1121 o->hflip, o->vflip);
1122 }
1123
1124 if (h->sei.afd.present) {
1125 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
1126 sizeof(uint8_t));
1127 if (!sd)
1128 return AVERROR(ENOMEM);
1129
1130 *sd->data = h->sei.afd.active_format_description;
1131 h->sei.afd.present = 0;
1132 }
1133
1134 if (h->sei.a53_caption.a53_caption) {
1135 H264SEIA53Caption *a53 = &h->sei.a53_caption;
1136 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
1137 AV_FRAME_DATA_A53_CC,
1138 a53->a53_caption_size);
1139 if (!sd)
1140 return AVERROR(ENOMEM);
1141
1142 memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
1143 av_freep(&a53->a53_caption);
1144 a53->a53_caption_size = 0;
1145 }
1146
1147 return 0;
1148 }
1149
1150 static int h264_select_output_frame(H264Context *h)
1151 {
1152 const SPS *sps = h->ps.sps;
1153 H264Picture *out = h->cur_pic_ptr;
1154 H264Picture *cur = h->cur_pic_ptr;
1155 int i, pics, out_of_order, out_idx;
1156 int invalid = 0, cnt = 0;
1157 int ret;
1158
1159 if (sps->bitstream_restriction_flag ||
1160 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
1161 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
1162 }
1163
1164 pics = 0;
1165 while (h->delayed_pic[pics])
1166 pics++;
1167
1168 assert(pics <= MAX_DELAYED_PIC_COUNT);
1169
1170 h->delayed_pic[pics++] = cur;
1171 if (cur->reference == 0)
1172 cur->reference = DELAYED_PIC_REF;
1173
1174 /* Frame reordering. This code takes pictures from coding order and sorts
1175 * them by their incremental POC value into display order. It supports POC
1176 * gaps, MMCO reset codes and random resets.
1177 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1178 * and/or can be closed down with a MMCO reset code. In sequences where
1179 * there is no delay, we can't detect that (since the frame was already
1180 * output to the user), so we also set h->mmco_reset to detect the MMCO
1181 * reset code.
1182 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1183 * we increase the delay between input and output. All frames affected by
1184 * the lag (e.g. those that should have been output before another frame
1185 * that we already returned to the user) will be dropped. This is a bug
1186 * that we will fix later. */
1187 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1188 cnt += out->poc < h->last_pocs[i];
1189 invalid += out->poc == INT_MIN;
1190 }
1191 if (!h->mmco_reset && !cur->f->key_frame &&
1192 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1193 h->mmco_reset = 2;
1194 if (pics > 1)
1195 h->delayed_pic[pics - 2]->mmco_reset = 2;
1196 }
1197 if (h->mmco_reset || cur->f->key_frame) {
1198 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1199 h->last_pocs[i] = INT_MIN;
1200 cnt = 0;
1201 invalid = MAX_DELAYED_PIC_COUNT;
1202 }
1203 out = h->delayed_pic[0];
1204 out_idx = 0;
1205 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1206 h->delayed_pic[i] &&
1207 !h->delayed_pic[i - 1]->mmco_reset &&
1208 !h->delayed_pic[i]->f->key_frame;
1209 i++)
1210 if (h->delayed_pic[i]->poc < out->poc) {
1211 out = h->delayed_pic[i];
1212 out_idx = i;
1213 }
1214 if (h->avctx->has_b_frames == 0 &&
1215 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
1216 h->next_outputed_poc = INT_MIN;
1217 out_of_order = !out->f->key_frame && !h->mmco_reset &&
1218 (out->poc < h->next_outputed_poc);
1219
1220 if (sps->bitstream_restriction_flag &&
1221 h->avctx->has_b_frames >= sps->num_reorder_frames) {
1222 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1223 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1224 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1225 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1226 }
1227 } else if (!h->avctx->has_b_frames &&
1228 ((h->next_outputed_poc != INT_MIN &&
1229 out->poc > h->next_outputed_poc + 2) ||
1230 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
1231 h->avctx->has_b_frames++;
1232 }
1233
1234 if (pics > h->avctx->has_b_frames) {
1235 out->reference &= ~DELAYED_PIC_REF;
1236 for (i = out_idx; h->delayed_pic[i]; i++)
1237 h->delayed_pic[i] = h->delayed_pic[i + 1];
1238 }
1239 memmove(h->last_pocs, &h->last_pocs[1],
1240 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1241 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1242 if (!out_of_order && pics > h->avctx->has_b_frames) {
1243 av_frame_unref(h->output_frame);
1244 ret = av_frame_ref(h->output_frame, out->f);
1245 if (ret < 0)
1246 return ret;
1247
1248 if (out->recovered) {
1249 // We have reached an recovery point and all frames after it in
1250 // display order are "recovered".
1251 h->frame_recovered |= FRAME_RECOVERED_SEI;
1252 }
1253 out->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1254
1255 if (!out->recovered) {
1256 if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT))
1257 av_frame_unref(h->output_frame);
1258 else
1259 h->output_frame->flags |= AV_FRAME_FLAG_CORRUPT;
1260 }
1261
1262 if (out->mmco_reset) {
1263 if (out_idx > 0) {
1264 h->next_outputed_poc = out->poc;
1265 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1266 } else {
1267 h->next_outputed_poc = INT_MIN;
1268 }
1269 } else {
1270 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
1271 h->next_outputed_poc = INT_MIN;
1272 } else {
1273 h->next_outputed_poc = out->poc;
1274 }
1275 }
1276 h->mmco_reset = 0;
1277 } else {
1278 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
1279 }
1280
1281 return 0;
1282 }
1283
1284 /* This function is called right after decoding the slice header for a first
1285 * slice in a field (or a frame). It decides whether we are decoding a new frame
1286 * or a second field in a pair and does the necessary setup.
1287 */
1288 static int h264_field_start(H264Context *h, const H264SliceContext *sl,
1289 const H2645NAL *nal)
1290 {
1291 const SPS *sps;
1292
1293 int last_pic_structure, last_pic_droppable, ret;
1294
1295 ret = h264_init_ps(h, sl);
1296 if (ret < 0)
1297 return ret;
1298
1299 sps = h->ps.sps;
1300
1301 last_pic_droppable = h->droppable;
1302 last_pic_structure = h->picture_structure;
1303 h->droppable = (nal->ref_idc == 0);
1304 h->picture_structure = sl->picture_structure;
1305
1306 h->poc.frame_num = sl->frame_num;
1307 h->poc.poc_lsb = sl->poc_lsb;
1308 h->poc.delta_poc_bottom = sl->delta_poc_bottom;
1309 h->poc.delta_poc[0] = sl->delta_poc[0];
1310 h->poc.delta_poc[1] = sl->delta_poc[1];
1311
1312 /* Shorten frame num gaps so we don't have to allocate reference
1313 * frames just to throw them away */
1314 if (h->poc.frame_num != h->poc.prev_frame_num) {
1315 int unwrap_prev_frame_num = h->poc.prev_frame_num;
1316 int max_frame_num = 1 << sps->log2_max_frame_num;
1317
1318 if (unwrap_prev_frame_num > h->poc.frame_num)
1319 unwrap_prev_frame_num -= max_frame_num;
1320
1321 if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1322 unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1323 if (unwrap_prev_frame_num < 0)
1324 unwrap_prev_frame_num += max_frame_num;
1325
1326 h->poc.prev_frame_num = unwrap_prev_frame_num;
1327 }
1328 }
1329
1330 /* See if we have a decoded first field looking for a pair...
1331 * Here, we're using that to see if we should mark previously
1332 * decode frames as "finished".
1333 * We have to do that before the "dummy" in-between frame allocation,
1334 * since that can modify s->current_picture_ptr. */
1335 if (h->first_field) {
1336 assert(h->cur_pic_ptr);
1337 assert(h->cur_pic_ptr->f->buf[0]);
1338 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1339
1340 /* figure out if we have a complementary field pair */
1341 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1342 /* Previous field is unmatched. Don't display it, but let it
1343 * remain for reference if marked as such. */
1344 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1345 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1346 last_pic_structure == PICT_TOP_FIELD);
1347 }
1348 } else {
1349 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1350 /* This and previous field were reference, but had
1351 * different frame_nums. Consider this field first in
1352 * pair. Throw away previous field except for reference
1353 * purposes. */
1354 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1355 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1356 last_pic_structure == PICT_TOP_FIELD);
1357 }
1358 } else {
1359 /* Second field in complementary pair */
1360 if (!((last_pic_structure == PICT_TOP_FIELD &&
1361 h->picture_structure == PICT_BOTTOM_FIELD) ||
1362 (last_pic_structure == PICT_BOTTOM_FIELD &&
1363 h->picture_structure == PICT_TOP_FIELD))) {
1364 av_log(h->avctx, AV_LOG_ERROR,
1365 "Invalid field mode combination %d/%d\n",
1366 last_pic_structure, h->picture_structure);
1367 h->picture_structure = last_pic_structure;
1368 h->droppable = last_pic_droppable;
1369 return AVERROR_INVALIDDATA;
1370 } else if (last_pic_droppable != h->droppable) {
1371 avpriv_request_sample(h->avctx,
1372 "Found reference and non-reference fields in the same frame, which");
1373 h->picture_structure = last_pic_structure;
1374 h->droppable = last_pic_droppable;
1375 return AVERROR_PATCHWELCOME;
1376 }
1377 }
1378 }
1379 }
1380
1381 while (h->poc.frame_num != h->poc.prev_frame_num &&
1382 h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1383 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1384 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1385 h->poc.frame_num, h->poc.prev_frame_num);
1386 ret = initialize_cur_frame(h);
1387 if (ret < 0) {
1388 h->first_field = 0;
1389 return ret;
1390 }
1391
1392 h->poc.prev_frame_num++;
1393 h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
1394 h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1395 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1396 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1397
1398 h->explicit_ref_marking = 0;
1399 ret = ff_h264_execute_ref_pic_marking(h);
1400 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1401 return ret;
1402 /* Error concealment: If a ref is missing, copy the previous ref
1403 * in its place.
1404 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1405 * many assumptions about there being no actual duplicates.
1406 * FIXME: This does not copy padding for out-of-frame motion
1407 * vectors. Given we are concealing a lost frame, this probably
1408 * is not noticeable by comparison, but it should be fixed. */
1409 if (h->short_ref_count) {
1410 if (prev &&
1411 h->short_ref[0]->f->width == prev->f->width &&
1412 h->short_ref[0]->f->height == prev->f->height &&
1413 h->short_ref[0]->f->format == prev->f->format) {
1414 ff_thread_await_progress(&prev->tf, INT_MAX, 0);
1415 if (prev->field_picture)
1416 ff_thread_await_progress(&prev->tf, INT_MAX, 1);
1417 av_image_copy(h->short_ref[0]->f->data,
1418 h->short_ref[0]->f->linesize,
1419 (const uint8_t **)prev->f->data,
1420 prev->f->linesize,
1421 prev->f->format,
1422 h->mb_width * 16,
1423 h->mb_height * 16);
1424 h->short_ref[0]->poc = prev->poc + 2;
1425 }
1426 h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1427 }
1428 }
1429
1430 /* See if we have a decoded first field looking for a pair...
1431 * We're using that to see whether to continue decoding in that
1432 * frame, or to allocate a new one. */
1433 if (h->first_field) {
1434 assert(h->cur_pic_ptr);
1435 assert(h->cur_pic_ptr->f->buf[0]);
1436 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1437
1438 /* figure out if we have a complementary field pair */
1439 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1440 /* Previous field is unmatched. Don't display it, but let it
1441 * remain for reference if marked as such. */
1442 h->cur_pic_ptr = NULL;
1443 h->first_field = FIELD_PICTURE(h);
1444 } else {
1445 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1446 /* This and the previous field had different frame_nums.
1447 * Consider this field first in pair. Throw away previous
1448 * one except for reference purposes. */
1449 h->first_field = 1;
1450 h->cur_pic_ptr = NULL;
1451 } else {
1452 /* Second field in complementary pair */
1453 h->first_field = 0;
1454 }
1455 }
1456 } else {
1457 /* Frame or first field in a potentially complementary pair */
1458 h->first_field = FIELD_PICTURE(h);
1459 }
1460
1461 if (!FIELD_PICTURE(h) || h->first_field) {
1462 if (h264_frame_start(h) < 0) {
1463 h->first_field = 0;
1464 return AVERROR_INVALIDDATA;
1465 }
1466 } else {
1467 release_unused_pictures(h, 0);
1468 }
1469
1470 ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1471 h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
1472
1473 memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
1474 h->nb_mmco = sl->nb_mmco;
1475 h->explicit_ref_marking = sl->explicit_ref_marking;
1476
1477 h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
1478
1479 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1480 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
1481 ((1 << h->ps.sps->log2_max_frame_num) - 1);
1482 }
1483
1484 h->cur_pic_ptr->f->key_frame |= (nal->type == H264_NAL_IDR_SLICE) ||
1485 (h->sei.recovery_point.recovery_frame_cnt >= 0);
1486
1487 if (nal->type == H264_NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
1488 h->recovery_frame = -1;
1489 h->cur_pic_ptr->recovered = 1;
1490 }
1491 // If we have an IDR, all frames after it in decoded order are
1492 // "recovered".
1493 if (nal->type == H264_NAL_IDR_SLICE)
1494 h->frame_recovered |= FRAME_RECOVERED_IDR;
1495 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1496
1497 /* Set the frame properties/side data. Only done for the second field in
1498 * field coded frames, since some SEI information is present for each field
1499 * and is merged by the SEI parsing code. */
1500 if (!FIELD_PICTURE(h) || !h->first_field) {
1501 ret = h264_export_frame_props(h);
1502 if (ret < 0)
1503 return ret;
1504
1505 ret = h264_select_output_frame(h);
1506 if (ret < 0)
1507 return ret;
1508 }
1509
1510 if (h->avctx->hwaccel) {
1511 ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0);
1512 if (ret < 0)
1513 return ret;
1514 }
1515
1516 return 0;
1517 }
1518
1519 static int h264_slice_header_parse(H264SliceContext *sl, const H2645NAL *nal,
1520 const H264ParamSets *ps, AVCodecContext *avctx)
1521 {
1522 const SPS *sps;
1523 const PPS *pps;
1524 int ret;
1525 unsigned int slice_type, tmp, i;
1526 int field_pic_flag, bottom_field_flag, picture_structure;
1527
1528 sl->first_mb_addr = get_ue_golomb(&sl->gb);
1529
1530 slice_type = get_ue_golomb_31(&sl->gb);
1531 if (slice_type > 9) {
1532 av_log(avctx, AV_LOG_ERROR,
1533 "slice type %d too large at %d\n",
1534 slice_type, sl->first_mb_addr);
1535 return AVERROR_INVALIDDATA;
1536 }
1537 if (slice_type > 4) {
1538 slice_type -= 5;
1539 sl->slice_type_fixed = 1;
1540 } else
1541 sl->slice_type_fixed = 0;
1542
1543 slice_type = ff_h264_golomb_to_pict_type[slice_type];
1544 sl->slice_type = slice_type;
1545 sl->slice_type_nos = slice_type & 3;
1546
1547 if (nal->type == H264_NAL_IDR_SLICE &&
1548 sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1549 av_log(avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1550 return AVERROR_INVALIDDATA;
1551 }
1552
1553 sl->pps_id = get_ue_golomb(&sl->gb);
1554 if (sl->pps_id >= MAX_PPS_COUNT) {
1555 av_log(avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
1556 return AVERROR_INVALIDDATA;
1557 }
1558 if (!ps->pps_list[sl->pps_id]) {
1559 av_log(avctx, AV_LOG_ERROR,
1560 "non-existing PPS %u referenced\n",
1561 sl->pps_id);
1562 return AVERROR_INVALIDDATA;
1563 }
1564 pps = (const PPS*)ps->pps_list[sl->pps_id]->data;
1565
1566 if (!ps->sps_list[pps->sps_id]) {
1567 av_log(avctx, AV_LOG_ERROR,
1568 "non-existing SPS %u referenced\n", pps->sps_id);
1569 return AVERROR_INVALIDDATA;
1570 }
1571 sps = (const SPS*)ps->sps_list[pps->sps_id]->data;
1572
1573 sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1574
1575 sl->mb_mbaff = 0;
1576
1577 if (sps->frame_mbs_only_flag) {
1578 picture_structure = PICT_FRAME;
1579 } else {
1580 field_pic_flag = get_bits1(&sl->gb);
1581 if (field_pic_flag) {
1582 bottom_field_flag = get_bits1(&sl->gb);
1583 picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1584 } else {
1585 picture_structure = PICT_FRAME;
1586 }
1587 }
1588 sl->picture_structure = picture_structure;
1589 sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
1590
1591 if (picture_structure == PICT_FRAME) {
1592 sl->curr_pic_num = sl->frame_num;
1593 sl->max_pic_num = 1 << sps->log2_max_frame_num;
1594 } else {
1595 sl->curr_pic_num = 2 * sl->frame_num + 1;
1596 sl->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
1597 }
1598
1599 if (nal->type == H264_NAL_IDR_SLICE)
1600 get_ue_golomb(&sl->gb); /* idr_pic_id */
1601
1602 if (sps->poc_type == 0) {
1603 sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1604
1605 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1606 sl->delta_poc_bottom = get_se_golomb(&sl->gb);
1607 }
1608
1609 if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1610 sl->delta_poc[0] = get_se_golomb(&sl->gb);
1611
1612 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1613 sl->delta_poc[1] = get_se_golomb(&sl->gb);
1614 }
1615
1616 sl->redundant_pic_count = 0;
1617 if (pps->redundant_pic_cnt_present)
1618 sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1619
1620 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1621 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1622
1623 ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1624 &sl->gb, pps, sl->slice_type_nos,
1625 picture_structure);
1626 if (ret < 0)
1627 return ret;
1628
1629 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1630 ret = ff_h264_decode_ref_pic_list_reordering(sl, avctx);
1631 if (ret < 0) {
1632 sl->ref_count[1] = sl->ref_count[0] = 0;
1633 return ret;
1634 }
1635 }
1636
1637 sl->pwt.use_weight = 0;
1638 for (i = 0; i < 2; i++) {
1639 sl->pwt.luma_weight_flag[i] = 0;
1640 sl->pwt.chroma_weight_flag[i] = 0;
1641 }
1642 if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1643 (pps->weighted_bipred_idc == 1 &&
1644 sl->slice_type_nos == AV_PICTURE_TYPE_B))
1645 ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1646 sl->slice_type_nos, &sl->pwt);
1647
1648 sl->explicit_ref_marking = 0;
1649 if (nal->ref_idc) {
1650 ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, avctx);
1651 if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
1652 return AVERROR_INVALIDDATA;
1653 }
1654
1655 if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1656 tmp = get_ue_golomb_31(&sl->gb);
1657 if (tmp > 2) {
1658 av_log(avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1659 return AVERROR_INVALIDDATA;
1660 }
1661 sl->cabac_init_idc = tmp;
1662 }
1663
1664 sl->last_qscale_diff = 0;
1665 tmp = pps->init_qp + get_se_golomb(&sl->gb);
1666 if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1667 av_log(avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1668 return AVERROR_INVALIDDATA;
1669 }
1670 sl->qscale = tmp;
1671 sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
1672 sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
1673 // FIXME qscale / qp ... stuff
1674 if (sl->slice_type == AV_PICTURE_TYPE_SP)
1675 get_bits1(&sl->gb); /* sp_for_switch_flag */
1676 if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1677 sl->slice_type == AV_PICTURE_TYPE_SI)
1678 get_se_golomb(&sl->gb); /* slice_qs_delta */
1679
1680 sl->deblocking_filter = 1;
1681 sl->slice_alpha_c0_offset = 0;
1682 sl->slice_beta_offset = 0;
1683 if (pps->deblocking_filter_parameters_present) {
1684 tmp = get_ue_golomb_31(&sl->gb);
1685 if (tmp > 2) {
1686 av_log(avctx, AV_LOG_ERROR,
1687 "deblocking_filter_idc %u out of range\n", tmp);
1688 return AVERROR_INVALIDDATA;
1689 }
1690 sl->deblocking_filter = tmp;
1691 if (sl->deblocking_filter < 2)
1692 sl->deblocking_filter ^= 1; // 1<->0
1693
1694 if (sl->deblocking_filter) {
1695 sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1696 sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2;
1697 if (sl->slice_alpha_c0_offset > 12 ||
1698 sl->slice_alpha_c0_offset < -12 ||
1699 sl->slice_beta_offset > 12 ||
1700 sl->slice_beta_offset < -12) {
1701 av_log(avctx, AV_LOG_ERROR,
1702 "deblocking filter parameters %d %d out of range\n",
1703 sl->slice_alpha_c0_offset, sl->slice_beta_offset);
1704 return AVERROR_INVALIDDATA;
1705 }
1706 }
1707 }
1708
1709 return 0;
1710 }
1711
1712 /* do all the per-slice initialization needed before we can start decoding the
1713 * actual MBs */
1714 static int h264_slice_init(H264Context *h, H264SliceContext *sl,
1715 const H2645NAL *nal)
1716 {
1717 int i, j, ret = 0;
1718
1719 if (h->current_slice > 0) {
1720 if (h->ps.pps != (const PPS*)h->ps.pps_list[sl->pps_id]->data) {
1721 av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
1722 return AVERROR_INVALIDDATA;
1723 }
1724
1725 if (h->picture_structure != sl->picture_structure ||
1726 h->droppable != (nal->ref_idc == 0)) {
1727 av_log(h->avctx, AV_LOG_ERROR,
1728 "Changing field mode (%d -> %d) between slices is not allowed\n",
1729 h->picture_structure, sl->picture_structure);
1730 return AVERROR_INVALIDDATA;
1731 } else if (!h->cur_pic_ptr) {
1732 av_log(h->avctx, AV_LOG_ERROR,
1733 "unset cur_pic_ptr on slice %d\n",
1734 h->current_slice + 1);
1735 return AVERROR_INVALIDDATA;
1736 }
1737 }
1738
1739 if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
1740 av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
1741 return AVERROR_INVALIDDATA;
1742 }
1743
1744 assert(h->mb_num == h->mb_width * h->mb_height);
1745 if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1746 sl->first_mb_addr >= h->mb_num) {
1747 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1748 return AVERROR_INVALIDDATA;
1749 }
1750 sl->resync_mb_x = sl->mb_x = sl->first_mb_addr % h->mb_width;
1751 sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
1752 FIELD_OR_MBAFF_PICTURE(h);
1753 if (h->picture_structure == PICT_BOTTOM_FIELD)
1754 sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1755 assert(sl->mb_y < h->mb_height);
1756
1757 ret = ff_h264_build_ref_list(h, sl);
1758 if (ret < 0)
1759 return ret;
1760
1761 if (h->ps.pps->weighted_bipred_idc == 2 &&
1762 sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1763 implicit_weight_table(h, sl, -1);
1764 if (FRAME_MBAFF(h)) {
1765 implicit_weight_table(h, sl, 0);
1766 implicit_weight_table(h, sl, 1);
1767 }
1768 }
1769
1770 if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1771 ff_h264_direct_dist_scale_factor(h, sl);
1772 ff_h264_direct_ref_list_init(h, sl);
1773
1774 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1775 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1776 sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1777 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
1778 sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1779 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1780 nal->ref_idc == 0))
1781 sl->deblocking_filter = 0;
1782
1783 if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
1784 if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1785 /* Cheat slightly for speed:
1786 * Do not bother to deblock across slices. */
1787 sl->deblocking_filter = 2;
1788 } else {
1789 h->postpone_filter = 1;
1790 }
1791 }
1792 sl->qp_thresh = 15 -
1793 FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1794 FFMAX3(0,
1795 h->ps.pps->chroma_qp_index_offset[0],
1796 h->ps.pps->chroma_qp_index_offset[1]) +
1797 6 * (h->ps.sps->bit_depth_luma - 8);
1798
1799 sl->slice_num = ++h->current_slice;
1800 if (sl->slice_num >= MAX_SLICES) {
1801 av_log(h->avctx, AV_LOG_ERROR,
1802 "Too many slices, increase MAX_SLICES and recompile\n");
1803 }
1804
1805 for (j = 0; j < 2; j++) {
1806 int id_list[16];
1807 int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
1808 for (i = 0; i < 16; i++) {
1809 id_list[i] = 60;
1810 if (j < sl->list_count && i < sl->ref_count[j] &&
1811 sl->ref_list[j][i].parent->f->buf[0]) {
1812 int k;
1813 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
1814 for (k = 0; k < h->short_ref_count; k++)
1815 if (h->short_ref[k]->f->buf[0]->buffer == buf) {
1816 id_list[i] = k;
1817 break;
1818 }
1819 for (k = 0; k < h->long_ref_count; k++)
1820 if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
1821 id_list[i] = h->short_ref_count + k;
1822 break;
1823 }
1824 }
1825 }
1826
1827 ref2frm[0] =
1828 ref2frm[1] = -1;
1829 for (i = 0; i < 16; i++)
1830 ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
1831 ref2frm[18 + 0] =
1832 ref2frm[18 + 1] = -1;
1833 for (i = 16; i < 48; i++)
1834 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
1835 (sl->ref_list[j][i].reference & 3);
1836 }
1837
1838 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1839 av_log(h->avctx, AV_LOG_DEBUG,
1840 "slice:%d %s mb:%d %c%s%s frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
1841 sl->slice_num,
1842 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1843 sl->mb_y * h->mb_width + sl->mb_x,
1844 av_get_picture_type_char(sl->slice_type),
1845 sl->slice_type_fixed ? " fix" : "",
1846 nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
1847 h->poc.frame_num,
1848 h->cur_pic_ptr->field_poc[0],
1849 h->cur_pic_ptr->field_poc[1],
1850 sl->ref_count[0], sl->ref_count[1],
1851 sl->qscale,
1852 sl->deblocking_filter,
1853 sl->slice_alpha_c0_offset, sl->slice_beta_offset,
1854 sl->pwt.use_weight,
1855 sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
1856 sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
1857 }
1858
1859 return 0;
1860 }
1861
1862 int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
1863 {
1864 H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
1865 int ret;
1866
1867 sl->gb = nal->gb;
1868
1869 ret = h264_slice_header_parse(sl, nal, &h->ps, h->avctx);
1870 if (ret < 0)
1871 return ret;
1872
1873 // discard redundant pictures
1874 if (sl->redundant_pic_count > 0)
1875 return 0;
1876
1877 if (!h->setup_finished) {
1878 if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
1879 // this slice starts a new field
1880 // first decode any pending queued slices
1881 if (h->nb_slice_ctx_queued) {
1882 H264SliceContext tmp_ctx;
1883
1884 ret = ff_h264_execute_decode_slices(h);
1885 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1886 return ret;
1887
1888 memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
1889 memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
1890 memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
1891 sl = h->slice_ctx;
1892 }
1893
1894 if (h->field_started)
1895 ff_h264_field_end(h, sl, 1);
1896
1897 h->current_slice = 0;
1898 if (!h->first_field) {
1899 if (h->cur_pic_ptr && !h->droppable) {
1900 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1901 h->picture_structure == PICT_BOTTOM_FIELD);
1902 }
1903 h->cur_pic_ptr = NULL;
1904 }
1905 }
1906
1907 if (h->current_slice == 0) {
1908 ret = h264_field_start(h, sl, nal);
1909 if (ret < 0)
1910 return ret;
1911 h->field_started = 1;
1912 }
1913 }
1914
1915 ret = h264_slice_init(h, sl, nal);
1916 if (ret < 0)
1917 return ret;
1918
1919 if ((h->avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1920 (h->avctx->skip_frame < AVDISCARD_BIDIR ||
1921 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1922 (h->avctx->skip_frame < AVDISCARD_NONKEY ||
1923 h->cur_pic_ptr->f->key_frame) &&
1924 h->avctx->skip_frame < AVDISCARD_ALL) {
1925 h->nb_slice_ctx_queued++;
1926 }
1927
1928 return 0;
1929 }
1930
1931 int ff_h264_get_slice_type(const H264SliceContext *sl)
1932 {
1933 switch (sl->slice_type) {
1934 case AV_PICTURE_TYPE_P:
1935 return 0;
1936 case AV_PICTURE_TYPE_B:
1937 return 1;
1938 case AV_PICTURE_TYPE_I:
1939 return 2;
1940 case AV_PICTURE_TYPE_SP:
1941 return 3;
1942 case AV_PICTURE_TYPE_SI:
1943 return 4;
1944 default:
1945 return AVERROR_INVALIDDATA;
1946 }
1947 }
1948
1949 static av_always_inline void fill_filter_caches_inter(const H264Context *h,
1950 H264SliceContext *sl,
1951 int mb_type, int top_xy,
1952 int left_xy[LEFT_MBS],
1953 int top_type,
1954 int left_type[LEFT_MBS],
1955 int mb_xy, int list)
1956 {
1957 int b_stride = h->b_stride;
1958 int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1959 int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
1960 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1961 if (USES_LIST(top_type, list)) {
1962 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
1963 const int b8_xy = 4 * top_xy + 2;
1964 const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1965 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1966 ref_cache[0 - 1 * 8] =
1967 ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
1968 ref_cache[2 - 1 * 8] =
1969 ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
1970 } else {
1971 AV_ZERO128(mv_dst - 1 * 8);
1972 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1973 }
1974
1975 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1976 if (USES_LIST(left_type[LTOP], list)) {
1977 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
1978 const int b8_xy = 4 * left_xy[LTOP] + 1;
1979 const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1980 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1981 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1982 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1983 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1984 ref_cache[-1 + 0] =
1985 ref_cache[-1 + 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1986 ref_cache[-1 + 16] =
1987 ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1988 } else {
1989 AV_ZERO32(mv_dst - 1 + 0);
1990 AV_ZERO32(mv_dst - 1 + 8);
1991 AV_ZERO32(mv_dst - 1 + 16);
1992 AV_ZERO32(mv_dst - 1 + 24);
1993 ref_cache[-1 + 0] =
1994 ref_cache[-1 + 8] =
1995 ref_cache[-1 + 16] =
1996 ref_cache[-1 + 24] = LIST_NOT_USED;
1997 }
1998 }
1999 }
2000
2001 if (!USES_LIST(mb_type, list)) {
2002 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
2003 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2004 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2005 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2006 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2007 return;
2008 }
2009
2010 {
2011 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
2012 const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
2013 uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
2014 uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
2015 AV_WN32A(&ref_cache[0 * 8], ref01);
2016 AV_WN32A(&ref_cache[1 * 8], ref01);
2017 AV_WN32A(&ref_cache[2 * 8], ref23);
2018 AV_WN32A(&ref_cache[3 * 8], ref23);
2019 }
2020
2021 {
2022 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
2023 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
2024 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
2025 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
2026 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
2027 }
2028 }
2029
2030 /**
2031 * @return non zero if the loop filter can be skipped
2032 */
2033 static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
2034 {
2035 const int mb_xy = sl->mb_xy;
2036 int top_xy, left_xy[LEFT_MBS];
2037 int top_type, left_type[LEFT_MBS];
2038 uint8_t *nnz;
2039 uint8_t *nnz_cache;
2040
2041 top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
2042
2043 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
2044 if (FRAME_MBAFF(h)) {
2045 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
2046 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
2047 if (sl->mb_y & 1) {
2048 if (left_mb_field_flag != curr_mb_field_flag)
2049 left_xy[LTOP] -= h->mb_stride;
2050 } else {
2051 if (curr_mb_field_flag)
2052 top_xy += h->mb_stride &
2053 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
2054 if (left_mb_field_flag != curr_mb_field_flag)
2055 left_xy[LBOT] += h->mb_stride;
2056 }
2057 }
2058
2059 sl->top_mb_xy = top_xy;
2060 sl->left_mb_xy[LTOP] = left_xy[LTOP];
2061 sl->left_mb_xy[LBOT] = left_xy[LBOT];
2062 {
2063 /* For sufficiently low qp, filtering wouldn't do anything.
2064 * This is a conservative estimate: could also check beta_offset
2065 * and more accurate chroma_qp. */
2066 int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
2067 int qp = h->cur_pic.qscale_table[mb_xy];
2068 if (qp <= qp_thresh &&
2069 (left_xy[LTOP] < 0 ||
2070 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
2071 (top_xy < 0 ||
2072 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
2073 if (!FRAME_MBAFF(h))
2074 return 1;
2075 if ((left_xy[LTOP] < 0 ||
2076 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
2077 (top_xy < h->mb_stride ||
2078 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
2079 return 1;
2080 }
2081 }
2082
2083 top_type = h->cur_pic.mb_type[top_xy];
2084 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
2085 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
2086 if (sl->deblocking_filter == 2) {
2087 if (h->slice_table[top_xy] != sl->slice_num)
2088 top_type = 0;
2089 if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
2090 left_type[LTOP] = left_type[LBOT] = 0;
2091 } else {
2092 if (h->slice_table[top_xy] == 0xFFFF)
2093 top_type = 0;
2094 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
2095 left_type[LTOP] = left_type[LBOT] = 0;
2096 }
2097 sl->top_type = top_type;
2098 sl->left_type[LTOP] = left_type[LTOP];
2099 sl->left_type[LBOT] = left_type[LBOT];
2100
2101 if (IS_INTRA(mb_type))
2102 return 0;
2103
2104 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2105 top_type, left_type, mb_xy, 0);
2106 if (sl->list_count == 2)
2107 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2108 top_type, left_type, mb_xy, 1);
2109
2110 nnz = h->non_zero_count[mb_xy];
2111 nnz_cache = sl->non_zero_count_cache;
2112 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
2113 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
2114 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
2115 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
2116 sl->cbp = h->cbp_table[mb_xy];
2117
2118 if (top_type) {
2119 nnz = h->non_zero_count[top_xy];
2120 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
2121 }
2122
2123 if (left_type[LTOP]) {
2124 nnz = h->non_zero_count[left_xy[LTOP]];
2125 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
2126 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
2127 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
2128 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
2129 }
2130
2131 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
2132 * from what the loop filter needs */
2133 if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
2134 if (IS_8x8DCT(top_type)) {
2135 nnz_cache[4 + 8 * 0] =
2136 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
2137 nnz_cache[6 + 8 * 0] =
2138 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
2139 }
2140 if (IS_8x8DCT(left_type[LTOP])) {
2141 nnz_cache[3 + 8 * 1] =
2142 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
2143 }
2144 if (IS_8x8DCT(left_type[LBOT])) {
2145 nnz_cache[3 + 8 * 3] =
2146 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
2147 }
2148
2149 if (IS_8x8DCT(mb_type)) {
2150 nnz_cache[scan8[0]] =
2151 nnz_cache[scan8[1]] =
2152 nnz_cache[scan8[2]] =
2153 nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
2154
2155 nnz_cache[scan8[0 + 4]] =
2156 nnz_cache[scan8[1 + 4]] =
2157 nnz_cache[scan8[2 + 4]] =
2158 nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
2159
2160 nnz_cache[scan8[0 + 8]] =
2161 nnz_cache[scan8[1 + 8]] =
2162 nnz_cache[scan8[2 + 8]] =
2163 nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
2164
2165 nnz_cache[scan8[0 + 12]] =
2166 nnz_cache[scan8[1 + 12]] =
2167 nnz_cache[scan8[2 + 12]] =
2168 nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
2169 }
2170 }
2171
2172 return 0;
2173 }
2174
2175 static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
2176 {
2177 uint8_t *dest_y, *dest_cb, *dest_cr;
2178 int linesize, uvlinesize, mb_x, mb_y;
2179 const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
2180 const int old_slice_type = sl->slice_type;
2181 const int pixel_shift = h->pixel_shift;
2182 const int block_h = 16 >> h->chroma_y_shift;
2183
2184 if (h->postpone_filter)
2185 return;
2186
2187 if (sl->deblocking_filter) {
2188 for (mb_x = start_x; mb_x < end_x; mb_x++)
2189 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
2190 int mb_xy, mb_type;
2191 mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
2192 mb_type = h->cur_pic.mb_type[mb_xy];
2193
2194 if (FRAME_MBAFF(h))
2195 sl->mb_mbaff =
2196 sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2197
2198 sl->mb_x = mb_x;
2199 sl->mb_y = mb_y;
2200 dest_y = h->cur_pic.f->data[0] +
2201 ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
2202 dest_cb = h->cur_pic.f->data[1] +
2203 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2204 mb_y * sl->uvlinesize * block_h;
2205 dest_cr = h->cur_pic.f->data[2] +
2206 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2207 mb_y * sl->uvlinesize * block_h;
2208 // FIXME simplify above
2209
2210 if (MB_FIELD(sl)) {
2211 linesize = sl->mb_linesize = sl->linesize * 2;
2212 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
2213 if (mb_y & 1) { // FIXME move out of this function?
2214 dest_y -= sl->linesize * 15;
2215 dest_cb -= sl->uvlinesize * (block_h - 1);
2216 dest_cr -= sl->uvlinesize * (block_h - 1);
2217 }
2218 } else {
2219 linesize = sl->mb_linesize = sl->linesize;
2220 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
2221 }
2222 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
2223 uvlinesize, 0);
2224 if (fill_filter_caches(h, sl, mb_type))
2225 continue;
2226 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
2227 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
2228
2229 if (FRAME_MBAFF(h)) {
2230 ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
2231 linesize, uvlinesize);
2232 } else {
2233 ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
2234 dest_cr, linesize, uvlinesize);
2235 }
2236 }
2237 }
2238 sl->slice_type = old_slice_type;
2239 sl->mb_x = end_x;
2240 sl->mb_y = end_mb_y - FRAME_MBAFF(h);
2241 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
2242 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
2243 }
2244
2245 static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
2246 {
2247 const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
2248 int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
2249 h->cur_pic.mb_type[mb_xy - 1] :
2250 (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
2251 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
2252 sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2253 }
2254
2255 /**
2256 * Draw edges and report progress for the last MB row.
2257 */
2258 static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
2259 {
2260 int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
2261 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
2262 int height = 16 << FRAME_MBAFF(h);
2263 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
2264
2265 if (sl->deblocking_filter) {
2266 if ((top + height) >= pic_height)
2267 height += deblock_border;
2268 top -= deblock_border;
2269 }
2270
2271 if (top >= pic_height || (top + height) < 0)
2272 return;
2273
2274 height = FFMIN(height, pic_height - top);
2275 if (top < 0) {
2276 height = top + height;
2277 top = 0;
2278 }
2279
2280 ff_h264_draw_horiz_band(h, sl, top, height);
2281
2282 if (h->droppable)
2283 return;
2284
2285 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
2286 h->picture_structure == PICT_BOTTOM_FIELD);
2287 }
2288
2289 static void er_add_slice(H264SliceContext *sl,
2290 int startx, int starty,
2291 int endx, int endy, int status)
2292 {
2293 #if CONFIG_ERROR_RESILIENCE
2294 ERContext *er = &sl->er;
2295
2296 if (!sl->h264->enable_er)
2297 return;
2298
2299 er->ref_count = sl->ref_count[0];
2300 ff_er_add_slice(er, startx, starty, endx, endy, status);
2301 #endif
2302 }
2303
2304 static int decode_slice(struct AVCodecContext *avctx, void *arg)
2305 {
2306 H264SliceContext *sl = arg;
2307 const H264Context *h = sl->h264;
2308 int lf_x_start = sl->mb_x;
2309 int orig_deblock = sl->deblocking_filter;
2310 int ret;
2311
2312 sl->linesize = h->cur_pic_ptr->f->linesize[0];
2313 sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
2314
2315 ret = alloc_scratch_buffers(sl, sl->linesize);
2316 if (ret < 0)
2317 return ret;
2318
2319 sl->mb_skip_run = -1;
2320
2321 if (h->postpone_filter)
2322 sl->deblocking_filter = 0;
2323
2324 sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
2325 (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
2326
2327 if (h->ps.pps->cabac) {
2328 /* realign */
2329 align_get_bits(&sl->gb);
2330
2331 /* init cabac */
2332 ff_init_cabac_decoder(&sl->cabac,
2333 sl->gb.buffer + get_bits_count(&sl->gb) / 8,
2334 (get_bits_left(&sl->gb) + 7) / 8);
2335
2336 ff_h264_init_cabac_states(h, sl);
2337
2338 for (;;) {
2339 // START_TIMER
2340 int ret, eos;
2341
2342 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2343 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2344 sl->next_slice_idx);
2345 return AVERROR_INVALIDDATA;
2346 }
2347
2348 ret = ff_h264_decode_mb_cabac(h, sl);
2349 // STOP_TIMER("decode_mb_cabac")
2350
2351 if (ret >= 0)
2352 ff_h264_hl_decode_mb(h, sl);
2353
2354 // FIXME optimal? or let mb_decode decode 16x32 ?
2355 if (ret >= 0 && FRAME_MBAFF(h)) {
2356 sl->mb_y++;
2357
2358 ret = ff_h264_decode_mb_cabac(h, sl);
2359
2360 if (ret >= 0)
2361 ff_h264_hl_decode_mb(h, sl);
2362 sl->mb_y--;
2363 }
2364 eos = get_cabac_terminate(&sl->cabac);
2365
2366 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
2367 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2368 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2369 sl->mb_y, ER_MB_END);
2370 if (sl->mb_x >= lf_x_start)
2371 loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
2372 goto finish;
2373 }
2374 if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2375 av_log(h->avctx, AV_LOG_ERROR,
2376 "error while decoding MB %d %d, bytestream %td\n",
2377 sl->mb_x, sl->mb_y,
2378 sl->cabac.bytestream_end - sl->cabac.bytestream);
2379 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2380 sl->mb_y, ER_MB_ERROR);
2381 return AVERROR_INVALIDDATA;
2382 }
2383
2384 if (++sl->mb_x >= h->mb_width) {
2385 loop_filter(h, sl, lf_x_start, sl->mb_x);
2386 sl->mb_x = lf_x_start = 0;
2387 decode_finish_row(h, sl);
2388 ++sl->mb_y;
2389 if (FIELD_OR_MBAFF_PICTURE(h)) {
2390 ++sl->mb_y;
2391 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2392 predict_field_decoding_flag(h, sl);
2393 }
2394 }
2395
2396 if (eos || sl->mb_y >= h->mb_height) {
2397 ff_tlog(h->avctx, "slice end %d %d\n",
2398 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2399 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2400 sl->mb_y, ER_MB_END);
2401 if (sl->mb_x > lf_x_start)
2402 loop_filter(h, sl, lf_x_start, sl->mb_x);
2403 goto finish;
2404 }
2405 }
2406 } else {
2407 for (;;) {
2408 int ret;
2409
2410 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2411 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2412 sl->next_slice_idx);
2413 return AVERROR_INVALIDDATA;
2414 }
2415
2416 ret = ff_h264_decode_mb_cavlc(h, sl);
2417
2418 if (ret >= 0)
2419 ff_h264_hl_decode_mb(h, sl);
2420
2421 // FIXME optimal? or let mb_decode decode 16x32 ?
2422 if (ret >= 0 && FRAME_MBAFF(h)) {
2423 sl->mb_y++;
2424 ret = ff_h264_decode_mb_cavlc(h, sl);
2425
2426 if (ret >= 0)
2427 ff_h264_hl_decode_mb(h, sl);
2428 sl->mb_y--;
2429 }
2430
2431 if (ret < 0) {
2432 av_log(h->avctx, AV_LOG_ERROR,
2433 "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2434 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2435 sl->mb_y, ER_MB_ERROR);
2436 return ret;
2437 }
2438
2439 if (++sl->mb_x >= h->mb_width) {
2440 loop_filter(h, sl, lf_x_start, sl->mb_x);
2441 sl->mb_x = lf_x_start = 0;
2442 decode_finish_row(h, sl);
2443 ++sl->mb_y;
2444 if (FIELD_OR_MBAFF_PICTURE(h)) {
2445 ++sl->mb_y;
2446 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2447 predict_field_decoding_flag(h, sl);
2448 }
2449 if (sl->mb_y >= h->mb_height) {
2450 ff_tlog(h->avctx, "slice end %d %d\n",
2451 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2452
2453 if (get_bits_left(&sl->gb) == 0) {
2454 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2455 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2456
2457 goto finish;
2458 } else {
2459 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2460 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2461
2462 return AVERROR_INVALIDDATA;
2463 }
2464 }
2465 }
2466
2467 if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2468 ff_tlog(h->avctx, "slice end %d %d\n",
2469 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2470
2471 if (get_bits_left(&sl->gb) == 0) {
2472 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2473 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2474 if (sl->mb_x > lf_x_start)
2475 loop_filter(h, sl, lf_x_start, sl->mb_x);
2476
2477 goto finish;
2478 } else {
2479 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2480 sl->mb_y, ER_MB_ERROR);
2481
2482 return AVERROR_INVALIDDATA;
2483 }
2484 }
2485 }
2486 }
2487
2488 finish:
2489 sl->deblocking_filter = orig_deblock;
2490 return 0;
2491 }
2492
2493 /**
2494 * Call decode_slice() for each context.
2495 *
2496 * @param h h264 master context
2497 */
2498 int ff_h264_execute_decode_slices(H264Context *h)
2499 {
2500 AVCodecContext *const avctx = h->avctx;
2501 H264SliceContext *sl;
2502 int context_count = h->nb_slice_ctx_queued;
2503 int ret = 0;
2504 int i, j;
2505
2506 if (h->avctx->hwaccel || context_count < 1)
2507 return 0;
2508 if (context_count == 1) {
2509
2510 h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2511 h->postpone_filter = 0;
2512
2513 ret = decode_slice(avctx, &h->slice_ctx[0]);
2514 h->mb_y = h->slice_ctx[0].mb_y;
2515 if (ret < 0)
2516 goto finish;
2517 } else {
2518 for (i = 0; i < context_count; i++) {
2519 int next_slice_idx = h->mb_width * h->mb_height;
2520 int slice_idx;
2521
2522 sl = &h->slice_ctx[i];
2523 sl->er.error_count = 0;
2524
2525 /* make sure none of those slices overlap */
2526 slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2527 for (j = 0; j < context_count; j++) {
2528 H264SliceContext *sl2 = &h->slice_ctx[j];
2529 int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2530
2531 if (i == j || slice_idx2 < slice_idx)
2532 continue;
2533 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2534 }
2535 sl->next_slice_idx = next_slice_idx;
2536 }
2537
2538 avctx->execute(avctx, decode_slice, h->slice_ctx,
2539 NULL, context_count, sizeof(h->slice_ctx[0]));
2540
2541 /* pull back stuff from slices to master context */
2542 sl = &h->slice_ctx[context_count - 1];
2543 h->mb_y = sl->mb_y;
2544 for (i = 1; i < context_count; i++)
2545 h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
2546
2547 if (h->postpone_filter) {
2548 h->postpone_filter = 0;
2549
2550 for (i = 0; i < context_count; i++) {
2551 int y_end, x_end;
2552
2553 sl = &h->slice_ctx[i];
2554 y_end = FFMIN(sl->mb_y + 1, h->mb_height);
2555 x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
2556
2557 for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
2558 sl->mb_y = j;
2559 loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
2560 j == y_end - 1 ? x_end : h->mb_width);
2561 }
2562 }
2563 }
2564 }
2565
2566 finish:
2567 h->nb_slice_ctx_queued = 0;
2568 return ret;
2569 }