2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of Libav.
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.
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.
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
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/imgutils.h"
31 #include "cabac_functions.h"
34 #include "mpegvideo.h"
37 #include "h264_mvpred.h"
40 #include "rectangle.h"
42 #include "vdpau_internal.h"
43 #include "libavutil/avassert.h"
48 static const uint8_t rem6[QP_MAX_NUM + 1] = {
49 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
50 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
51 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
54 static const uint8_t div6[QP_MAX_NUM + 1] = {
55 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
56 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
57 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
60 static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
69 * Check if the top & left blocks are available if needed and
70 * change the dc mode so it only uses the available blocks.
72 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
74 MpegEncContext *const s = &h->s;
75 static const int8_t top[12] = {
76 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
78 static const int8_t left[12] = {
79 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
83 if (!(h->top_samples_available & 0x8000)) {
84 for (i = 0; i < 4; i++) {
85 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
87 av_log(h->s.avctx, AV_LOG_ERROR,
88 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
89 status, s->mb_x, s->mb_y);
92 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
97 if ((h->left_samples_available & 0x8888) != 0x8888) {
98 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
99 for (i = 0; i < 4; i++)
100 if (!(h->left_samples_available & mask[i])) {
101 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
103 av_log(h->s.avctx, AV_LOG_ERROR,
104 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
105 status, s->mb_x, s->mb_y);
108 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
114 } // FIXME cleanup like ff_h264_check_intra_pred_mode
117 * Check if the top & left blocks are available if needed and
118 * change the dc mode so it only uses the available blocks.
120 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
122 MpegEncContext *const s = &h->s;
123 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
124 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
127 av_log(h->s.avctx, AV_LOG_ERROR,
128 "out of range intra chroma pred mode at %d %d\n",
133 if (!(h->top_samples_available & 0x8000)) {
136 av_log(h->s.avctx, AV_LOG_ERROR,
137 "top block unavailable for requested intra mode at %d %d\n",
143 if ((h->left_samples_available & 0x8080) != 0x8080) {
145 if (is_chroma && (h->left_samples_available & 0x8080)) {
146 // mad cow disease mode, aka MBAFF + constrained_intra_pred
147 mode = ALZHEIMER_DC_L0T_PRED8x8 +
148 (!(h->left_samples_available & 0x8000)) +
149 2 * (mode == DC_128_PRED8x8);
152 av_log(h->s.avctx, AV_LOG_ERROR,
153 "left block unavailable for requested intra mode at %d %d\n",
162 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
163 int *dst_length, int *consumed, int length)
169 // src[0]&0x80; // forbidden bit
170 h->nal_ref_idc = src[0] >> 5;
171 h->nal_unit_type = src[0] & 0x1F;
176 #if HAVE_FAST_UNALIGNED
179 for (i = 0; i + 1 < length; i += 9) {
180 if (!((~AV_RN64A(src + i) &
181 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
182 0x8000800080008080ULL))
185 for (i = 0; i + 1 < length; i += 5) {
186 if (!((~AV_RN32A(src + i) &
187 (AV_RN32A(src + i) - 0x01000101U)) &
191 if (i > 0 && !src[i])
197 for (i = 0; i + 1 < length; i += 2) {
200 if (i > 0 && src[i - 1] == 0)
203 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {
204 if (src[i + 2] != 3) {
205 /* startcode, so we must be past the end */
213 if (i >= length - 1) { // no escaped 0
214 *dst_length = length;
215 *consumed = length + 1; // +1 for the header
219 // use second escape buffer for inter data
220 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
221 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
222 length + FF_INPUT_BUFFER_PADDING_SIZE);
223 dst = h->rbsp_buffer[bufidx];
228 // printf("decoding esc\n");
231 while (si + 2 < length) {
232 // remove escapes (very rare 1:2^22)
233 if (src[si + 2] > 3) {
234 dst[di++] = src[si++];
235 dst[di++] = src[si++];
236 } else if (src[si] == 0 && src[si + 1] == 0) {
237 if (src[si + 2] == 3) { // escape
242 } else // next start code
246 dst[di++] = src[si++];
249 dst[di++] = src[si++];
252 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
255 *consumed = si + 1; // +1 for the header
256 /* FIXME store exact number of bits in the getbitcontext
257 * (it is needed for decoding) */
262 * Identify the exact end of the bitstream
263 * @return the length of the trailing, or 0 if damaged
265 static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src)
270 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
272 for (r = 1; r < 9; r++) {
280 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
281 int height, int y_offset, int list)
283 int raw_my = h->mv_cache[list][scan8[n]][1];
284 int filter_height = (raw_my & 3) ? 2 : 0;
285 int full_my = (raw_my >> 2) + y_offset;
286 int top = full_my - filter_height;
287 int bottom = full_my + filter_height + height;
289 return FFMAX(abs(top), bottom);
292 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
293 int height, int y_offset, int list0,
294 int list1, int *nrefs)
296 MpegEncContext *const s = &h->s;
299 y_offset += 16 * (s->mb_y >> MB_FIELD);
302 int ref_n = h->ref_cache[0][scan8[n]];
303 Picture *ref = &h->ref_list[0][ref_n];
305 // Error resilience puts the current picture in the ref list.
306 // Don't try to wait on these as it will cause a deadlock.
307 // Fields can wait on each other, though.
308 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
309 (ref->f.reference & 3) != s->picture_structure) {
310 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
311 if (refs[0][ref_n] < 0)
313 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
318 int ref_n = h->ref_cache[1][scan8[n]];
319 Picture *ref = &h->ref_list[1][ref_n];
321 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
322 (ref->f.reference & 3) != s->picture_structure) {
323 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
324 if (refs[1][ref_n] < 0)
326 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
332 * Wait until all reference frames are available for MC operations.
334 * @param h the H264 context
336 static void await_references(H264Context *h)
338 MpegEncContext *const s = &h->s;
339 const int mb_xy = h->mb_xy;
340 const int mb_type = s->current_picture.f.mb_type[mb_xy];
342 int nrefs[2] = { 0 };
345 memset(refs, -1, sizeof(refs));
347 if (IS_16X16(mb_type)) {
348 get_lowest_part_y(h, refs, 0, 16, 0,
349 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
350 } else if (IS_16X8(mb_type)) {
351 get_lowest_part_y(h, refs, 0, 8, 0,
352 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
353 get_lowest_part_y(h, refs, 8, 8, 8,
354 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
355 } else if (IS_8X16(mb_type)) {
356 get_lowest_part_y(h, refs, 0, 16, 0,
357 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
358 get_lowest_part_y(h, refs, 4, 16, 0,
359 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
363 assert(IS_8X8(mb_type));
365 for (i = 0; i < 4; i++) {
366 const int sub_mb_type = h->sub_mb_type[i];
368 int y_offset = (i & 2) << 2;
370 if (IS_SUB_8X8(sub_mb_type)) {
371 get_lowest_part_y(h, refs, n, 8, y_offset,
372 IS_DIR(sub_mb_type, 0, 0),
373 IS_DIR(sub_mb_type, 0, 1),
375 } else if (IS_SUB_8X4(sub_mb_type)) {
376 get_lowest_part_y(h, refs, n, 4, y_offset,
377 IS_DIR(sub_mb_type, 0, 0),
378 IS_DIR(sub_mb_type, 0, 1),
380 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
381 IS_DIR(sub_mb_type, 0, 0),
382 IS_DIR(sub_mb_type, 0, 1),
384 } else if (IS_SUB_4X8(sub_mb_type)) {
385 get_lowest_part_y(h, refs, n, 8, y_offset,
386 IS_DIR(sub_mb_type, 0, 0),
387 IS_DIR(sub_mb_type, 0, 1),
389 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
390 IS_DIR(sub_mb_type, 0, 0),
391 IS_DIR(sub_mb_type, 0, 1),
395 assert(IS_SUB_4X4(sub_mb_type));
396 for (j = 0; j < 4; j++) {
397 int sub_y_offset = y_offset + 2 * (j & 2);
398 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
399 IS_DIR(sub_mb_type, 0, 0),
400 IS_DIR(sub_mb_type, 0, 1),
407 for (list = h->list_count - 1; list >= 0; list--)
408 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
409 int row = refs[list][ref];
411 Picture *ref_pic = &h->ref_list[list][ref];
412 int ref_field = ref_pic->f.reference - 1;
413 int ref_field_picture = ref_pic->field_picture;
414 int pic_height = 16 * s->mb_height >> ref_field_picture;
419 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
420 ff_thread_await_progress(&ref_pic->f,
421 FFMIN((row >> 1) - !(row & 1),
424 ff_thread_await_progress(&ref_pic->f,
425 FFMIN((row >> 1), pic_height - 1),
427 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
428 ff_thread_await_progress(&ref_pic->f,
429 FFMIN(row * 2 + ref_field,
432 } else if (FIELD_PICTURE) {
433 ff_thread_await_progress(&ref_pic->f,
434 FFMIN(row, pic_height - 1),
437 ff_thread_await_progress(&ref_pic->f,
438 FFMIN(row, pic_height - 1),
445 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
446 int n, int square, int height,
448 uint8_t *dest_y, uint8_t *dest_cb,
450 int src_x_offset, int src_y_offset,
451 qpel_mc_func *qpix_op,
452 h264_chroma_mc_func chroma_op,
453 int pixel_shift, int chroma_idc)
455 MpegEncContext *const s = &h->s;
456 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
457 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
458 const int luma_xy = (mx & 3) + ((my & 3) << 2);
459 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
460 uint8_t *src_y = pic->f.data[0] + offset;
461 uint8_t *src_cb, *src_cr;
462 int extra_width = h->emu_edge_width;
463 int extra_height = h->emu_edge_height;
465 const int full_mx = mx >> 2;
466 const int full_my = my >> 2;
467 const int pic_width = 16 * s->mb_width;
468 const int pic_height = 16 * s->mb_height >> MB_FIELD;
476 if (full_mx < 0 - extra_width ||
477 full_my < 0 - extra_height ||
478 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
479 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
480 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
481 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
483 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
484 full_my - 2, pic_width, pic_height);
485 src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
489 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
491 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
493 if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
496 if (chroma_idc == 3 /* yuv444 */) {
497 src_cb = pic->f.data[1] + offset;
499 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
500 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
502 16 + 5, 16 + 5 /*FIXME*/,
503 full_mx - 2, full_my - 2,
504 pic_width, pic_height);
505 src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
507 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
509 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
511 src_cr = pic->f.data[2] + offset;
513 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
514 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
516 16 + 5, 16 + 5 /*FIXME*/,
517 full_mx - 2, full_my - 2,
518 pic_width, pic_height);
519 src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
521 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
523 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
527 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
528 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
529 // chroma offset when predicting from a field of opposite parity
530 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
531 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
534 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
535 (my >> ysh) * h->mb_uvlinesize;
536 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
537 (my >> ysh) * h->mb_uvlinesize;
540 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
541 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
542 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
543 src_cb = s->edge_emu_buffer;
545 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
546 height >> (chroma_idc == 1 /* yuv420 */),
547 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
550 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
551 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
552 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
553 src_cr = s->edge_emu_buffer;
555 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
556 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
559 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
560 int height, int delta,
561 uint8_t *dest_y, uint8_t *dest_cb,
563 int x_offset, int y_offset,
564 qpel_mc_func *qpix_put,
565 h264_chroma_mc_func chroma_put,
566 qpel_mc_func *qpix_avg,
567 h264_chroma_mc_func chroma_avg,
568 int list0, int list1,
569 int pixel_shift, int chroma_idc)
571 MpegEncContext *const s = &h->s;
572 qpel_mc_func *qpix_op = qpix_put;
573 h264_chroma_mc_func chroma_op = chroma_put;
575 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
576 if (chroma_idc == 3 /* yuv444 */) {
577 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
578 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
579 } else if (chroma_idc == 2 /* yuv422 */) {
580 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
581 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
582 } else { /* yuv420 */
583 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
584 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
586 x_offset += 8 * s->mb_x;
587 y_offset += 8 * (s->mb_y >> MB_FIELD);
590 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
591 mc_dir_part(h, ref, n, square, height, delta, 0,
592 dest_y, dest_cb, dest_cr, x_offset, y_offset,
593 qpix_op, chroma_op, pixel_shift, chroma_idc);
596 chroma_op = chroma_avg;
600 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
601 mc_dir_part(h, ref, n, square, height, delta, 1,
602 dest_y, dest_cb, dest_cr, x_offset, y_offset,
603 qpix_op, chroma_op, pixel_shift, chroma_idc);
607 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
608 int height, int delta,
609 uint8_t *dest_y, uint8_t *dest_cb,
611 int x_offset, int y_offset,
612 qpel_mc_func *qpix_put,
613 h264_chroma_mc_func chroma_put,
614 h264_weight_func luma_weight_op,
615 h264_weight_func chroma_weight_op,
616 h264_biweight_func luma_weight_avg,
617 h264_biweight_func chroma_weight_avg,
618 int list0, int list1,
619 int pixel_shift, int chroma_idc)
621 MpegEncContext *const s = &h->s;
624 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
625 if (chroma_idc == 3 /* yuv444 */) {
626 chroma_height = height;
627 chroma_weight_avg = luma_weight_avg;
628 chroma_weight_op = luma_weight_op;
629 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
630 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
631 } else if (chroma_idc == 2 /* yuv422 */) {
632 chroma_height = height;
633 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
634 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
635 } else { /* yuv420 */
636 chroma_height = height >> 1;
637 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
638 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
640 x_offset += 8 * s->mb_x;
641 y_offset += 8 * (s->mb_y >> MB_FIELD);
643 if (list0 && list1) {
644 /* don't optimize for luma-only case, since B-frames usually
645 * use implicit weights => chroma too. */
646 uint8_t *tmp_cb = s->obmc_scratchpad;
647 uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
648 uint8_t *tmp_y = s->obmc_scratchpad + 16 * h->mb_uvlinesize;
649 int refn0 = h->ref_cache[0][scan8[n]];
650 int refn1 = h->ref_cache[1][scan8[n]];
652 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
653 dest_y, dest_cb, dest_cr,
654 x_offset, y_offset, qpix_put, chroma_put,
655 pixel_shift, chroma_idc);
656 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
657 tmp_y, tmp_cb, tmp_cr,
658 x_offset, y_offset, qpix_put, chroma_put,
659 pixel_shift, chroma_idc);
661 if (h->use_weight == 2) {
662 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
663 int weight1 = 64 - weight0;
664 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
665 height, 5, weight0, weight1, 0);
666 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
667 chroma_height, 5, weight0, weight1, 0);
668 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
669 chroma_height, 5, weight0, weight1, 0);
671 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
672 h->luma_log2_weight_denom,
673 h->luma_weight[refn0][0][0],
674 h->luma_weight[refn1][1][0],
675 h->luma_weight[refn0][0][1] +
676 h->luma_weight[refn1][1][1]);
677 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
678 h->chroma_log2_weight_denom,
679 h->chroma_weight[refn0][0][0][0],
680 h->chroma_weight[refn1][1][0][0],
681 h->chroma_weight[refn0][0][0][1] +
682 h->chroma_weight[refn1][1][0][1]);
683 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
684 h->chroma_log2_weight_denom,
685 h->chroma_weight[refn0][0][1][0],
686 h->chroma_weight[refn1][1][1][0],
687 h->chroma_weight[refn0][0][1][1] +
688 h->chroma_weight[refn1][1][1][1]);
691 int list = list1 ? 1 : 0;
692 int refn = h->ref_cache[list][scan8[n]];
693 Picture *ref = &h->ref_list[list][refn];
694 mc_dir_part(h, ref, n, square, height, delta, list,
695 dest_y, dest_cb, dest_cr, x_offset, y_offset,
696 qpix_put, chroma_put, pixel_shift, chroma_idc);
698 luma_weight_op(dest_y, h->mb_linesize, height,
699 h->luma_log2_weight_denom,
700 h->luma_weight[refn][list][0],
701 h->luma_weight[refn][list][1]);
702 if (h->use_weight_chroma) {
703 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
704 h->chroma_log2_weight_denom,
705 h->chroma_weight[refn][list][0][0],
706 h->chroma_weight[refn][list][0][1]);
707 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
708 h->chroma_log2_weight_denom,
709 h->chroma_weight[refn][list][1][0],
710 h->chroma_weight[refn][list][1][1]);
715 static av_always_inline void mc_part(H264Context *h, int n, int square,
716 int height, int delta,
717 uint8_t *dest_y, uint8_t *dest_cb,
719 int x_offset, int y_offset,
720 qpel_mc_func *qpix_put,
721 h264_chroma_mc_func chroma_put,
722 qpel_mc_func *qpix_avg,
723 h264_chroma_mc_func chroma_avg,
724 h264_weight_func *weight_op,
725 h264_biweight_func *weight_avg,
726 int list0, int list1,
727 int pixel_shift, int chroma_idc)
729 if ((h->use_weight == 2 && list0 && list1 &&
730 (h->implicit_weight[h->ref_cache[0][scan8[n]]][h->ref_cache[1][scan8[n]]][h->s.mb_y & 1] != 32)) ||
732 mc_part_weighted(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
733 x_offset, y_offset, qpix_put, chroma_put,
734 weight_op[0], weight_op[1], weight_avg[0],
735 weight_avg[1], list0, list1, pixel_shift, chroma_idc);
737 mc_part_std(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
738 x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
739 chroma_avg, list0, list1, pixel_shift, chroma_idc);
742 static av_always_inline void prefetch_motion(H264Context *h, int list,
743 int pixel_shift, int chroma_idc)
745 /* fetch pixels for estimated mv 4 macroblocks ahead
746 * optimized for 64byte cache lines */
747 MpegEncContext *const s = &h->s;
748 const int refn = h->ref_cache[list][scan8[0]];
750 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
751 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
752 uint8_t **src = h->ref_list[list][refn].f.data;
753 int off = (mx << pixel_shift) +
754 (my + (s->mb_x & 3) * 4) * h->mb_linesize +
756 s->dsp.prefetch(src[0] + off, s->linesize, 4);
757 if (chroma_idc == 3 /* yuv444 */) {
758 s->dsp.prefetch(src[1] + off, s->linesize, 4);
759 s->dsp.prefetch(src[2] + off, s->linesize, 4);
761 off = ((mx >> 1) << pixel_shift) +
762 ((my >> 1) + (s->mb_x & 7)) * s->uvlinesize +
764 s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
769 static av_always_inline void hl_motion(H264Context *h, uint8_t *dest_y,
770 uint8_t *dest_cb, uint8_t *dest_cr,
771 qpel_mc_func(*qpix_put)[16],
772 h264_chroma_mc_func(*chroma_put),
773 qpel_mc_func(*qpix_avg)[16],
774 h264_chroma_mc_func(*chroma_avg),
775 h264_weight_func *weight_op,
776 h264_biweight_func *weight_avg,
777 int pixel_shift, int chroma_idc)
779 MpegEncContext *const s = &h->s;
780 const int mb_xy = h->mb_xy;
781 const int mb_type = s->current_picture.f.mb_type[mb_xy];
783 assert(IS_INTER(mb_type));
785 if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
787 prefetch_motion(h, 0, pixel_shift, chroma_idc);
789 if (IS_16X16(mb_type)) {
790 mc_part(h, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0,
791 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
792 weight_op, weight_avg,
793 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
794 pixel_shift, chroma_idc);
795 } else if (IS_16X8(mb_type)) {
796 mc_part(h, 0, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 0,
797 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
798 weight_op, weight_avg,
799 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
800 pixel_shift, chroma_idc);
801 mc_part(h, 8, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 4,
802 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
803 weight_op, weight_avg,
804 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
805 pixel_shift, chroma_idc);
806 } else if (IS_8X16(mb_type)) {
807 mc_part(h, 0, 0, 16, 8 * h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
808 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
809 &weight_op[1], &weight_avg[1],
810 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
811 pixel_shift, chroma_idc);
812 mc_part(h, 4, 0, 16, 8 * h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
813 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
814 &weight_op[1], &weight_avg[1],
815 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
816 pixel_shift, chroma_idc);
820 assert(IS_8X8(mb_type));
822 for (i = 0; i < 4; i++) {
823 const int sub_mb_type = h->sub_mb_type[i];
825 int x_offset = (i & 1) << 2;
826 int y_offset = (i & 2) << 1;
828 if (IS_SUB_8X8(sub_mb_type)) {
829 mc_part(h, n, 1, 8, 0, dest_y, dest_cb, dest_cr,
831 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
832 &weight_op[1], &weight_avg[1],
833 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
834 pixel_shift, chroma_idc);
835 } else if (IS_SUB_8X4(sub_mb_type)) {
836 mc_part(h, n, 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr,
838 qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
839 &weight_op[1], &weight_avg[1],
840 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
841 pixel_shift, chroma_idc);
842 mc_part(h, n + 2, 0, 4, 4 << pixel_shift,
843 dest_y, dest_cb, dest_cr, x_offset, y_offset + 2,
844 qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
845 &weight_op[1], &weight_avg[1],
846 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
847 pixel_shift, chroma_idc);
848 } else if (IS_SUB_4X8(sub_mb_type)) {
849 mc_part(h, n, 0, 8, 4 * h->mb_linesize,
850 dest_y, dest_cb, dest_cr, x_offset, y_offset,
851 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
852 &weight_op[2], &weight_avg[2],
853 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
854 pixel_shift, chroma_idc);
855 mc_part(h, n + 1, 0, 8, 4 * h->mb_linesize,
856 dest_y, dest_cb, dest_cr, x_offset + 2, y_offset,
857 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
858 &weight_op[2], &weight_avg[2],
859 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
860 pixel_shift, chroma_idc);
863 assert(IS_SUB_4X4(sub_mb_type));
864 for (j = 0; j < 4; j++) {
865 int sub_x_offset = x_offset + 2 * (j & 1);
866 int sub_y_offset = y_offset + (j & 2);
867 mc_part(h, n + j, 1, 4, 0,
868 dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
869 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
870 &weight_op[2], &weight_avg[2],
871 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
872 pixel_shift, chroma_idc);
878 prefetch_motion(h, 1, pixel_shift, chroma_idc);
881 static av_always_inline void hl_motion_420(H264Context *h, uint8_t *dest_y,
882 uint8_t *dest_cb, uint8_t *dest_cr,
883 qpel_mc_func(*qpix_put)[16],
884 h264_chroma_mc_func(*chroma_put),
885 qpel_mc_func(*qpix_avg)[16],
886 h264_chroma_mc_func(*chroma_avg),
887 h264_weight_func *weight_op,
888 h264_biweight_func *weight_avg,
891 hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
892 qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 1);
895 static av_always_inline void hl_motion_422(H264Context *h, uint8_t *dest_y,
896 uint8_t *dest_cb, uint8_t *dest_cr,
897 qpel_mc_func(*qpix_put)[16],
898 h264_chroma_mc_func(*chroma_put),
899 qpel_mc_func(*qpix_avg)[16],
900 h264_chroma_mc_func(*chroma_avg),
901 h264_weight_func *weight_op,
902 h264_biweight_func *weight_avg,
905 hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
906 qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 2);
909 static void free_tables(H264Context *h, int free_rbsp)
914 av_freep(&h->intra4x4_pred_mode);
915 av_freep(&h->chroma_pred_mode_table);
916 av_freep(&h->cbp_table);
917 av_freep(&h->mvd_table[0]);
918 av_freep(&h->mvd_table[1]);
919 av_freep(&h->direct_table);
920 av_freep(&h->non_zero_count);
921 av_freep(&h->slice_table_base);
922 h->slice_table = NULL;
923 av_freep(&h->list_counts);
925 av_freep(&h->mb2b_xy);
926 av_freep(&h->mb2br_xy);
928 for (i = 0; i < MAX_THREADS; i++) {
929 hx = h->thread_context[i];
932 av_freep(&hx->top_borders[1]);
933 av_freep(&hx->top_borders[0]);
934 av_freep(&hx->s.obmc_scratchpad);
936 av_freep(&hx->rbsp_buffer[1]);
937 av_freep(&hx->rbsp_buffer[0]);
938 hx->rbsp_buffer_size[0] = 0;
939 hx->rbsp_buffer_size[1] = 0;
942 av_freep(&h->thread_context[i]);
946 static void init_dequant8_coeff_table(H264Context *h)
949 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
951 for (i = 0; i < 6; i++) {
952 h->dequant8_coeff[i] = h->dequant8_buffer[i];
953 for (j = 0; j < i; j++)
954 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
955 64 * sizeof(uint8_t))) {
956 h->dequant8_coeff[i] = h->dequant8_buffer[j];
962 for (q = 0; q < max_qp + 1; q++) {
965 for (x = 0; x < 64; x++)
966 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
967 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
968 h->pps.scaling_matrix8[i][x]) << shift;
973 static void init_dequant4_coeff_table(H264Context *h)
976 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
977 for (i = 0; i < 6; i++) {
978 h->dequant4_coeff[i] = h->dequant4_buffer[i];
979 for (j = 0; j < i; j++)
980 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
981 16 * sizeof(uint8_t))) {
982 h->dequant4_coeff[i] = h->dequant4_buffer[j];
988 for (q = 0; q < max_qp + 1; q++) {
989 int shift = div6[q] + 2;
991 for (x = 0; x < 16; x++)
992 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
993 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
994 h->pps.scaling_matrix4[i][x]) << shift;
999 static void init_dequant_tables(H264Context *h)
1002 init_dequant4_coeff_table(h);
1003 if (h->pps.transform_8x8_mode)
1004 init_dequant8_coeff_table(h);
1005 if (h->sps.transform_bypass) {
1006 for (i = 0; i < 6; i++)
1007 for (x = 0; x < 16; x++)
1008 h->dequant4_coeff[i][0][x] = 1 << 6;
1009 if (h->pps.transform_8x8_mode)
1010 for (i = 0; i < 6; i++)
1011 for (x = 0; x < 64; x++)
1012 h->dequant8_coeff[i][0][x] = 1 << 6;
1016 int ff_h264_alloc_tables(H264Context *h)
1018 MpegEncContext *const s = &h->s;
1019 const int big_mb_num = s->mb_stride * (s->mb_height + 1);
1020 const int row_mb_num = s->mb_stride * 2 * s->avctx->thread_count;
1023 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
1024 row_mb_num * 8 * sizeof(uint8_t), fail)
1025 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
1026 big_mb_num * 48 * sizeof(uint8_t), fail)
1027 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
1028 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
1029 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
1030 big_mb_num * sizeof(uint16_t), fail)
1031 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
1032 big_mb_num * sizeof(uint8_t), fail)
1033 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
1034 16 * row_mb_num * sizeof(uint8_t), fail);
1035 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
1036 16 * row_mb_num * sizeof(uint8_t), fail);
1037 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
1038 4 * big_mb_num * sizeof(uint8_t), fail);
1039 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
1040 big_mb_num * sizeof(uint8_t), fail)
1042 memset(h->slice_table_base, -1,
1043 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
1044 h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
1046 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
1047 big_mb_num * sizeof(uint32_t), fail);
1048 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
1049 big_mb_num * sizeof(uint32_t), fail);
1050 for (y = 0; y < s->mb_height; y++)
1051 for (x = 0; x < s->mb_width; x++) {
1052 const int mb_xy = x + y * s->mb_stride;
1053 const int b_xy = 4 * x + 4 * y * h->b_stride;
1055 h->mb2b_xy[mb_xy] = b_xy;
1056 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
1059 s->obmc_scratchpad = NULL;
1061 if (!h->dequant4_coeff[0])
1062 init_dequant_tables(h);
1072 * Mimic alloc_tables(), but for every context thread.
1074 static void clone_tables(H264Context *dst, H264Context *src, int i)
1076 MpegEncContext *const s = &src->s;
1077 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
1078 dst->non_zero_count = src->non_zero_count;
1079 dst->slice_table = src->slice_table;
1080 dst->cbp_table = src->cbp_table;
1081 dst->mb2b_xy = src->mb2b_xy;
1082 dst->mb2br_xy = src->mb2br_xy;
1083 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1084 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
1085 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
1086 dst->direct_table = src->direct_table;
1087 dst->list_counts = src->list_counts;
1088 dst->s.obmc_scratchpad = NULL;
1089 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
1090 src->sps.chroma_format_idc);
1095 * Allocate buffers which are not shared amongst multiple threads.
1097 static int context_init(H264Context *h)
1099 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
1100 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1101 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
1102 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1104 h->ref_cache[0][scan8[5] + 1] =
1105 h->ref_cache[0][scan8[7] + 1] =
1106 h->ref_cache[0][scan8[13] + 1] =
1107 h->ref_cache[1][scan8[5] + 1] =
1108 h->ref_cache[1][scan8[7] + 1] =
1109 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1114 return -1; // free_tables will clean up for us
1117 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
1119 static av_cold void common_init(H264Context *h)
1121 MpegEncContext *const s = &h->s;
1123 s->width = s->avctx->width;
1124 s->height = s->avctx->height;
1125 s->codec_id = s->avctx->codec->id;
1127 ff_h264dsp_init(&h->h264dsp, 8, 1);
1128 ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);
1130 h->dequant_coeff_pps = -1;
1131 s->unrestricted_mv = 1;
1133 /* needed so that IDCT permutation is known early */
1134 ff_dsputil_init(&s->dsp, s->avctx);
1136 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1137 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1140 int ff_h264_decode_extradata(H264Context *h)
1142 AVCodecContext *avctx = h->s.avctx;
1144 if (avctx->extradata[0] == 1) {
1145 int i, cnt, nalsize;
1146 unsigned char *p = avctx->extradata;
1150 if (avctx->extradata_size < 7) {
1151 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1154 /* sps and pps in the avcC always have length coded with 2 bytes,
1155 * so put a fake nal_length_size = 2 while parsing them */
1156 h->nal_length_size = 2;
1157 // Decode sps from avcC
1158 cnt = *(p + 5) & 0x1f; // Number of sps
1160 for (i = 0; i < cnt; i++) {
1161 nalsize = AV_RB16(p) + 2;
1162 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1164 if (decode_nal_units(h, p, nalsize) < 0) {
1165 av_log(avctx, AV_LOG_ERROR,
1166 "Decoding sps %d from avcC failed\n", i);
1171 // Decode pps from avcC
1172 cnt = *(p++); // Number of pps
1173 for (i = 0; i < cnt; i++) {
1174 nalsize = AV_RB16(p) + 2;
1175 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1177 if (decode_nal_units(h, p, nalsize) < 0) {
1178 av_log(avctx, AV_LOG_ERROR,
1179 "Decoding pps %d from avcC failed\n", i);
1184 // Now store right nal length size, that will be used to parse all other nals
1185 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1188 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
1194 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1196 H264Context *h = avctx->priv_data;
1197 MpegEncContext *const s = &h->s;
1200 ff_MPV_decode_defaults(s);
1205 s->out_format = FMT_H264;
1206 s->workaround_bugs = avctx->workaround_bugs;
1209 // s->decode_mb = ff_h263_decode_mb;
1210 s->quarter_sample = 1;
1211 if (!avctx->has_b_frames)
1214 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1216 ff_h264_decode_init_vlc();
1219 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1221 h->thread_context[0] = h;
1222 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1223 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1224 h->last_pocs[i] = INT_MIN;
1225 h->prev_poc_msb = 1 << 16;
1227 ff_h264_reset_sei(h);
1228 if (avctx->codec_id == CODEC_ID_H264) {
1229 if (avctx->ticks_per_frame == 1)
1230 s->avctx->time_base.den *= 2;
1231 avctx->ticks_per_frame = 2;
1234 if (avctx->extradata_size > 0 && avctx->extradata &&
1235 ff_h264_decode_extradata(h))
1238 if (h->sps.bitstream_restriction_flag &&
1239 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1240 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1247 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1249 static void copy_picture_range(Picture **to, Picture **from, int count,
1250 MpegEncContext *new_base,
1251 MpegEncContext *old_base)
1255 for (i = 0; i < count; i++) {
1256 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1257 IN_RANGE(from[i], old_base->picture,
1258 sizeof(Picture) * old_base->picture_count) ||
1260 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1264 static void copy_parameter_set(void **to, void **from, int count, int size)
1268 for (i = 0; i < count; i++) {
1269 if (to[i] && !from[i])
1271 else if (from[i] && !to[i])
1272 to[i] = av_malloc(size);
1275 memcpy(to[i], from[i], size);
1279 static int decode_init_thread_copy(AVCodecContext *avctx)
1281 H264Context *h = avctx->priv_data;
1283 if (!avctx->internal->is_copy)
1285 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1286 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1291 #define copy_fields(to, from, start_field, end_field) \
1292 memcpy(&to->start_field, &from->start_field, \
1293 (char *)&to->end_field - (char *)&to->start_field)
1295 static int decode_update_thread_context(AVCodecContext *dst,
1296 const AVCodecContext *src)
1298 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1299 MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1300 int inited = s->context_initialized, err;
1303 if (dst == src || !s1->context_initialized)
1306 err = ff_mpeg_update_thread_context(dst, src);
1310 // FIXME handle width/height changing
1312 for (i = 0; i < MAX_SPS_COUNT; i++)
1313 av_freep(h->sps_buffers + i);
1315 for (i = 0; i < MAX_PPS_COUNT; i++)
1316 av_freep(h->pps_buffers + i);
1318 // copy all fields after MpegEnc
1319 memcpy(&h->s + 1, &h1->s + 1,
1320 sizeof(H264Context) - sizeof(MpegEncContext));
1321 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1322 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1323 if (ff_h264_alloc_tables(h) < 0) {
1324 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1325 return AVERROR(ENOMEM);
1329 for (i = 0; i < 2; i++) {
1330 h->rbsp_buffer[i] = NULL;
1331 h->rbsp_buffer_size[i] = 0;
1334 h->thread_context[0] = h;
1336 /* frame_start may not be called for the next thread (if it's decoding
1337 * a bottom field) so this has to be allocated here */
1338 h->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1340 s->dsp.clear_blocks(h->mb);
1341 s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1344 // extradata/NAL handling
1345 h->is_avc = h1->is_avc;
1348 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1349 MAX_SPS_COUNT, sizeof(SPS));
1351 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1352 MAX_PPS_COUNT, sizeof(PPS));
1355 // Dequantization matrices
1356 // FIXME these are big - can they be only copied when PPS changes?
1357 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1359 for (i = 0; i < 6; i++)
1360 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1361 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1363 for (i = 0; i < 6; i++)
1364 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1365 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1367 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1370 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1373 copy_fields(h, h1, ref_count, list_count);
1374 copy_fields(h, h1, ref_list, intra_gb);
1375 copy_fields(h, h1, short_ref, cabac_init_idc);
1377 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1378 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1379 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1380 MAX_DELAYED_PIC_COUNT + 2, s, s1);
1382 h->last_slice_type = h1->last_slice_type;
1384 if (!s->current_picture_ptr)
1388 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1389 h->prev_poc_msb = h->poc_msb;
1390 h->prev_poc_lsb = h->poc_lsb;
1392 h->prev_frame_num_offset = h->frame_num_offset;
1393 h->prev_frame_num = h->frame_num;
1394 h->outputed_poc = h->next_outputed_poc;
1399 int ff_h264_frame_start(H264Context *h)
1401 MpegEncContext *const s = &h->s;
1403 const int pixel_shift = h->pixel_shift;
1405 if (ff_MPV_frame_start(s, s->avctx) < 0)
1407 ff_er_frame_start(s);
1409 * ff_MPV_frame_start uses pict_type to derive key_frame.
1410 * This is incorrect for H.264; IDR markings must be used.
1411 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1412 * See decode_nal_units().
1414 s->current_picture_ptr->f.key_frame = 0;
1415 s->current_picture_ptr->mmco_reset = 0;
1417 assert(s->linesize && s->uvlinesize);
1419 for (i = 0; i < 16; i++) {
1420 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1421 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1423 for (i = 0; i < 16; i++) {
1424 h->block_offset[16 + i] =
1425 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1426 h->block_offset[48 + 16 + i] =
1427 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1430 /* can't be in alloc_tables because linesize isn't known there.
1431 * FIXME: redo bipred weight to not require extra buffer? */
1432 for (i = 0; i < s->slice_context_count; i++)
1433 if (h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1434 h->thread_context[i]->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1436 /* Some macroblocks can be accessed before they're available in case
1437 * of lost slices, MBAFF or threading. */
1438 memset(h->slice_table, -1,
1439 (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1441 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1442 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1444 /* We mark the current picture as non-reference after allocating it, so
1445 * that if we break out due to an error it can be released automatically
1446 * in the next ff_MPV_frame_start().
1447 * SVQ3 as well as most other codecs have only last/next/current and thus
1448 * get released even with set reference, besides SVQ3 and others do not
1449 * mark frames as reference later "naturally". */
1450 if (s->codec_id != CODEC_ID_SVQ3)
1451 s->current_picture_ptr->f.reference = 0;
1453 s->current_picture_ptr->field_poc[0] =
1454 s->current_picture_ptr->field_poc[1] = INT_MAX;
1456 h->next_output_pic = NULL;
1458 assert(s->current_picture_ptr->long_ref == 0);
1464 * Run setup operations that must be run after slice header decoding.
1465 * This includes finding the next displayed frame.
1467 * @param h h264 master context
1468 * @param setup_finished enough NALs have been read that we can call
1469 * ff_thread_finish_setup()
1471 static void decode_postinit(H264Context *h, int setup_finished)
1473 MpegEncContext *const s = &h->s;
1474 Picture *out = s->current_picture_ptr;
1475 Picture *cur = s->current_picture_ptr;
1476 int i, pics, out_of_order, out_idx;
1477 int invalid = 0, cnt = 0;
1479 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1480 s->current_picture_ptr->f.pict_type = s->pict_type;
1482 if (h->next_output_pic)
1485 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1486 /* FIXME: if we have two PAFF fields in one packet, we can't start
1487 * the next thread here. If we have one field per packet, we can.
1488 * The check in decode_nal_units() is not good enough to find this
1489 * yet, so we assume the worst for now. */
1490 // if (setup_finished)
1491 // ff_thread_finish_setup(s->avctx);
1495 cur->f.interlaced_frame = 0;
1496 cur->f.repeat_pict = 0;
1498 /* Signal interlacing information externally. */
1499 /* Prioritize picture timing SEI information over used
1500 * decoding process if it exists. */
1502 if (h->sps.pic_struct_present_flag) {
1503 switch (h->sei_pic_struct) {
1504 case SEI_PIC_STRUCT_FRAME:
1506 case SEI_PIC_STRUCT_TOP_FIELD:
1507 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1508 cur->f.interlaced_frame = 1;
1510 case SEI_PIC_STRUCT_TOP_BOTTOM:
1511 case SEI_PIC_STRUCT_BOTTOM_TOP:
1512 if (FIELD_OR_MBAFF_PICTURE)
1513 cur->f.interlaced_frame = 1;
1515 // try to flag soft telecine progressive
1516 cur->f.interlaced_frame = h->prev_interlaced_frame;
1518 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1519 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1520 /* Signal the possibility of telecined film externally
1521 * (pic_struct 5,6). From these hints, let the applications
1522 * decide if they apply deinterlacing. */
1523 cur->f.repeat_pict = 1;
1525 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1526 // Force progressive here, doubling interlaced frame is a bad idea.
1527 cur->f.repeat_pict = 2;
1529 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1530 cur->f.repeat_pict = 4;
1534 if ((h->sei_ct_type & 3) &&
1535 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1536 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1538 /* Derive interlacing flag from used decoding process. */
1539 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1541 h->prev_interlaced_frame = cur->f.interlaced_frame;
1543 if (cur->field_poc[0] != cur->field_poc[1]) {
1544 /* Derive top_field_first from field pocs. */
1545 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1547 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1548 /* Use picture timing SEI information. Even if it is a
1549 * information of a past frame, better than nothing. */
1550 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1551 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1552 cur->f.top_field_first = 1;
1554 cur->f.top_field_first = 0;
1556 /* Most likely progressive */
1557 cur->f.top_field_first = 0;
1561 // FIXME do something with unavailable reference frames
1563 /* Sort B-frames into display order */
1565 if (h->sps.bitstream_restriction_flag &&
1566 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1567 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1571 if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1572 !h->sps.bitstream_restriction_flag) {
1573 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1578 while (h->delayed_pic[pics])
1581 assert(pics <= MAX_DELAYED_PIC_COUNT);
1583 h->delayed_pic[pics++] = cur;
1584 if (cur->f.reference == 0)
1585 cur->f.reference = DELAYED_PIC_REF;
1587 /* Frame reordering. This code takes pictures from coding order and sorts
1588 * them by their incremental POC value into display order. It supports POC
1589 * gaps, MMCO reset codes and random resets.
1590 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1591 * and/or can be closed down with a MMCO reset code. In sequences where
1592 * there is no delay, we can't detect that (since the frame was already
1593 * output to the user), so we also set h->mmco_reset to detect the MMCO
1595 * FIXME: if we detect insufficient delays (as per s->avctx->has_b_frames),
1596 * we increase the delay between input and output. All frames affected by
1597 * the lag (e.g. those that should have been output before another frame
1598 * that we already returned to the user) will be dropped. This is a bug
1599 * that we will fix later. */
1600 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1601 cnt += out->poc < h->last_pocs[i];
1602 invalid += out->poc == INT_MIN;
1604 if (!h->mmco_reset && !cur->f.key_frame &&
1605 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1608 h->delayed_pic[pics - 2]->mmco_reset = 2;
1610 if (h->mmco_reset || cur->f.key_frame) {
1611 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1612 h->last_pocs[i] = INT_MIN;
1614 invalid = MAX_DELAYED_PIC_COUNT;
1616 out = h->delayed_pic[0];
1618 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1619 h->delayed_pic[i] &&
1620 !h->delayed_pic[i - 1]->mmco_reset &&
1621 !h->delayed_pic[i]->f.key_frame;
1623 if (h->delayed_pic[i]->poc < out->poc) {
1624 out = h->delayed_pic[i];
1627 if (s->avctx->has_b_frames == 0 &&
1628 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
1629 h->next_outputed_poc = INT_MIN;
1630 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1631 (out->poc < h->next_outputed_poc);
1633 if (h->sps.bitstream_restriction_flag &&
1634 s->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1635 } else if (out_of_order && pics - 1 == s->avctx->has_b_frames &&
1636 s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1637 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1638 s->avctx->has_b_frames = FFMAX(s->avctx->has_b_frames, cnt);
1641 } else if (s->low_delay &&
1642 ((h->next_outputed_poc != INT_MIN &&
1643 out->poc > h->next_outputed_poc + 2) ||
1644 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
1646 s->avctx->has_b_frames++;
1649 if (pics > s->avctx->has_b_frames) {
1650 out->f.reference &= ~DELAYED_PIC_REF;
1651 // for frame threading, the owner must be the second field's thread or
1652 // else the first thread can release the picture and reuse it unsafely
1654 for (i = out_idx; h->delayed_pic[i]; i++)
1655 h->delayed_pic[i] = h->delayed_pic[i + 1];
1657 memmove(h->last_pocs, &h->last_pocs[1],
1658 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1659 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1660 if (!out_of_order && pics > s->avctx->has_b_frames) {
1661 h->next_output_pic = out;
1662 if (out->mmco_reset) {
1664 h->next_outputed_poc = out->poc;
1665 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1667 h->next_outputed_poc = INT_MIN;
1670 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
1671 h->next_outputed_poc = INT_MIN;
1673 h->next_outputed_poc = out->poc;
1678 av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1682 ff_thread_finish_setup(s->avctx);
1685 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1686 uint8_t *src_cb, uint8_t *src_cr,
1687 int linesize, int uvlinesize,
1690 MpegEncContext *const s = &h->s;
1691 uint8_t *top_border;
1693 const int pixel_shift = h->pixel_shift;
1694 int chroma444 = CHROMA444;
1695 int chroma422 = CHROMA422;
1698 src_cb -= uvlinesize;
1699 src_cr -= uvlinesize;
1701 if (!simple && FRAME_MBAFF) {
1704 top_border = h->top_borders[0][s->mb_x];
1705 AV_COPY128(top_border, src_y + 15 * linesize);
1707 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1708 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1711 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1712 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1713 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1714 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1716 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1717 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1719 } else if (chroma422) {
1721 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1722 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1724 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1725 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1729 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1730 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1732 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1733 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1738 } else if (MB_MBAFF) {
1744 top_border = h->top_borders[top_idx][s->mb_x];
1745 /* There are two lines saved, the line above the the top macroblock
1746 * of a pair, and the line above the bottom macroblock. */
1747 AV_COPY128(top_border, src_y + 16 * linesize);
1749 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1751 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1754 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1755 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1756 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1757 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1759 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1760 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1762 } else if (chroma422) {
1764 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1765 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1767 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1768 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1772 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1773 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1775 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1776 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1782 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1783 uint8_t *src_cb, uint8_t *src_cr,
1784 int linesize, int uvlinesize,
1785 int xchg, int chroma444,
1786 int simple, int pixel_shift)
1788 MpegEncContext *const s = &h->s;
1789 int deblock_topleft;
1792 uint8_t *top_border_m1;
1793 uint8_t *top_border;
1795 if (!simple && FRAME_MBAFF) {
1800 top_idx = MB_MBAFF ? 0 : 1;
1804 if (h->deblocking_filter == 2) {
1805 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1806 deblock_top = h->top_type;
1808 deblock_topleft = (s->mb_x > 0);
1809 deblock_top = (s->mb_y > !!MB_FIELD);
1812 src_y -= linesize + 1 + pixel_shift;
1813 src_cb -= uvlinesize + 1 + pixel_shift;
1814 src_cr -= uvlinesize + 1 + pixel_shift;
1816 top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1817 top_border = h->top_borders[top_idx][s->mb_x];
1819 #define XCHG(a, b, xchg) \
1820 if (pixel_shift) { \
1822 AV_SWAP64(b + 0, a + 0); \
1823 AV_SWAP64(b + 8, a + 8); \
1833 if (deblock_topleft) {
1834 XCHG(top_border_m1 + (8 << pixel_shift),
1835 src_y - (7 << pixel_shift), 1);
1837 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1838 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1839 if (s->mb_x + 1 < s->mb_width) {
1840 XCHG(h->top_borders[top_idx][s->mb_x + 1],
1841 src_y + (17 << pixel_shift), 1);
1844 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1846 if (deblock_topleft) {
1847 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1848 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1850 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1851 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1852 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1853 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1854 if (s->mb_x + 1 < s->mb_width) {
1855 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1856 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1860 if (deblock_topleft) {
1861 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1862 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1864 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1865 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1871 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
1874 if (high_bit_depth) {
1875 return AV_RN32A(((int32_t *)mb) + index);
1877 return AV_RN16A(mb + index);
1880 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
1881 int index, int value)
1883 if (high_bit_depth) {
1884 AV_WN32A(((int32_t *)mb) + index, value);
1886 AV_WN16A(mb + index, value);
1889 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1890 int mb_type, int is_h264,
1892 int transform_bypass,
1896 uint8_t *dest_y, int p)
1898 MpegEncContext *const s = &h->s;
1899 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1900 void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1902 int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1903 block_offset += 16 * p;
1904 if (IS_INTRA4x4(mb_type)) {
1905 if (simple || !s->encoding) {
1906 if (IS_8x8DCT(mb_type)) {
1907 if (transform_bypass) {
1909 idct_add = s->dsp.add_pixels8;
1911 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1912 idct_add = h->h264dsp.h264_idct8_add;
1914 for (i = 0; i < 16; i += 4) {
1915 uint8_t *const ptr = dest_y + block_offset[i];
1916 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1917 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1918 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1920 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1921 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1922 (h->topright_samples_available << i) & 0x4000, linesize);
1924 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1925 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1927 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1932 if (transform_bypass) {
1934 idct_add = s->dsp.add_pixels4;
1936 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1937 idct_add = h->h264dsp.h264_idct_add;
1939 for (i = 0; i < 16; i++) {
1940 uint8_t *const ptr = dest_y + block_offset[i];
1941 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1943 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1944 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1949 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1950 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1951 assert(s->mb_y || linesize <= block_offset[i]);
1952 if (!topright_avail) {
1954 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1955 topright = (uint8_t *)&tr_high;
1957 tr = ptr[3 - linesize] * 0x01010101u;
1958 topright = (uint8_t *)&tr;
1961 topright = ptr + (4 << pixel_shift) - linesize;
1965 h->hpc.pred4x4[dir](ptr, topright, linesize);
1966 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1969 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1970 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1972 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1973 } else if (CONFIG_SVQ3_DECODER)
1974 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1981 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1983 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1984 if (!transform_bypass)
1985 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1987 h->dequant4_coeff[p][qscale][0]);
1989 static const uint8_t dc_mapping[16] = {
1990 0 * 16, 1 * 16, 4 * 16, 5 * 16,
1991 2 * 16, 3 * 16, 6 * 16, 7 * 16,
1992 8 * 16, 9 * 16, 12 * 16, 13 * 16,
1993 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1994 for (i = 0; i < 16; i++)
1995 dctcoef_set(h->mb + (p * 256 << pixel_shift),
1996 pixel_shift, dc_mapping[i],
1997 dctcoef_get(h->mb_luma_dc[p],
2001 } else if (CONFIG_SVQ3_DECODER)
2002 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2003 h->mb_luma_dc[p], qscale);
2007 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2008 int is_h264, int simple,
2009 int transform_bypass,
2013 uint8_t *dest_y, int p)
2015 MpegEncContext *const s = &h->s;
2016 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
2018 block_offset += 16 * p;
2019 if (!IS_INTRA4x4(mb_type)) {
2021 if (IS_INTRA16x16(mb_type)) {
2022 if (transform_bypass) {
2023 if (h->sps.profile_idc == 244 &&
2024 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2025 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2026 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2027 h->mb + (p * 256 << pixel_shift),
2030 for (i = 0; i < 16; i++)
2031 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2032 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2033 s->dsp.add_pixels4(dest_y + block_offset[i],
2034 h->mb + (i * 16 + p * 256 << pixel_shift),
2038 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2039 h->mb + (p * 256 << pixel_shift),
2041 h->non_zero_count_cache + p * 5 * 8);
2043 } else if (h->cbp & 15) {
2044 if (transform_bypass) {
2045 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2046 idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
2047 : s->dsp.add_pixels4;
2048 for (i = 0; i < 16; i += di)
2049 if (h->non_zero_count_cache[scan8[i + p * 16]])
2050 idct_add(dest_y + block_offset[i],
2051 h->mb + (i * 16 + p * 256 << pixel_shift),
2054 if (IS_8x8DCT(mb_type))
2055 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2056 h->mb + (p * 256 << pixel_shift),
2058 h->non_zero_count_cache + p * 5 * 8);
2060 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2061 h->mb + (p * 256 << pixel_shift),
2063 h->non_zero_count_cache + p * 5 * 8);
2066 } else if (CONFIG_SVQ3_DECODER) {
2067 for (i = 0; i < 16; i++)
2068 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2069 // FIXME benchmark weird rule, & below
2070 uint8_t *const ptr = dest_y + block_offset[i];
2071 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2072 s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2078 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple,
2081 MpegEncContext *const s = &h->s;
2082 const int mb_x = s->mb_x;
2083 const int mb_y = s->mb_y;
2084 const int mb_xy = h->mb_xy;
2085 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2086 uint8_t *dest_y, *dest_cb, *dest_cr;
2087 int linesize, uvlinesize /*dct_offset*/;
2089 int *block_offset = &h->block_offset[0];
2090 const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2091 /* is_h264 should always be true if SVQ3 is disabled. */
2092 const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
2093 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
2094 const int block_h = 16 >> s->chroma_y_shift;
2095 const int chroma422 = CHROMA422;
2097 dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2098 dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift) * 8 + mb_y * s->uvlinesize * block_h;
2099 dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift) * 8 + mb_y * s->uvlinesize * block_h;
2101 s->dsp.prefetch(dest_y + (s->mb_x & 3) * 4 * s->linesize + (64 << pixel_shift), s->linesize, 4);
2102 s->dsp.prefetch(dest_cb + (s->mb_x & 7) * s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
2104 h->list_counts[mb_xy] = h->list_count;
2106 if (!simple && MB_FIELD) {
2107 linesize = h->mb_linesize = s->linesize * 2;
2108 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2109 block_offset = &h->block_offset[48];
2110 if (mb_y & 1) { // FIXME move out of this function?
2111 dest_y -= s->linesize * 15;
2112 dest_cb -= s->uvlinesize * (block_h - 1);
2113 dest_cr -= s->uvlinesize * (block_h - 1);
2117 for (list = 0; list < h->list_count; list++) {
2118 if (!USES_LIST(mb_type, list))
2120 if (IS_16X16(mb_type)) {
2121 int8_t *ref = &h->ref_cache[list][scan8[0]];
2122 fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (s->mb_y & 1), 1);
2124 for (i = 0; i < 16; i += 4) {
2125 int ref = h->ref_cache[list][scan8[i]];
2127 fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,
2128 8, (16 + ref) ^ (s->mb_y & 1), 1);
2134 linesize = h->mb_linesize = s->linesize;
2135 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2136 // dct_offset = s->linesize * 16;
2139 if (!simple && IS_INTRA_PCM(mb_type)) {
2141 const int bit_depth = h->sps.bit_depth_luma;
2144 init_get_bits(&gb, (uint8_t *)h->mb, 384 * bit_depth);
2146 for (i = 0; i < 16; i++) {
2147 uint16_t *tmp_y = (uint16_t *)(dest_y + i * linesize);
2148 for (j = 0; j < 16; j++)
2149 tmp_y[j] = get_bits(&gb, bit_depth);
2151 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2152 if (!h->sps.chroma_format_idc) {
2153 for (i = 0; i < block_h; i++) {
2154 uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);
2155 for (j = 0; j < 8; j++)
2156 tmp_cb[j] = 1 << (bit_depth - 1);
2158 for (i = 0; i < block_h; i++) {
2159 uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);
2160 for (j = 0; j < 8; j++)
2161 tmp_cr[j] = 1 << (bit_depth - 1);
2164 for (i = 0; i < block_h; i++) {
2165 uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);
2166 for (j = 0; j < 8; j++)
2167 tmp_cb[j] = get_bits(&gb, bit_depth);
2169 for (i = 0; i < block_h; i++) {
2170 uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);
2171 for (j = 0; j < 8; j++)
2172 tmp_cr[j] = get_bits(&gb, bit_depth);
2177 for (i = 0; i < 16; i++)
2178 memcpy(dest_y + i * linesize, h->mb + i * 8, 16);
2179 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2180 if (!h->sps.chroma_format_idc) {
2181 for (i = 0; i < block_h; i++) {
2182 memset(dest_cb + i * uvlinesize, 128, 8);
2183 memset(dest_cr + i * uvlinesize, 128, 8);
2186 for (i = 0; i < block_h; i++) {
2187 memcpy(dest_cb + i * uvlinesize, h->mb + 128 + i * 4, 8);
2188 memcpy(dest_cr + i * uvlinesize, h->mb + 160 + i * 4, 8);
2194 if (IS_INTRA(mb_type)) {
2195 if (h->deblocking_filter)
2196 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
2197 uvlinesize, 1, 0, simple, pixel_shift);
2199 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2200 h->hpc.pred8x8[h->chroma_pred_mode](dest_cb, uvlinesize);
2201 h->hpc.pred8x8[h->chroma_pred_mode](dest_cr, uvlinesize);
2204 hl_decode_mb_predict_luma(h, mb_type, is_h264, simple,
2205 transform_bypass, pixel_shift,
2206 block_offset, linesize, dest_y, 0);
2208 if (h->deblocking_filter)
2209 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
2210 uvlinesize, 0, 0, simple, pixel_shift);
2211 } else if (is_h264) {
2213 hl_motion_422(h, dest_y, dest_cb, dest_cr,
2214 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2215 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2216 h->h264dsp.weight_h264_pixels_tab,
2217 h->h264dsp.biweight_h264_pixels_tab,
2220 hl_motion_420(h, dest_y, dest_cb, dest_cr,
2221 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2222 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2223 h->h264dsp.weight_h264_pixels_tab,
2224 h->h264dsp.biweight_h264_pixels_tab,
2229 hl_decode_mb_idct_luma(h, mb_type, is_h264, simple, transform_bypass,
2230 pixel_shift, block_offset, linesize, dest_y, 0);
2232 if ((simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) &&
2234 uint8_t *dest[2] = { dest_cb, dest_cr };
2235 if (transform_bypass) {
2236 if (IS_INTRA(mb_type) && h->sps.profile_idc == 244 &&
2237 (h->chroma_pred_mode == VERT_PRED8x8 ||
2238 h->chroma_pred_mode == HOR_PRED8x8)) {
2239 h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0],
2241 h->mb + (16 * 16 * 1 << pixel_shift),
2243 h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1],
2245 h->mb + (16 * 16 * 2 << pixel_shift),
2248 idct_add = s->dsp.add_pixels4;
2249 for (j = 1; j < 3; j++) {
2250 for (i = j * 16; i < j * 16 + 4; i++)
2251 if (h->non_zero_count_cache[scan8[i]] ||
2252 dctcoef_get(h->mb, pixel_shift, i * 16))
2253 idct_add(dest[j - 1] + block_offset[i],
2254 h->mb + (i * 16 << pixel_shift),
2257 for (i = j * 16 + 4; i < j * 16 + 8; i++)
2258 if (h->non_zero_count_cache[scan8[i + 4]] ||
2259 dctcoef_get(h->mb, pixel_shift, i * 16))
2260 idct_add(dest[j - 1] + block_offset[i + 4],
2261 h->mb + (i * 16 << pixel_shift),
2270 qp[0] = h->chroma_qp[0] + 3;
2271 qp[1] = h->chroma_qp[1] + 3;
2273 qp[0] = h->chroma_qp[0];
2274 qp[1] = h->chroma_qp[1];
2276 if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 0]])
2277 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 1 << pixel_shift),
2278 h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][qp[0]][0]);
2279 if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 1]])
2280 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 2 << pixel_shift),
2281 h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][qp[1]][0]);
2282 h->h264dsp.h264_idct_add8(dest, block_offset,
2284 h->non_zero_count_cache);
2285 } else if (CONFIG_SVQ3_DECODER) {
2286 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 1,
2287 h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][h->chroma_qp[0]][0]);
2288 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 2,
2289 h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][h->chroma_qp[1]][0]);
2290 for (j = 1; j < 3; j++) {
2291 for (i = j * 16; i < j * 16 + 4; i++)
2292 if (h->non_zero_count_cache[scan8[i]] || h->mb[i * 16]) {
2293 uint8_t *const ptr = dest[j - 1] + block_offset[i];
2294 ff_svq3_add_idct_c(ptr, h->mb + i * 16,
2296 ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
2303 if (h->cbp || IS_INTRA(mb_type)) {
2304 s->dsp.clear_blocks(h->mb);
2305 s->dsp.clear_blocks(h->mb + (24 * 16 << pixel_shift));
2309 static av_always_inline void hl_decode_mb_444_internal(H264Context *h,
2313 MpegEncContext *const s = &h->s;
2314 const int mb_x = s->mb_x;
2315 const int mb_y = s->mb_y;
2316 const int mb_xy = h->mb_xy;
2317 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2321 int *block_offset = &h->block_offset[0];
2322 const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2323 const int plane_count = (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) ? 3 : 1;
2325 for (p = 0; p < plane_count; p++) {
2326 dest[p] = s->current_picture.f.data[p] +
2327 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2328 s->dsp.prefetch(dest[p] + (s->mb_x & 3) * 4 * s->linesize + (64 << pixel_shift),
2332 h->list_counts[mb_xy] = h->list_count;
2334 if (!simple && MB_FIELD) {
2335 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize * 2;
2336 block_offset = &h->block_offset[48];
2337 if (mb_y & 1) // FIXME move out of this function?
2338 for (p = 0; p < 3; p++)
2339 dest[p] -= s->linesize * 15;
2342 for (list = 0; list < h->list_count; list++) {
2343 if (!USES_LIST(mb_type, list))
2345 if (IS_16X16(mb_type)) {
2346 int8_t *ref = &h->ref_cache[list][scan8[0]];
2347 fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (s->mb_y & 1), 1);
2349 for (i = 0; i < 16; i += 4) {
2350 int ref = h->ref_cache[list][scan8[i]];
2352 fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,
2353 8, (16 + ref) ^ (s->mb_y & 1), 1);
2359 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize;
2362 if (!simple && IS_INTRA_PCM(mb_type)) {
2364 const int bit_depth = h->sps.bit_depth_luma;
2366 init_get_bits(&gb, (uint8_t *)h->mb, 768 * bit_depth);
2368 for (p = 0; p < plane_count; p++)
2369 for (i = 0; i < 16; i++) {
2370 uint16_t *tmp = (uint16_t *)(dest[p] + i * linesize);
2371 for (j = 0; j < 16; j++)
2372 tmp[j] = get_bits(&gb, bit_depth);
2375 for (p = 0; p < plane_count; p++)
2376 for (i = 0; i < 16; i++)
2377 memcpy(dest[p] + i * linesize, h->mb + p * 128 + i * 8, 16);
2380 if (IS_INTRA(mb_type)) {
2381 if (h->deblocking_filter)
2382 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,
2383 linesize, 1, 1, simple, pixel_shift);
2385 for (p = 0; p < plane_count; p++)
2386 hl_decode_mb_predict_luma(h, mb_type, 1, simple,
2387 transform_bypass, pixel_shift,
2388 block_offset, linesize, dest[p], p);
2390 if (h->deblocking_filter)
2391 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,
2392 linesize, 0, 1, simple, pixel_shift);
2394 hl_motion(h, dest[0], dest[1], dest[2],
2395 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2396 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2397 h->h264dsp.weight_h264_pixels_tab,
2398 h->h264dsp.biweight_h264_pixels_tab, pixel_shift, 3);
2401 for (p = 0; p < plane_count; p++)
2402 hl_decode_mb_idct_luma(h, mb_type, 1, simple, transform_bypass,
2403 pixel_shift, block_offset, linesize,
2406 if (h->cbp || IS_INTRA(mb_type)) {
2407 s->dsp.clear_blocks(h->mb);
2408 s->dsp.clear_blocks(h->mb + (24 * 16 << pixel_shift));
2413 * Process a macroblock; this case avoids checks for expensive uncommon cases.
2415 #define hl_decode_mb_simple(sh, bits) \
2416 static void hl_decode_mb_simple_ ## bits(H264Context *h) \
2418 hl_decode_mb_internal(h, 1, sh); \
2421 hl_decode_mb_simple(0, 8)
2422 hl_decode_mb_simple(1, 16)
2425 * Process a macroblock; this handles edge cases, such as interlacing.
2427 static void av_noinline hl_decode_mb_complex(H264Context *h)
2429 hl_decode_mb_internal(h, 0, h->pixel_shift);
2432 static void av_noinline hl_decode_mb_444_complex(H264Context *h)
2434 hl_decode_mb_444_internal(h, 0, h->pixel_shift);
2437 static void av_noinline hl_decode_mb_444_simple(H264Context *h)
2439 hl_decode_mb_444_internal(h, 1, 0);
2442 void ff_h264_hl_decode_mb(H264Context *h)
2444 MpegEncContext *const s = &h->s;
2445 const int mb_xy = h->mb_xy;
2446 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2447 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2450 if (is_complex || h->pixel_shift)
2451 hl_decode_mb_444_complex(h);
2453 hl_decode_mb_444_simple(h);
2454 } else if (is_complex) {
2455 hl_decode_mb_complex(h);
2456 } else if (h->pixel_shift) {
2457 hl_decode_mb_simple_16(h);
2459 hl_decode_mb_simple_8(h);
2462 static int pred_weight_table(H264Context *h)
2464 MpegEncContext *const s = &h->s;
2466 int luma_def, chroma_def;
2469 h->use_weight_chroma = 0;
2470 h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
2471 if (h->sps.chroma_format_idc)
2472 h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
2473 luma_def = 1 << h->luma_log2_weight_denom;
2474 chroma_def = 1 << h->chroma_log2_weight_denom;
2476 for (list = 0; list < 2; list++) {
2477 h->luma_weight_flag[list] = 0;
2478 h->chroma_weight_flag[list] = 0;
2479 for (i = 0; i < h->ref_count[list]; i++) {
2480 int luma_weight_flag, chroma_weight_flag;
2482 luma_weight_flag = get_bits1(&s->gb);
2483 if (luma_weight_flag) {
2484 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
2485 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
2486 if (h->luma_weight[i][list][0] != luma_def ||
2487 h->luma_weight[i][list][1] != 0) {
2489 h->luma_weight_flag[list] = 1;
2492 h->luma_weight[i][list][0] = luma_def;
2493 h->luma_weight[i][list][1] = 0;
2496 if (h->sps.chroma_format_idc) {
2497 chroma_weight_flag = get_bits1(&s->gb);
2498 if (chroma_weight_flag) {
2500 for (j = 0; j < 2; j++) {
2501 h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
2502 h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
2503 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2504 h->chroma_weight[i][list][j][1] != 0) {
2505 h->use_weight_chroma = 1;
2506 h->chroma_weight_flag[list] = 1;
2511 for (j = 0; j < 2; j++) {
2512 h->chroma_weight[i][list][j][0] = chroma_def;
2513 h->chroma_weight[i][list][j][1] = 0;
2518 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2521 h->use_weight = h->use_weight || h->use_weight_chroma;
2526 * Initialize implicit_weight table.
2527 * @param field 0/1 initialize the weight for interlaced MBAFF
2528 * -1 initializes the rest
2530 static void implicit_weight_table(H264Context *h, int field)
2532 MpegEncContext *const s = &h->s;
2533 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2535 for (i = 0; i < 2; i++) {
2536 h->luma_weight_flag[i] = 0;
2537 h->chroma_weight_flag[i] = 0;
2541 if (s->picture_structure == PICT_FRAME) {
2542 cur_poc = s->current_picture_ptr->poc;
2544 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2546 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2547 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2549 h->use_weight_chroma = 0;
2553 ref_count0 = h->ref_count[0];
2554 ref_count1 = h->ref_count[1];
2556 cur_poc = s->current_picture_ptr->field_poc[field];
2558 ref_count0 = 16 + 2 * h->ref_count[0];
2559 ref_count1 = 16 + 2 * h->ref_count[1];
2563 h->use_weight_chroma = 2;
2564 h->luma_log2_weight_denom = 5;
2565 h->chroma_log2_weight_denom = 5;
2567 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2568 int poc0 = h->ref_list[0][ref0].poc;
2569 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2571 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2572 int poc1 = h->ref_list[1][ref1].poc;
2573 int td = av_clip(poc1 - poc0, -128, 127);
2575 int tb = av_clip(cur_poc - poc0, -128, 127);
2576 int tx = (16384 + (FFABS(td) >> 1)) / td;
2577 int dist_scale_factor = (tb * tx + 32) >> 8;
2578 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2579 w = 64 - dist_scale_factor;
2583 h->implicit_weight[ref0][ref1][0] =
2584 h->implicit_weight[ref0][ref1][1] = w;
2586 h->implicit_weight[ref0][ref1][field] = w;
2593 * instantaneous decoder refresh.
2595 static void idr(H264Context *h)
2597 ff_h264_remove_all_refs(h);
2598 h->prev_frame_num = 0;
2599 h->prev_frame_num_offset = 0;
2601 h->prev_poc_lsb = 0;
2604 /* forget old pics after a seek */
2605 static void flush_dpb(AVCodecContext *avctx)
2607 H264Context *h = avctx->priv_data;
2609 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2610 if (h->delayed_pic[i])
2611 h->delayed_pic[i]->f.reference = 0;
2612 h->delayed_pic[i] = NULL;
2614 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2615 h->last_pocs[i] = INT_MIN;
2616 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2617 h->prev_interlaced_frame = 1;
2619 if (h->s.current_picture_ptr)
2620 h->s.current_picture_ptr->f.reference = 0;
2621 h->s.first_field = 0;
2622 ff_h264_reset_sei(h);
2623 ff_mpeg_flush(avctx);
2626 static int init_poc(H264Context *h)
2628 MpegEncContext *const s = &h->s;
2629 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2631 Picture *cur = s->current_picture_ptr;
2633 h->frame_num_offset = h->prev_frame_num_offset;
2634 if (h->frame_num < h->prev_frame_num)
2635 h->frame_num_offset += max_frame_num;
2637 if (h->sps.poc_type == 0) {
2638 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2640 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2641 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2642 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2643 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2645 h->poc_msb = h->prev_poc_msb;
2646 // printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2648 field_poc[1] = h->poc_msb + h->poc_lsb;
2649 if (s->picture_structure == PICT_FRAME)
2650 field_poc[1] += h->delta_poc_bottom;
2651 } else if (h->sps.poc_type == 1) {
2652 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2655 if (h->sps.poc_cycle_length != 0)
2656 abs_frame_num = h->frame_num_offset + h->frame_num;
2660 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2663 expected_delta_per_poc_cycle = 0;
2664 for (i = 0; i < h->sps.poc_cycle_length; i++)
2665 // FIXME integrate during sps parse
2666 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2668 if (abs_frame_num > 0) {
2669 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2670 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2672 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2673 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2674 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2678 if (h->nal_ref_idc == 0)
2679 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2681 field_poc[0] = expectedpoc + h->delta_poc[0];
2682 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2684 if (s->picture_structure == PICT_FRAME)
2685 field_poc[1] += h->delta_poc[1];
2687 int poc = 2 * (h->frame_num_offset + h->frame_num);
2689 if (!h->nal_ref_idc)
2696 if (s->picture_structure != PICT_BOTTOM_FIELD)
2697 s->current_picture_ptr->field_poc[0] = field_poc[0];
2698 if (s->picture_structure != PICT_TOP_FIELD)
2699 s->current_picture_ptr->field_poc[1] = field_poc[1];
2700 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2706 * initialize scan tables
2708 static void init_scan_tables(H264Context *h)
2711 for (i = 0; i < 16; i++) {
2712 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2713 h->zigzag_scan[i] = T(zigzag_scan[i]);
2714 h->field_scan[i] = T(field_scan[i]);
2717 for (i = 0; i < 64; i++) {
2718 #define T(x) (x >> 3) | ((x & 7) << 3)
2719 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2720 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2721 h->field_scan8x8[i] = T(field_scan8x8[i]);
2722 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2725 if (h->sps.transform_bypass) { // FIXME same ugly
2726 h->zigzag_scan_q0 = zigzag_scan;
2727 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2728 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2729 h->field_scan_q0 = field_scan;
2730 h->field_scan8x8_q0 = field_scan8x8;
2731 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2733 h->zigzag_scan_q0 = h->zigzag_scan;
2734 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2735 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2736 h->field_scan_q0 = h->field_scan;
2737 h->field_scan8x8_q0 = h->field_scan8x8;
2738 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2742 static int field_end(H264Context *h, int in_setup)
2744 MpegEncContext *const s = &h->s;
2745 AVCodecContext *const avctx = s->avctx;
2749 if (!in_setup && !s->dropable)
2750 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2751 s->picture_structure == PICT_BOTTOM_FIELD);
2753 if (CONFIG_H264_VDPAU_DECODER &&
2754 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2755 ff_vdpau_h264_set_reference_frames(s);
2757 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2759 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2760 h->prev_poc_msb = h->poc_msb;
2761 h->prev_poc_lsb = h->poc_lsb;
2763 h->prev_frame_num_offset = h->frame_num_offset;
2764 h->prev_frame_num = h->frame_num;
2765 h->outputed_poc = h->next_outputed_poc;
2768 if (avctx->hwaccel) {
2769 if (avctx->hwaccel->end_frame(avctx) < 0)
2770 av_log(avctx, AV_LOG_ERROR,
2771 "hardware accelerator failed to decode picture\n");
2774 if (CONFIG_H264_VDPAU_DECODER &&
2775 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2776 ff_vdpau_h264_picture_complete(s);
2779 * FIXME: Error handling code does not seem to support interlaced
2780 * when slices span multiple rows
2781 * The ff_er_add_slice calls don't work right for bottom
2782 * fields; they cause massive erroneous error concealing
2783 * Error marking covers both fields (top and bottom).
2784 * This causes a mismatched s->error_count
2785 * and a bad error table. Further, the error count goes to
2786 * INT_MAX when called for bottom field, because mb_y is
2787 * past end by one (callers fault) and resync_mb_y != 0
2788 * causes problems for the first MB line, too.
2793 ff_MPV_frame_end(s);
2795 h->current_slice = 0;
2801 * Replicate H264 "master" context to thread contexts.
2803 static void clone_slice(H264Context *dst, H264Context *src)
2805 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2806 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2807 dst->s.current_picture = src->s.current_picture;
2808 dst->s.linesize = src->s.linesize;
2809 dst->s.uvlinesize = src->s.uvlinesize;
2810 dst->s.first_field = src->s.first_field;
2812 dst->prev_poc_msb = src->prev_poc_msb;
2813 dst->prev_poc_lsb = src->prev_poc_lsb;
2814 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2815 dst->prev_frame_num = src->prev_frame_num;
2816 dst->short_ref_count = src->short_ref_count;
2818 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2819 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2820 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2821 memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
2823 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2824 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2828 * Compute profile from profile_idc and constraint_set?_flags.
2832 * @return profile as defined by FF_PROFILE_H264_*
2834 int ff_h264_get_profile(SPS *sps)
2836 int profile = sps->profile_idc;
2838 switch (sps->profile_idc) {
2839 case FF_PROFILE_H264_BASELINE:
2840 // constraint_set1_flag set to 1
2841 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2843 case FF_PROFILE_H264_HIGH_10:
2844 case FF_PROFILE_H264_HIGH_422:
2845 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2846 // constraint_set3_flag set to 1
2847 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2855 * Decode a slice header.
2856 * This will also call ff_MPV_common_init() and frame_start() as needed.
2858 * @param h h264context
2859 * @param h0 h264 master context (differs from 'h' when doing sliced based
2860 * parallel decoding)
2862 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2864 static int decode_slice_header(H264Context *h, H264Context *h0)
2866 MpegEncContext *const s = &h->s;
2867 MpegEncContext *const s0 = &h0->s;
2868 unsigned int first_mb_in_slice;
2869 unsigned int pps_id;
2870 int num_ref_idx_active_override_flag;
2871 unsigned int slice_type, tmp, i, j;
2872 int default_ref_list_done = 0;
2873 int last_pic_structure, last_pic_dropable;
2875 /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2876 if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
2877 !h->nal_ref_idc && !h->pixel_shift) {
2878 s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
2879 s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
2881 s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
2882 s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
2885 first_mb_in_slice = get_ue_golomb(&s->gb);
2887 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2888 if (h0->current_slice && FIELD_PICTURE) {
2892 h0->current_slice = 0;
2893 if (!s0->first_field) {
2894 if (s->current_picture_ptr && !s->dropable &&
2895 s->current_picture_ptr->owner2 == s) {
2896 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2897 s->picture_structure == PICT_BOTTOM_FIELD);
2899 s->current_picture_ptr = NULL;
2903 slice_type = get_ue_golomb_31(&s->gb);
2904 if (slice_type > 9) {
2905 av_log(h->s.avctx, AV_LOG_ERROR,
2906 "slice type too large (%d) at %d %d\n",
2907 h->slice_type, s->mb_x, s->mb_y);
2910 if (slice_type > 4) {
2912 h->slice_type_fixed = 1;
2914 h->slice_type_fixed = 0;
2916 slice_type = golomb_to_pict_type[slice_type];
2917 if (slice_type == AV_PICTURE_TYPE_I ||
2918 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2919 default_ref_list_done = 1;
2921 h->slice_type = slice_type;
2922 h->slice_type_nos = slice_type & 3;
2924 // to make a few old functions happy, it's wrong though
2925 s->pict_type = h->slice_type;
2927 pps_id = get_ue_golomb(&s->gb);
2928 if (pps_id >= MAX_PPS_COUNT) {
2929 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2932 if (!h0->pps_buffers[pps_id]) {
2933 av_log(h->s.avctx, AV_LOG_ERROR,
2934 "non-existing PPS %u referenced\n",
2938 h->pps = *h0->pps_buffers[pps_id];
2940 if (!h0->sps_buffers[h->pps.sps_id]) {
2941 av_log(h->s.avctx, AV_LOG_ERROR,
2942 "non-existing SPS %u referenced\n",
2946 h->sps = *h0->sps_buffers[h->pps.sps_id];
2948 s->avctx->profile = ff_h264_get_profile(&h->sps);
2949 s->avctx->level = h->sps.level_idc;
2950 s->avctx->refs = h->sps.ref_frame_count;
2952 s->mb_width = h->sps.mb_width;
2953 s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2955 h->b_stride = s->mb_width * 4;
2957 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2959 s->width = 16 * s->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
2960 if (h->sps.frame_mbs_only_flag)
2961 s->height = 16 * s->mb_height - (1 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2963 s->height = 16 * s->mb_height - (2 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2965 if (s->context_initialized &&
2966 (s->width != s->avctx->width || s->height != s->avctx->height ||
2967 av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2969 av_log_missing_feature(s->avctx,
2970 "Width/height changing with threads is", 0);
2971 return -1; // width / height changed during parallelized decoding
2974 flush_dpb(s->avctx);
2975 ff_MPV_common_end(s);
2977 if (!s->context_initialized) {
2979 av_log(h->s.avctx, AV_LOG_ERROR,
2980 "Cannot (re-)initialize context during parallel decoding.\n");
2984 avcodec_set_dimensions(s->avctx, s->width, s->height);
2985 s->avctx->sample_aspect_ratio = h->sps.sar;
2986 av_assert0(s->avctx->sample_aspect_ratio.den);
2988 if (h->sps.video_signal_type_present_flag) {
2989 s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
2991 if (h->sps.colour_description_present_flag) {
2992 s->avctx->color_primaries = h->sps.color_primaries;
2993 s->avctx->color_trc = h->sps.color_trc;
2994 s->avctx->colorspace = h->sps.colorspace;
2998 if (h->sps.timing_info_present_flag) {
2999 int64_t den = h->sps.time_scale;
3000 if (h->x264_build < 44U)
3002 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
3003 h->sps.num_units_in_tick, den, 1 << 30);
3006 switch (h->sps.bit_depth_luma) {
3009 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3010 s->avctx->pix_fmt = PIX_FMT_GBRP9;
3012 s->avctx->pix_fmt = PIX_FMT_YUV444P9;
3013 } else if (CHROMA422)
3014 s->avctx->pix_fmt = PIX_FMT_YUV422P9;
3016 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
3020 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3021 s->avctx->pix_fmt = PIX_FMT_GBRP10;
3023 s->avctx->pix_fmt = PIX_FMT_YUV444P10;
3024 } else if (CHROMA422)
3025 s->avctx->pix_fmt = PIX_FMT_YUV422P10;
3027 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
3031 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3032 s->avctx->pix_fmt = PIX_FMT_GBRP;
3034 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P
3036 } else if (CHROMA422) {
3037 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P
3040 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
3041 s->avctx->codec->pix_fmts ?
3042 s->avctx->codec->pix_fmts :
3043 s->avctx->color_range == AVCOL_RANGE_JPEG ?
3044 hwaccel_pixfmt_list_h264_jpeg_420 :
3045 ff_hwaccel_pixfmt_list_420);
3049 av_log(s->avctx, AV_LOG_ERROR,
3050 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3051 return AVERROR_INVALIDDATA;
3054 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
3057 if (ff_MPV_common_init(s) < 0) {
3058 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
3062 h->prev_interlaced_frame = 1;
3064 init_scan_tables(h);
3065 if (ff_h264_alloc_tables(h) < 0) {
3066 av_log(h->s.avctx, AV_LOG_ERROR,
3067 "Could not allocate memory for h264\n");
3068 return AVERROR(ENOMEM);
3071 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
3072 if (context_init(h) < 0) {
3073 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
3077 for (i = 1; i < s->slice_context_count; i++) {
3079 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
3080 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
3081 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
3082 c->h264dsp = h->h264dsp;
3085 c->pixel_shift = h->pixel_shift;
3086 init_scan_tables(c);
3087 clone_tables(c, h, i);
3090 for (i = 0; i < s->slice_context_count; i++)
3091 if (context_init(h->thread_context[i]) < 0) {
3092 av_log(h->s.avctx, AV_LOG_ERROR,
3093 "context_init() failed.\n");
3099 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3100 h->dequant_coeff_pps = pps_id;
3101 init_dequant_tables(h);
3104 h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
3107 h->mb_aff_frame = 0;
3108 last_pic_structure = s0->picture_structure;
3109 last_pic_dropable = s->dropable;
3110 s->dropable = h->nal_ref_idc == 0;
3111 if (h->sps.frame_mbs_only_flag) {
3112 s->picture_structure = PICT_FRAME;
3114 if (get_bits1(&s->gb)) { // field_pic_flag
3115 s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
3117 s->picture_structure = PICT_FRAME;
3118 h->mb_aff_frame = h->sps.mb_aff;
3121 h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
3123 if (h0->current_slice != 0) {
3124 if (last_pic_structure != s->picture_structure ||
3125 last_pic_dropable != s->dropable) {
3126 av_log(h->s.avctx, AV_LOG_ERROR,
3127 "Changing field mode (%d -> %d) between slices is not allowed\n",
3128 last_pic_structure, s->picture_structure);
3129 s->picture_structure = last_pic_structure;
3130 s->dropable = last_pic_dropable;
3131 return AVERROR_INVALIDDATA;
3134 /* Shorten frame num gaps so we don't have to allocate reference
3135 * frames just to throw them away */
3136 if (h->frame_num != h->prev_frame_num) {
3137 int unwrap_prev_frame_num = h->prev_frame_num;
3138 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3140 if (unwrap_prev_frame_num > h->frame_num)
3141 unwrap_prev_frame_num -= max_frame_num;
3143 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3144 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3145 if (unwrap_prev_frame_num < 0)
3146 unwrap_prev_frame_num += max_frame_num;
3148 h->prev_frame_num = unwrap_prev_frame_num;
3152 /* See if we have a decoded first field looking for a pair...
3153 * Here, we're using that to see if we should mark previously
3154 * decode frames as "finished".
3155 * We have to do that before the "dummy" in-between frame allocation,
3156 * since that can modify s->current_picture_ptr. */
3157 if (s0->first_field) {
3158 assert(s0->current_picture_ptr);
3159 assert(s0->current_picture_ptr->f.data[0]);
3160 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
3162 /* Mark old field/frame as completed */
3163 if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
3164 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
3165 last_pic_structure == PICT_BOTTOM_FIELD);
3168 /* figure out if we have a complementary field pair */
3169 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3170 /* Previous field is unmatched. Don't display it, but let it
3171 * remain for reference if marked as such. */
3172 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
3173 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
3174 last_pic_structure == PICT_TOP_FIELD);
3177 if (s0->current_picture_ptr->frame_num != h->frame_num) {
3178 /* This and previous field were reference, but had
3179 * different frame_nums. Consider this field first in
3180 * pair. Throw away previous field except for reference
3182 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
3183 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
3184 last_pic_structure == PICT_TOP_FIELD);
3187 /* Second field in complementary pair */
3188 if (!((last_pic_structure == PICT_TOP_FIELD &&
3189 s->picture_structure == PICT_BOTTOM_FIELD) ||
3190 (last_pic_structure == PICT_BOTTOM_FIELD &&
3191 s->picture_structure == PICT_TOP_FIELD))) {
3192 av_log(s->avctx, AV_LOG_ERROR,
3193 "Invalid field mode combination %d/%d\n",
3194 last_pic_structure, s->picture_structure);
3195 s->picture_structure = last_pic_structure;
3196 s->dropable = last_pic_dropable;
3197 return AVERROR_INVALIDDATA;
3198 } else if (last_pic_dropable != s->dropable) {
3199 av_log(s->avctx, AV_LOG_ERROR,
3200 "Cannot combine reference and non-reference fields in the same frame\n");
3201 av_log_ask_for_sample(s->avctx, NULL);
3202 s->picture_structure = last_pic_structure;
3203 s->dropable = last_pic_dropable;
3204 return AVERROR_INVALIDDATA;
3207 /* Take ownership of this buffer. Note that if another thread owned
3208 * the first field of this buffer, we're not operating on that pointer,
3209 * so the original thread is still responsible for reporting progress
3210 * on that first field (or if that was us, we just did that above).
3211 * By taking ownership, we assign responsibility to ourselves to
3212 * report progress on the second field. */
3213 s0->current_picture_ptr->owner2 = s0;
3218 while (h->frame_num != h->prev_frame_num &&
3219 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3220 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3221 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3222 h->frame_num, h->prev_frame_num);
3223 if (ff_h264_frame_start(h) < 0)
3225 h->prev_frame_num++;
3226 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3227 s->current_picture_ptr->frame_num = h->prev_frame_num;
3228 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
3229 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
3230 ff_generate_sliding_window_mmcos(h);
3231 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3232 (s->avctx->err_recognition & AV_EF_EXPLODE))
3233 return AVERROR_INVALIDDATA;
3234 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3235 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3236 * about there being no actual duplicates.
3237 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3238 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3240 if (h->short_ref_count) {
3242 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3243 (const uint8_t **)prev->f.data, prev->f.linesize,
3244 s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
3245 h->short_ref[0]->poc = prev->poc + 2;
3247 h->short_ref[0]->frame_num = h->prev_frame_num;
3251 /* See if we have a decoded first field looking for a pair...
3252 * We're using that to see whether to continue decoding in that
3253 * frame, or to allocate a new one. */
3254 if (s0->first_field) {
3255 assert(s0->current_picture_ptr);
3256 assert(s0->current_picture_ptr->f.data[0]);
3257 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
3259 /* figure out if we have a complementary field pair */
3260 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3261 /* Previous field is unmatched. Don't display it, but let it
3262 * remain for reference if marked as such. */
3263 s0->current_picture_ptr = NULL;
3264 s0->first_field = FIELD_PICTURE;
3266 if (s0->current_picture_ptr->frame_num != h->frame_num) {
3267 /* This and the previous field had different frame_nums.
3268 * Consider this field first in pair. Throw away previous
3269 * one except for reference purposes. */
3270 s0->first_field = 1;
3271 s0->current_picture_ptr = NULL;
3273 /* Second field in complementary pair */
3274 s0->first_field = 0;
3278 /* Frame or first field in a potentially complementary pair */
3279 assert(!s0->current_picture_ptr);
3280 s0->first_field = FIELD_PICTURE;
3283 if (!FIELD_PICTURE || s0->first_field) {
3284 if (ff_h264_frame_start(h) < 0) {
3285 s0->first_field = 0;
3289 ff_release_unused_pictures(s, 0);
3295 s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3297 assert(s->mb_num == s->mb_width * s->mb_height);
3298 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
3299 first_mb_in_slice >= s->mb_num) {
3300 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3303 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3304 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3305 if (s->picture_structure == PICT_BOTTOM_FIELD)
3306 s->resync_mb_y = s->mb_y = s->mb_y + 1;
3307 assert(s->mb_y < s->mb_height);
3309 if (s->picture_structure == PICT_FRAME) {
3310 h->curr_pic_num = h->frame_num;
3311 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3313 h->curr_pic_num = 2 * h->frame_num + 1;
3314 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3317 if (h->nal_unit_type == NAL_IDR_SLICE)
3318 get_ue_golomb(&s->gb); /* idr_pic_id */
3320 if (h->sps.poc_type == 0) {
3321 h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3323 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3324 h->delta_poc_bottom = get_se_golomb(&s->gb);
3327 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3328 h->delta_poc[0] = get_se_golomb(&s->gb);
3330 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3331 h->delta_poc[1] = get_se_golomb(&s->gb);
3336 if (h->pps.redundant_pic_cnt_present)
3337 h->redundant_pic_count = get_ue_golomb(&s->gb);
3339 // set defaults, might be overridden a few lines later
3340 h->ref_count[0] = h->pps.ref_count[0];
3341 h->ref_count[1] = h->pps.ref_count[1];
3343 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3344 int max_refs = s->picture_structure == PICT_FRAME ? 16 : 32;
3346 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3347 h->direct_spatial_mv_pred = get_bits1(&s->gb);
3348 num_ref_idx_active_override_flag = get_bits1(&s->gb);
3350 if (num_ref_idx_active_override_flag) {
3351 h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
3352 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3353 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
3356 if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
3357 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3358 h->ref_count[0] = h->ref_count[1] = 1;
3359 return AVERROR_INVALIDDATA;
3362 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3369 if (!default_ref_list_done)
3370 ff_h264_fill_default_ref_list(h);
3372 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
3373 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3374 h->ref_count[1] = h->ref_count[0] = 0;
3378 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3379 s->last_picture_ptr = &h->ref_list[0][0];
3380 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3382 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3383 s->next_picture_ptr = &h->ref_list[1][0];
3384 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3387 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3388 (h->pps.weighted_bipred_idc == 1 &&
3389 h->slice_type_nos == AV_PICTURE_TYPE_B))
3390 pred_weight_table(h);
3391 else if (h->pps.weighted_bipred_idc == 2 &&
3392 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3393 implicit_weight_table(h, -1);
3396 for (i = 0; i < 2; i++) {
3397 h->luma_weight_flag[i] = 0;
3398 h->chroma_weight_flag[i] = 0;
3402 if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
3403 (s->avctx->err_recognition & AV_EF_EXPLODE))
3404 return AVERROR_INVALIDDATA;
3407 ff_h264_fill_mbaff_ref_list(h);
3409 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3410 implicit_weight_table(h, 0);
3411 implicit_weight_table(h, 1);
3415 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3416 ff_h264_direct_dist_scale_factor(h);
3417 ff_h264_direct_ref_list_init(h);
3419 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3420 tmp = get_ue_golomb_31(&s->gb);
3422 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3425 h->cabac_init_idc = tmp;
3428 h->last_qscale_diff = 0;
3429 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3430 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3431 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3435 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3436 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3437 // FIXME qscale / qp ... stuff
3438 if (h->slice_type == AV_PICTURE_TYPE_SP)
3439 get_bits1(&s->gb); /* sp_for_switch_flag */
3440 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3441 h->slice_type == AV_PICTURE_TYPE_SI)
3442 get_se_golomb(&s->gb); /* slice_qs_delta */
3444 h->deblocking_filter = 1;
3445 h->slice_alpha_c0_offset = 52;
3446 h->slice_beta_offset = 52;
3447 if (h->pps.deblocking_filter_parameters_present) {
3448 tmp = get_ue_golomb_31(&s->gb);
3450 av_log(s->avctx, AV_LOG_ERROR,
3451 "deblocking_filter_idc %u out of range\n", tmp);
3454 h->deblocking_filter = tmp;
3455 if (h->deblocking_filter < 2)
3456 h->deblocking_filter ^= 1; // 1<->0
3458 if (h->deblocking_filter) {
3459 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3460 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3461 if (h->slice_alpha_c0_offset > 104U ||
3462 h->slice_beta_offset > 104U) {
3463 av_log(s->avctx, AV_LOG_ERROR,
3464 "deblocking filter parameters %d %d out of range\n",
3465 h->slice_alpha_c0_offset, h->slice_beta_offset);
3471 if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3472 (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3473 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3474 (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3475 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3476 (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3477 h->nal_ref_idc == 0))
3478 h->deblocking_filter = 0;
3480 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3481 if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3482 /* Cheat slightly for speed:
3483 * Do not bother to deblock across slices. */
3484 h->deblocking_filter = 2;
3486 h0->max_contexts = 1;
3487 if (!h0->single_decode_warning) {
3488 av_log(s->avctx, AV_LOG_INFO,
3489 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3490 h0->single_decode_warning = 1;
3493 av_log(h->s.avctx, AV_LOG_ERROR,
3494 "Deblocking switched inside frame.\n");
3499 h->qp_thresh = 15 + 52 -
3500 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3502 h->pps.chroma_qp_index_offset[0],
3503 h->pps.chroma_qp_index_offset[1]) +
3504 6 * (h->sps.bit_depth_luma - 8);
3506 h0->last_slice_type = slice_type;
3507 h->slice_num = ++h0->current_slice;
3508 if (h->slice_num >= MAX_SLICES) {
3509 av_log(s->avctx, AV_LOG_ERROR,
3510 "Too many slices, increase MAX_SLICES and recompile\n");
3513 for (j = 0; j < 2; j++) {
3515 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3516 for (i = 0; i < 16; i++) {
3518 if (h->ref_list[j][i].f.data[0]) {
3520 uint8_t *base = h->ref_list[j][i].f.base[0];
3521 for (k = 0; k < h->short_ref_count; k++)
3522 if (h->short_ref[k]->f.base[0] == base) {
3526 for (k = 0; k < h->long_ref_count; k++)
3527 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3528 id_list[i] = h->short_ref_count + k;
3536 for (i = 0; i < 16; i++)
3537 ref2frm[i + 2] = 4 * id_list[i] +
3538 (h->ref_list[j][i].f.reference & 3);
3540 ref2frm[18 + 1] = -1;
3541 for (i = 16; i < 48; i++)
3542 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3543 (h->ref_list[j][i].f.reference & 3);
3546 // FIXME: fix draw_edges + PAFF + frame threads
3547 h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
3548 (!h->sps.frame_mbs_only_flag &&
3549 s->avctx->active_thread_type))
3551 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3553 if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3554 av_log(h->s.avctx, AV_LOG_DEBUG,
3555 "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
3557 (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3559 av_get_picture_type_char(h->slice_type),
3560 h->slice_type_fixed ? " fix" : "",
3561 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3562 pps_id, h->frame_num,
3563 s->current_picture_ptr->field_poc[0],
3564 s->current_picture_ptr->field_poc[1],
3565 h->ref_count[0], h->ref_count[1],
3567 h->deblocking_filter,
3568 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3570 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3571 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3577 int ff_h264_get_slice_type(const H264Context *h)
3579 switch (h->slice_type) {
3580 case AV_PICTURE_TYPE_P:
3582 case AV_PICTURE_TYPE_B:
3584 case AV_PICTURE_TYPE_I:
3586 case AV_PICTURE_TYPE_SP:
3588 case AV_PICTURE_TYPE_SI:
3595 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3596 MpegEncContext *const s,
3597 int mb_type, int top_xy,
3598 int left_xy[LEFT_MBS],
3600 int left_type[LEFT_MBS],
3601 int mb_xy, int list)
3603 int b_stride = h->b_stride;
3604 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3605 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3606 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3607 if (USES_LIST(top_type, list)) {
3608 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3609 const int b8_xy = 4 * top_xy + 2;
3610 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3611 AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
3612 ref_cache[0 - 1 * 8] =
3613 ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3614 ref_cache[2 - 1 * 8] =
3615 ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3617 AV_ZERO128(mv_dst - 1 * 8);
3618 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3621 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3622 if (USES_LIST(left_type[LTOP], list)) {
3623 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3624 const int b8_xy = 4 * left_xy[LTOP] + 1;
3625 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3626 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
3627 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
3628 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
3629 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
3631 ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
3632 ref_cache[-1 + 16] =
3633 ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
3635 AV_ZERO32(mv_dst - 1 + 0);
3636 AV_ZERO32(mv_dst - 1 + 8);
3637 AV_ZERO32(mv_dst - 1 + 16);
3638 AV_ZERO32(mv_dst - 1 + 24);
3641 ref_cache[-1 + 16] =
3642 ref_cache[-1 + 24] = LIST_NOT_USED;
3647 if (!USES_LIST(mb_type, list)) {
3648 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3649 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3650 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3651 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3652 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3657 int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
3658 int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3659 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3660 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3661 AV_WN32A(&ref_cache[0 * 8], ref01);
3662 AV_WN32A(&ref_cache[1 * 8], ref01);
3663 AV_WN32A(&ref_cache[2 * 8], ref23);
3664 AV_WN32A(&ref_cache[3 * 8], ref23);
3668 int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
3669 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3670 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3671 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3672 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3678 * @return non zero if the loop filter can be skipped
3680 static int fill_filter_caches(H264Context *h, int mb_type)
3682 MpegEncContext *const s = &h->s;
3683 const int mb_xy = h->mb_xy;
3684 int top_xy, left_xy[LEFT_MBS];
3685 int top_type, left_type[LEFT_MBS];
3689 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3691 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3692 * stuff, I can't imagine that these complex rules are worth it. */
3694 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3696 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3697 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3699 if (left_mb_field_flag != curr_mb_field_flag)
3700 left_xy[LTOP] -= s->mb_stride;
3702 if (curr_mb_field_flag)
3703 top_xy += s->mb_stride &
3704 (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3705 if (left_mb_field_flag != curr_mb_field_flag)
3706 left_xy[LBOT] += s->mb_stride;
3710 h->top_mb_xy = top_xy;
3711 h->left_mb_xy[LTOP] = left_xy[LTOP];
3712 h->left_mb_xy[LBOT] = left_xy[LBOT];
3714 /* For sufficiently low qp, filtering wouldn't do anything.
3715 * This is a conservative estimate: could also check beta_offset
3716 * and more accurate chroma_qp. */
3717 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3718 int qp = s->current_picture.f.qscale_table[mb_xy];
3719 if (qp <= qp_thresh &&
3720 (left_xy[LTOP] < 0 ||
3721 ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3723 ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3726 if ((left_xy[LTOP] < 0 ||
3727 ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3728 (top_xy < s->mb_stride ||
3729 ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3734 top_type = s->current_picture.f.mb_type[top_xy];
3735 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3736 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3737 if (h->deblocking_filter == 2) {
3738 if (h->slice_table[top_xy] != h->slice_num)
3740 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3741 left_type[LTOP] = left_type[LBOT] = 0;
3743 if (h->slice_table[top_xy] == 0xFFFF)
3745 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3746 left_type[LTOP] = left_type[LBOT] = 0;
3748 h->top_type = top_type;
3749 h->left_type[LTOP] = left_type[LTOP];
3750 h->left_type[LBOT] = left_type[LBOT];
3752 if (IS_INTRA(mb_type))
3755 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3756 top_type, left_type, mb_xy, 0);
3757 if (h->list_count == 2)
3758 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3759 top_type, left_type, mb_xy, 1);
3761 nnz = h->non_zero_count[mb_xy];
3762 nnz_cache = h->non_zero_count_cache;
3763 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3764 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3765 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3766 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3767 h->cbp = h->cbp_table[mb_xy];
3770 nnz = h->non_zero_count[top_xy];
3771 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3774 if (left_type[LTOP]) {
3775 nnz = h->non_zero_count[left_xy[LTOP]];
3776 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3777 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3778 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3779 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3782 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3783 * from what the loop filter needs */
3784 if (!CABAC && h->pps.transform_8x8_mode) {
3785 if (IS_8x8DCT(top_type)) {
3786 nnz_cache[4 + 8 * 0] =
3787 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3788 nnz_cache[6 + 8 * 0] =
3789 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3791 if (IS_8x8DCT(left_type[LTOP])) {
3792 nnz_cache[3 + 8 * 1] =
3793 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3795 if (IS_8x8DCT(left_type[LBOT])) {
3796 nnz_cache[3 + 8 * 3] =
3797 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3800 if (IS_8x8DCT(mb_type)) {
3801 nnz_cache[scan8[0]] =
3802 nnz_cache[scan8[1]] =
3803 nnz_cache[scan8[2]] =
3804 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3806 nnz_cache[scan8[0 + 4]] =
3807 nnz_cache[scan8[1 + 4]] =
3808 nnz_cache[scan8[2 + 4]] =
3809 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3811 nnz_cache[scan8[0 + 8]] =
3812 nnz_cache[scan8[1 + 8]] =
3813 nnz_cache[scan8[2 + 8]] =
3814 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3816 nnz_cache[scan8[0 + 12]] =
3817 nnz_cache[scan8[1 + 12]] =
3818 nnz_cache[scan8[2 + 12]] =
3819 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3826 static void loop_filter(H264Context *h, int start_x, int end_x)
3828 MpegEncContext *const s = &h->s;
3829 uint8_t *dest_y, *dest_cb, *dest_cr;
3830 int linesize, uvlinesize, mb_x, mb_y;
3831 const int end_mb_y = s->mb_y + FRAME_MBAFF;
3832 const int old_slice_type = h->slice_type;
3833 const int pixel_shift = h->pixel_shift;
3834 const int block_h = 16 >> s->chroma_y_shift;
3836 if (h->deblocking_filter) {
3837 for (mb_x = start_x; mb_x < end_x; mb_x++)
3838 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
3840 mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
3841 h->slice_num = h->slice_table[mb_xy];
3842 mb_type = s->current_picture.f.mb_type[mb_xy];
3843 h->list_count = h->list_counts[mb_xy];
3847 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3851 dest_y = s->current_picture.f.data[0] +
3852 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
3853 dest_cb = s->current_picture.f.data[1] +
3854 (mb_x << pixel_shift) * (8 << CHROMA444) +
3855 mb_y * s->uvlinesize * block_h;
3856 dest_cr = s->current_picture.f.data[2] +
3857 (mb_x << pixel_shift) * (8 << CHROMA444) +
3858 mb_y * s->uvlinesize * block_h;
3859 // FIXME simplify above
3862 linesize = h->mb_linesize = s->linesize * 2;
3863 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3864 if (mb_y & 1) { // FIXME move out of this function?
3865 dest_y -= s->linesize * 15;
3866 dest_cb -= s->uvlinesize * (block_h - 1);
3867 dest_cr -= s->uvlinesize * (block_h - 1);
3870 linesize = h->mb_linesize = s->linesize;
3871 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3873 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
3875 if (fill_filter_caches(h, mb_type))
3877 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3878 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3881 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
3882 linesize, uvlinesize);
3884 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
3885 dest_cr, linesize, uvlinesize);
3889 h->slice_type = old_slice_type;
3891 s->mb_y = end_mb_y - FRAME_MBAFF;
3892 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3893 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3896 static void predict_field_decoding_flag(H264Context *h)
3898 MpegEncContext *const s = &h->s;
3899 const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
3900 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
3901 s->current_picture.f.mb_type[mb_xy - 1] :
3902 (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
3903 s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
3904 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3908 * Draw edges and report progress for the last MB row.
3910 static void decode_finish_row(H264Context *h)
3912 MpegEncContext *const s = &h->s;
3913 int top = 16 * (s->mb_y >> FIELD_PICTURE);
3914 int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
3915 int height = 16 << FRAME_MBAFF;
3916 int deblock_border = (16 + 4) << FRAME_MBAFF;
3918 if (h->deblocking_filter) {
3919 if ((top + height) >= pic_height)
3920 height += deblock_border;
3921 top -= deblock_border;
3924 if (top >= pic_height || (top + height) < h->emu_edge_height)
3927 height = FFMIN(height, pic_height - top);
3928 if (top < h->emu_edge_height) {
3929 height = top + height;
3933 ff_draw_horiz_band(s, top, height);
3938 ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
3939 s->picture_structure == PICT_BOTTOM_FIELD);
3942 static int decode_slice(struct AVCodecContext *avctx, void *arg)
3944 H264Context *h = *(void **)arg;
3945 MpegEncContext *const s = &h->s;
3946 const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
3948 int lf_x_start = s->mb_x;
3950 s->mb_skip_run = -1;
3952 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
3953 s->codec_id != CODEC_ID_H264 ||
3954 (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
3958 align_get_bits(&s->gb);
3961 ff_init_cabac_states(&h->cabac);
3962 ff_init_cabac_decoder(&h->cabac,
3963 s->gb.buffer + get_bits_count(&s->gb) / 8,
3964 (get_bits_left(&s->gb) + 7) / 8);
3966 ff_h264_init_cabac_states(h);
3970 int ret = ff_h264_decode_mb_cabac(h);
3972 // STOP_TIMER("decode_mb_cabac")
3975 ff_h264_hl_decode_mb(h);
3977 // FIXME optimal? or let mb_decode decode 16x32 ?
3978 if (ret >= 0 && FRAME_MBAFF) {
3981 ret = ff_h264_decode_mb_cabac(h);
3984 ff_h264_hl_decode_mb(h);
3987 eos = get_cabac_terminate(&h->cabac);
3989 if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
3990 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3991 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3992 s->mb_y, ER_MB_END & part_mask);
3993 if (s->mb_x >= lf_x_start)
3994 loop_filter(h, lf_x_start, s->mb_x + 1);
3997 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3998 av_log(h->s.avctx, AV_LOG_ERROR,
3999 "error while decoding MB %d %d, bytestream (%td)\n",
4001 h->cabac.bytestream_end - h->cabac.bytestream);
4002 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
4003 s->mb_y, ER_MB_ERROR & part_mask);
4007 if (++s->mb_x >= s->mb_width) {
4008 loop_filter(h, lf_x_start, s->mb_x);
4009 s->mb_x = lf_x_start = 0;
4010 decode_finish_row(h);
4012 if (FIELD_OR_MBAFF_PICTURE) {
4014 if (FRAME_MBAFF && s->mb_y < s->mb_height)
4015 predict_field_decoding_flag(h);
4019 if (eos || s->mb_y >= s->mb_height) {
4020 tprintf(s->avctx, "slice end %d %d\n",
4021 get_bits_count(&s->gb), s->gb.size_in_bits);
4022 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
4023 s->mb_y, ER_MB_END & part_mask);
4024 if (s->mb_x > lf_x_start)
4025 loop_filter(h, lf_x_start, s->mb_x);
4031 int ret = ff_h264_decode_mb_cavlc(h);
4034 ff_h264_hl_decode_mb(h);
4036 // FIXME optimal? or let mb_decode decode 16x32 ?
4037 if (ret >= 0 && FRAME_MBAFF) {
4039 ret = ff_h264_decode_mb_cavlc(h);
4042 ff_h264_hl_decode_mb(h);
4047 av_log(h->s.avctx, AV_LOG_ERROR,
4048 "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
4049 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
4050 s->mb_y, ER_MB_ERROR & part_mask);
4054 if (++s->mb_x >= s->mb_width) {
4055 loop_filter(h, lf_x_start, s->mb_x);
4056 s->mb_x = lf_x_start = 0;
4057 decode_finish_row(h);
4059 if (FIELD_OR_MBAFF_PICTURE) {
4061 if (FRAME_MBAFF && s->mb_y < s->mb_height)
4062 predict_field_decoding_flag(h);
4064 if (s->mb_y >= s->mb_height) {
4065 tprintf(s->avctx, "slice end %d %d\n",
4066 get_bits_count(&s->gb), s->gb.size_in_bits);
4068 if (get_bits_left(&s->gb) == 0) {
4069 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
4070 s->mb_x - 1, s->mb_y,
4071 ER_MB_END & part_mask);
4075 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
4077 ER_MB_END & part_mask);
4084 if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
4085 tprintf(s->avctx, "slice end %d %d\n",
4086 get_bits_count(&s->gb), s->gb.size_in_bits);
4087 if (get_bits_left(&s->gb) == 0) {
4088 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
4089 s->mb_x - 1, s->mb_y,
4090 ER_MB_END & part_mask);
4091 if (s->mb_x > lf_x_start)
4092 loop_filter(h, lf_x_start, s->mb_x);
4096 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
4097 s->mb_y, ER_MB_ERROR & part_mask);
4107 * Call decode_slice() for each context.
4109 * @param h h264 master context
4110 * @param context_count number of contexts to execute
4112 static int execute_decode_slices(H264Context *h, int context_count)
4114 MpegEncContext *const s = &h->s;
4115 AVCodecContext *const avctx = s->avctx;
4119 if (s->avctx->hwaccel ||
4120 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4122 if (context_count == 1) {
4123 return decode_slice(avctx, &h);
4125 for (i = 1; i < context_count; i++) {
4126 hx = h->thread_context[i];
4127 hx->s.err_recognition = avctx->err_recognition;
4128 hx->s.error_count = 0;
4131 avctx->execute(avctx, decode_slice, h->thread_context,
4132 NULL, context_count, sizeof(void *));
4134 /* pull back stuff from slices to master context */
4135 hx = h->thread_context[context_count - 1];
4136 s->mb_x = hx->s.mb_x;
4137 s->mb_y = hx->s.mb_y;
4138 s->dropable = hx->s.dropable;
4139 s->picture_structure = hx->s.picture_structure;
4140 for (i = 1; i < context_count; i++)
4141 h->s.error_count += h->thread_context[i]->s.error_count;
4147 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
4149 MpegEncContext *const s = &h->s;
4150 AVCodecContext *const avctx = s->avctx;
4151 H264Context *hx; ///< thread context
4155 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4156 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4159 h->max_contexts = s->slice_context_count;
4160 if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
4161 h->current_slice = 0;
4162 if (!s->first_field)
4163 s->current_picture_ptr = NULL;
4164 ff_h264_reset_sei(h);
4167 for (; pass <= 1; pass++) {
4170 next_avc = h->is_avc ? 0 : buf_size;
4180 if (buf_index >= next_avc) {
4181 if (buf_index >= buf_size - h->nal_length_size)
4184 for (i = 0; i < h->nal_length_size; i++)
4185 nalsize = (nalsize << 8) | buf[buf_index++];
4186 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4187 av_log(h->s.avctx, AV_LOG_ERROR,
4188 "AVC: nal size %d\n", nalsize);
4191 next_avc = buf_index + nalsize;
4193 // start code prefix search
4194 for (; buf_index + 3 < next_avc; buf_index++)
4195 // This should always succeed in the first iteration.
4196 if (buf[buf_index] == 0 &&
4197 buf[buf_index + 1] == 0 &&
4198 buf[buf_index + 2] == 1)
4201 if (buf_index + 3 >= buf_size)
4205 if (buf_index >= next_avc)
4209 hx = h->thread_context[context_count];
4211 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4212 &consumed, next_avc - buf_index);
4213 if (ptr == NULL || dst_length < 0) {
4217 i = buf_index + consumed;
4218 if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4219 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4220 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4221 s->workaround_bugs |= FF_BUG_TRUNCATED;
4223 if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
4224 while (ptr[dst_length - 1] == 0 && dst_length > 0)
4226 bit_length = !dst_length ? 0
4228 ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
4230 if (s->avctx->debug & FF_DEBUG_STARTCODE)
4231 av_log(h->s.avctx, AV_LOG_DEBUG,
4232 "NAL %d at %d/%d length %d\n",
4233 hx->nal_unit_type, buf_index, buf_size, dst_length);
4235 if (h->is_avc && (nalsize != consumed) && nalsize)
4236 av_log(h->s.avctx, AV_LOG_DEBUG,
4237 "AVC: Consumed only %d bytes instead of %d\n",
4240 buf_index += consumed;
4244 /* packets can sometimes contain multiple PPS/SPS,
4245 * e.g. two PAFF field pictures in one packet, or a demuxer
4246 * which splits NALs strangely if so, when frame threading we
4247 * can't start the next thread until we've read all of them */
4248 switch (hx->nal_unit_type) {
4251 nals_needed = nal_index;
4255 init_get_bits(&hx->s.gb, ptr, bit_length);
4256 if (!get_ue_golomb(&hx->s.gb))
4257 nals_needed = nal_index;
4262 // FIXME do not discard SEI id
4263 if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
4268 switch (hx->nal_unit_type) {
4270 if (h->nal_unit_type != NAL_IDR_SLICE) {
4271 av_log(h->s.avctx, AV_LOG_ERROR,
4272 "Invalid mix of idr and non-idr slices");
4276 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4278 init_get_bits(&hx->s.gb, ptr, bit_length);
4280 hx->inter_gb_ptr = &hx->s.gb;
4281 hx->s.data_partitioning = 0;
4283 if ((err = decode_slice_header(hx, h)))
4286 s->current_picture_ptr->f.key_frame |=
4287 (hx->nal_unit_type == NAL_IDR_SLICE) ||
4288 (h->sei_recovery_frame_cnt >= 0);
4290 if (h->current_slice == 1) {
4291 if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
4292 decode_postinit(h, nal_index >= nals_needed);
4294 if (s->avctx->hwaccel &&
4295 s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
4297 if (CONFIG_H264_VDPAU_DECODER &&
4298 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4299 ff_vdpau_h264_picture_start(s);
4302 if (hx->redundant_pic_count == 0 &&
4303 (avctx->skip_frame < AVDISCARD_NONREF ||
4305 (avctx->skip_frame < AVDISCARD_BIDIR ||
4306 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4307 (avctx->skip_frame < AVDISCARD_NONKEY ||
4308 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4309 avctx->skip_frame < AVDISCARD_ALL) {
4310 if (avctx->hwaccel) {
4311 if (avctx->hwaccel->decode_slice(avctx,
4312 &buf[buf_index - consumed],
4315 } else if (CONFIG_H264_VDPAU_DECODER &&
4316 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4317 static const uint8_t start_code[] = {
4319 ff_vdpau_add_data_chunk(s, start_code,
4320 sizeof(start_code));
4321 ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
4328 init_get_bits(&hx->s.gb, ptr, bit_length);
4330 hx->inter_gb_ptr = NULL;
4332 if ((err = decode_slice_header(hx, h)) < 0)
4335 hx->s.data_partitioning = 1;
4338 init_get_bits(&hx->intra_gb, ptr, bit_length);
4339 hx->intra_gb_ptr = &hx->intra_gb;
4342 init_get_bits(&hx->inter_gb, ptr, bit_length);
4343 hx->inter_gb_ptr = &hx->inter_gb;
4345 if (hx->redundant_pic_count == 0 &&
4347 hx->s.data_partitioning &&
4348 s->context_initialized &&
4349 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4350 (avctx->skip_frame < AVDISCARD_BIDIR ||
4351 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4352 (avctx->skip_frame < AVDISCARD_NONKEY ||
4353 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4354 avctx->skip_frame < AVDISCARD_ALL)
4358 init_get_bits(&s->gb, ptr, bit_length);
4359 ff_h264_decode_sei(h);
4362 init_get_bits(&s->gb, ptr, bit_length);
4363 if (ff_h264_decode_seq_parameter_set(h) < 0 &&
4364 h->is_avc && (nalsize != consumed) && nalsize) {
4365 av_log(h->s.avctx, AV_LOG_DEBUG,
4366 "SPS decoding failure, try parsing the coomplete NAL\n");
4367 init_get_bits(&s->gb, buf + buf_index + 1 - consumed,
4369 ff_h264_decode_seq_parameter_set(h);
4372 if (s->flags & CODEC_FLAG_LOW_DELAY ||
4373 (h->sps.bitstream_restriction_flag &&
4374 !h->sps.num_reorder_frames))
4377 if (avctx->has_b_frames < 2)
4378 avctx->has_b_frames = !s->low_delay;
4380 if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
4381 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
4382 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
4383 avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
4384 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
4385 h->pixel_shift = h->sps.bit_depth_luma > 8;
4387 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
4388 h->sps.chroma_format_idc);
4389 ff_h264_pred_init(&h->hpc, s->codec_id,
4390 h->sps.bit_depth_luma,
4391 h->sps.chroma_format_idc);
4392 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
4393 ff_dsputil_init(&s->dsp, s->avctx);
4395 av_log(avctx, AV_LOG_ERROR,
4396 "Unsupported bit depth: %d\n",
4397 h->sps.bit_depth_luma);
4404 init_get_bits(&s->gb, ptr, bit_length);
4405 ff_h264_decode_picture_parameter_set(h, bit_length);
4408 case NAL_END_SEQUENCE:
4409 case NAL_END_STREAM:
4410 case NAL_FILLER_DATA:
4412 case NAL_AUXILIARY_SLICE:
4415 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4416 hx->nal_unit_type, bit_length);
4419 if (context_count == h->max_contexts) {
4420 execute_decode_slices(h, context_count);
4425 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4426 else if (err == 1) {
4427 /* Slice could not be decoded in parallel mode, copy down
4428 * NAL unit stuff to context 0 and restart. Note that
4429 * rbsp_buffer is not transferred, but since we no longer
4430 * run in parallel mode this should not be an issue. */
4431 h->nal_unit_type = hx->nal_unit_type;
4432 h->nal_ref_idc = hx->nal_ref_idc;
4439 execute_decode_slices(h, context_count);
4443 if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
4445 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
4446 s->picture_structure == PICT_BOTTOM_FIELD);
4453 * Return the number of bytes consumed for building the current frame.
4455 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
4458 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4459 if (pos + 10 > buf_size)
4460 pos = buf_size; // oops ;)
4465 static int decode_frame(AVCodecContext *avctx, void *data,
4466 int *data_size, AVPacket *avpkt)
4468 const uint8_t *buf = avpkt->data;
4469 int buf_size = avpkt->size;
4470 H264Context *h = avctx->priv_data;
4471 MpegEncContext *s = &h->s;
4472 AVFrame *pict = data;
4475 s->flags = avctx->flags;
4476 s->flags2 = avctx->flags2;
4478 /* end of stream, output what is still in the buffers */
4480 if (buf_size == 0) {
4484 s->current_picture_ptr = NULL;
4486 // FIXME factorize this with the output code below
4487 out = h->delayed_pic[0];
4490 h->delayed_pic[i] &&
4491 !h->delayed_pic[i]->f.key_frame &&
4492 !h->delayed_pic[i]->mmco_reset;
4494 if (h->delayed_pic[i]->poc < out->poc) {
4495 out = h->delayed_pic[i];
4499 for (i = out_idx; h->delayed_pic[i]; i++)
4500 h->delayed_pic[i] = h->delayed_pic[i + 1];
4503 *data_size = sizeof(AVFrame);
4510 buf_index = decode_nal_units(h, buf, buf_size);
4514 if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4519 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
4520 if (avctx->skip_frame >= AVDISCARD_NONREF)
4522 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4526 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
4527 (s->mb_y >= s->mb_height && s->mb_height)) {
4528 if (s->flags2 & CODEC_FLAG2_CHUNKS)
4529 decode_postinit(h, 1);
4533 if (!h->next_output_pic) {
4534 /* Wait for second field. */
4537 *data_size = sizeof(AVFrame);
4538 *pict = h->next_output_pic->f;
4542 assert(pict->data[0] || !*data_size);
4543 ff_print_debug_info(s, pict);
4544 // printf("out %d\n", (int)pict->data[0]);
4546 return get_consumed_bytes(s, buf_index, buf_size);
4549 av_cold void ff_h264_free_context(H264Context *h)
4553 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4555 for (i = 0; i < MAX_SPS_COUNT; i++)
4556 av_freep(h->sps_buffers + i);
4558 for (i = 0; i < MAX_PPS_COUNT; i++)
4559 av_freep(h->pps_buffers + i);
4562 av_cold int ff_h264_decode_end(AVCodecContext *avctx)
4564 H264Context *h = avctx->priv_data;
4565 MpegEncContext *s = &h->s;
4567 ff_h264_free_context(h);
4569 ff_MPV_common_end(s);
4571 // memset(h, 0, sizeof(H264Context));
4576 static const AVProfile profiles[] = {
4577 { FF_PROFILE_H264_BASELINE, "Baseline" },
4578 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4579 { FF_PROFILE_H264_MAIN, "Main" },
4580 { FF_PROFILE_H264_EXTENDED, "Extended" },
4581 { FF_PROFILE_H264_HIGH, "High" },
4582 { FF_PROFILE_H264_HIGH_10, "High 10" },
4583 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4584 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4585 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4586 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4587 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4588 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4589 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4590 { FF_PROFILE_UNKNOWN },
4593 AVCodec ff_h264_decoder = {
4595 .type = AVMEDIA_TYPE_VIDEO,
4596 .id = CODEC_ID_H264,
4597 .priv_data_size = sizeof(H264Context),
4598 .init = ff_h264_decode_init,
4599 .close = ff_h264_decode_end,
4600 .decode = decode_frame,
4601 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4602 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4603 CODEC_CAP_FRAME_THREADS,
4605 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4606 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4607 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4608 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4611 #if CONFIG_H264_VDPAU_DECODER
4612 AVCodec ff_h264_vdpau_decoder = {
4613 .name = "h264_vdpau",
4614 .type = AVMEDIA_TYPE_VIDEO,
4615 .id = CODEC_ID_H264,
4616 .priv_data_size = sizeof(H264Context),
4617 .init = ff_h264_decode_init,
4618 .close = ff_h264_decode_end,
4619 .decode = decode_frame,
4620 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4622 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4623 .pix_fmts = (const enum PixelFormat[]) { PIX_FMT_VDPAU_H264,
4625 .profiles = NULL_IF_CONFIG_SMALL(profiles),