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 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
50 static const uint8_t rem6[QP_MAX_NUM + 1] = {
51 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
52 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
53 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
56 static const uint8_t div6[QP_MAX_NUM + 1] = {
57 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
58 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
59 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
62 static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
71 * Check if the top & left blocks are available if needed and
72 * change the dc mode so it only uses the available blocks.
74 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
76 MpegEncContext *const s = &h->s;
77 static const int8_t top[12] = {
78 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
80 static const int8_t left[12] = {
81 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
85 if (!(h->top_samples_available & 0x8000)) {
86 for (i = 0; i < 4; i++) {
87 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
89 av_log(h->s.avctx, AV_LOG_ERROR,
90 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
91 status, s->mb_x, s->mb_y);
94 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
99 if ((h->left_samples_available & 0x8888) != 0x8888) {
100 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
101 for (i = 0; i < 4; i++)
102 if (!(h->left_samples_available & mask[i])) {
103 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
105 av_log(h->s.avctx, AV_LOG_ERROR,
106 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
107 status, s->mb_x, s->mb_y);
110 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
116 } // FIXME cleanup like ff_h264_check_intra_pred_mode
119 * Check if the top & left blocks are available if needed and
120 * change the dc mode so it only uses the available blocks.
122 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
124 MpegEncContext *const s = &h->s;
125 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
126 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
129 av_log(h->s.avctx, AV_LOG_ERROR,
130 "out of range intra chroma pred mode at %d %d\n",
135 if (!(h->top_samples_available & 0x8000)) {
138 av_log(h->s.avctx, AV_LOG_ERROR,
139 "top block unavailable for requested intra mode at %d %d\n",
145 if ((h->left_samples_available & 0x8080) != 0x8080) {
147 if (is_chroma && (h->left_samples_available & 0x8080)) {
148 // mad cow disease mode, aka MBAFF + constrained_intra_pred
149 mode = ALZHEIMER_DC_L0T_PRED8x8 +
150 (!(h->left_samples_available & 0x8000)) +
151 2 * (mode == DC_128_PRED8x8);
154 av_log(h->s.avctx, AV_LOG_ERROR,
155 "left block unavailable for requested intra mode at %d %d\n",
164 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
165 int *dst_length, int *consumed, int length)
171 // src[0]&0x80; // forbidden bit
172 h->nal_ref_idc = src[0] >> 5;
173 h->nal_unit_type = src[0] & 0x1F;
178 #if HAVE_FAST_UNALIGNED
181 for (i = 0; i + 1 < length; i += 9) {
182 if (!((~AV_RN64A(src + i) &
183 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
184 0x8000800080008080ULL))
187 for (i = 0; i + 1 < length; i += 5) {
188 if (!((~AV_RN32A(src + i) &
189 (AV_RN32A(src + i) - 0x01000101U)) &
193 if (i > 0 && !src[i])
199 for (i = 0; i + 1 < length; i += 2) {
202 if (i > 0 && src[i - 1] == 0)
205 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {
206 if (src[i + 2] != 3) {
207 /* startcode, so we must be past the end */
215 if (i >= length - 1) { // no escaped 0
216 *dst_length = length;
217 *consumed = length + 1; // +1 for the header
221 // use second escape buffer for inter data
222 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
223 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
224 length + FF_INPUT_BUFFER_PADDING_SIZE);
225 dst = h->rbsp_buffer[bufidx];
230 // printf("decoding esc\n");
233 while (si + 2 < length) {
234 // remove escapes (very rare 1:2^22)
235 if (src[si + 2] > 3) {
236 dst[di++] = src[si++];
237 dst[di++] = src[si++];
238 } else if (src[si] == 0 && src[si + 1] == 0) {
239 if (src[si + 2] == 3) { // escape
244 } else // next start code
248 dst[di++] = src[si++];
251 dst[di++] = src[si++];
254 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
257 *consumed = si + 1; // +1 for the header
258 /* FIXME store exact number of bits in the getbitcontext
259 * (it is needed for decoding) */
264 * Identify the exact end of the bitstream
265 * @return the length of the trailing, or 0 if damaged
267 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
272 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
274 for (r = 1; r < 9; r++) {
282 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
283 int height, int y_offset, int list)
285 int raw_my = h->mv_cache[list][scan8[n]][1];
286 int filter_height = (raw_my & 3) ? 2 : 0;
287 int full_my = (raw_my >> 2) + y_offset;
288 int top = full_my - filter_height;
289 int bottom = full_my + filter_height + height;
291 return FFMAX(abs(top), bottom);
294 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
295 int height, int y_offset, int list0,
296 int list1, int *nrefs)
298 MpegEncContext *const s = &h->s;
301 y_offset += 16 * (s->mb_y >> MB_FIELD);
304 int ref_n = h->ref_cache[0][scan8[n]];
305 Picture *ref = &h->ref_list[0][ref_n];
307 // Error resilience puts the current picture in the ref list.
308 // Don't try to wait on these as it will cause a deadlock.
309 // Fields can wait on each other, though.
310 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
311 (ref->f.reference & 3) != s->picture_structure) {
312 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
313 if (refs[0][ref_n] < 0)
315 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
320 int ref_n = h->ref_cache[1][scan8[n]];
321 Picture *ref = &h->ref_list[1][ref_n];
323 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
324 (ref->f.reference & 3) != s->picture_structure) {
325 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
326 if (refs[1][ref_n] < 0)
328 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
334 * Wait until all reference frames are available for MC operations.
336 * @param h the H264 context
338 static void await_references(H264Context *h)
340 MpegEncContext *const s = &h->s;
341 const int mb_xy = h->mb_xy;
342 const int mb_type = s->current_picture.f.mb_type[mb_xy];
344 int nrefs[2] = { 0 };
347 memset(refs, -1, sizeof(refs));
349 if (IS_16X16(mb_type)) {
350 get_lowest_part_y(h, refs, 0, 16, 0,
351 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
352 } else if (IS_16X8(mb_type)) {
353 get_lowest_part_y(h, refs, 0, 8, 0,
354 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
355 get_lowest_part_y(h, refs, 8, 8, 8,
356 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
357 } else if (IS_8X16(mb_type)) {
358 get_lowest_part_y(h, refs, 0, 16, 0,
359 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
360 get_lowest_part_y(h, refs, 4, 16, 0,
361 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
365 assert(IS_8X8(mb_type));
367 for (i = 0; i < 4; i++) {
368 const int sub_mb_type = h->sub_mb_type[i];
370 int y_offset = (i & 2) << 2;
372 if (IS_SUB_8X8(sub_mb_type)) {
373 get_lowest_part_y(h, refs, n, 8, y_offset,
374 IS_DIR(sub_mb_type, 0, 0),
375 IS_DIR(sub_mb_type, 0, 1),
377 } else if (IS_SUB_8X4(sub_mb_type)) {
378 get_lowest_part_y(h, refs, n, 4, y_offset,
379 IS_DIR(sub_mb_type, 0, 0),
380 IS_DIR(sub_mb_type, 0, 1),
382 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
383 IS_DIR(sub_mb_type, 0, 0),
384 IS_DIR(sub_mb_type, 0, 1),
386 } else if (IS_SUB_4X8(sub_mb_type)) {
387 get_lowest_part_y(h, refs, n, 8, y_offset,
388 IS_DIR(sub_mb_type, 0, 0),
389 IS_DIR(sub_mb_type, 0, 1),
391 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
392 IS_DIR(sub_mb_type, 0, 0),
393 IS_DIR(sub_mb_type, 0, 1),
397 assert(IS_SUB_4X4(sub_mb_type));
398 for (j = 0; j < 4; j++) {
399 int sub_y_offset = y_offset + 2 * (j & 2);
400 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
401 IS_DIR(sub_mb_type, 0, 0),
402 IS_DIR(sub_mb_type, 0, 1),
409 for (list = h->list_count - 1; list >= 0; list--)
410 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
411 int row = refs[list][ref];
413 Picture *ref_pic = &h->ref_list[list][ref];
414 int ref_field = ref_pic->f.reference - 1;
415 int ref_field_picture = ref_pic->field_picture;
416 int pic_height = 16 * s->mb_height >> ref_field_picture;
421 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
422 ff_thread_await_progress(&ref_pic->f,
423 FFMIN((row >> 1) - !(row & 1),
426 ff_thread_await_progress(&ref_pic->f,
427 FFMIN((row >> 1), pic_height - 1),
429 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
430 ff_thread_await_progress(&ref_pic->f,
431 FFMIN(row * 2 + ref_field,
434 } else if (FIELD_PICTURE) {
435 ff_thread_await_progress(&ref_pic->f,
436 FFMIN(row, pic_height - 1),
439 ff_thread_await_progress(&ref_pic->f,
440 FFMIN(row, pic_height - 1),
447 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
448 int n, int square, int height,
450 uint8_t *dest_y, uint8_t *dest_cb,
452 int src_x_offset, int src_y_offset,
453 qpel_mc_func *qpix_op,
454 h264_chroma_mc_func chroma_op,
455 int pixel_shift, int chroma_idc)
457 MpegEncContext *const s = &h->s;
458 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
459 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
460 const int luma_xy = (mx & 3) + ((my & 3) << 2);
461 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
462 uint8_t *src_y = pic->f.data[0] + offset;
463 uint8_t *src_cb, *src_cr;
464 int extra_width = h->emu_edge_width;
465 int extra_height = h->emu_edge_height;
467 const int full_mx = mx >> 2;
468 const int full_my = my >> 2;
469 const int pic_width = 16 * s->mb_width;
470 const int pic_height = 16 * s->mb_height >> MB_FIELD;
478 if (full_mx < 0 - extra_width ||
479 full_my < 0 - extra_height ||
480 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
481 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
482 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
483 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
485 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
486 full_my - 2, pic_width, pic_height);
487 src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
491 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
493 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
495 if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
498 if (chroma_idc == 3 /* yuv444 */) {
499 src_cb = pic->f.data[1] + offset;
501 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
502 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
504 16 + 5, 16 + 5 /*FIXME*/,
505 full_mx - 2, full_my - 2,
506 pic_width, pic_height);
507 src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
509 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
511 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
513 src_cr = pic->f.data[2] + offset;
515 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
516 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
518 16 + 5, 16 + 5 /*FIXME*/,
519 full_mx - 2, full_my - 2,
520 pic_width, pic_height);
521 src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
523 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
525 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
529 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
530 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
531 // chroma offset when predicting from a field of opposite parity
532 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
533 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
536 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
537 (my >> ysh) * h->mb_uvlinesize;
538 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
539 (my >> ysh) * h->mb_uvlinesize;
542 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
543 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
544 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
545 src_cb = s->edge_emu_buffer;
547 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
548 height >> (chroma_idc == 1 /* yuv420 */),
549 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
552 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
553 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
554 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
555 src_cr = s->edge_emu_buffer;
557 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
558 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
561 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
562 int height, int delta,
563 uint8_t *dest_y, uint8_t *dest_cb,
565 int x_offset, int y_offset,
566 qpel_mc_func *qpix_put,
567 h264_chroma_mc_func chroma_put,
568 qpel_mc_func *qpix_avg,
569 h264_chroma_mc_func chroma_avg,
570 int list0, int list1,
571 int pixel_shift, int chroma_idc)
573 MpegEncContext *const s = &h->s;
574 qpel_mc_func *qpix_op = qpix_put;
575 h264_chroma_mc_func chroma_op = chroma_put;
577 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
578 if (chroma_idc == 3 /* yuv444 */) {
579 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
580 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
581 } else if (chroma_idc == 2 /* yuv422 */) {
582 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
583 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
584 } else { /* yuv420 */
585 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
586 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
588 x_offset += 8 * s->mb_x;
589 y_offset += 8 * (s->mb_y >> MB_FIELD);
592 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
593 mc_dir_part(h, ref, n, square, height, delta, 0,
594 dest_y, dest_cb, dest_cr, x_offset, y_offset,
595 qpix_op, chroma_op, pixel_shift, chroma_idc);
598 chroma_op = chroma_avg;
602 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
603 mc_dir_part(h, ref, n, square, height, delta, 1,
604 dest_y, dest_cb, dest_cr, x_offset, y_offset,
605 qpix_op, chroma_op, pixel_shift, chroma_idc);
609 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
610 int height, int delta,
611 uint8_t *dest_y, uint8_t *dest_cb,
613 int x_offset, int y_offset,
614 qpel_mc_func *qpix_put,
615 h264_chroma_mc_func chroma_put,
616 h264_weight_func luma_weight_op,
617 h264_weight_func chroma_weight_op,
618 h264_biweight_func luma_weight_avg,
619 h264_biweight_func chroma_weight_avg,
620 int list0, int list1,
621 int pixel_shift, int chroma_idc)
623 MpegEncContext *const s = &h->s;
626 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
627 if (chroma_idc == 3 /* yuv444 */) {
628 chroma_height = height;
629 chroma_weight_avg = luma_weight_avg;
630 chroma_weight_op = luma_weight_op;
631 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
632 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
633 } else if (chroma_idc == 2 /* yuv422 */) {
634 chroma_height = height;
635 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
636 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
637 } else { /* yuv420 */
638 chroma_height = height >> 1;
639 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
640 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
642 x_offset += 8 * s->mb_x;
643 y_offset += 8 * (s->mb_y >> MB_FIELD);
645 if (list0 && list1) {
646 /* don't optimize for luma-only case, since B-frames usually
647 * use implicit weights => chroma too. */
648 uint8_t *tmp_cb = s->obmc_scratchpad;
649 uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
650 uint8_t *tmp_y = s->obmc_scratchpad + 16 * h->mb_uvlinesize;
651 int refn0 = h->ref_cache[0][scan8[n]];
652 int refn1 = h->ref_cache[1][scan8[n]];
654 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
655 dest_y, dest_cb, dest_cr,
656 x_offset, y_offset, qpix_put, chroma_put,
657 pixel_shift, chroma_idc);
658 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
659 tmp_y, tmp_cb, tmp_cr,
660 x_offset, y_offset, qpix_put, chroma_put,
661 pixel_shift, chroma_idc);
663 if (h->use_weight == 2) {
664 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
665 int weight1 = 64 - weight0;
666 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
667 height, 5, weight0, weight1, 0);
668 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
669 chroma_height, 5, weight0, weight1, 0);
670 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
671 chroma_height, 5, weight0, weight1, 0);
673 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
674 h->luma_log2_weight_denom,
675 h->luma_weight[refn0][0][0],
676 h->luma_weight[refn1][1][0],
677 h->luma_weight[refn0][0][1] +
678 h->luma_weight[refn1][1][1]);
679 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
680 h->chroma_log2_weight_denom,
681 h->chroma_weight[refn0][0][0][0],
682 h->chroma_weight[refn1][1][0][0],
683 h->chroma_weight[refn0][0][0][1] +
684 h->chroma_weight[refn1][1][0][1]);
685 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
686 h->chroma_log2_weight_denom,
687 h->chroma_weight[refn0][0][1][0],
688 h->chroma_weight[refn1][1][1][0],
689 h->chroma_weight[refn0][0][1][1] +
690 h->chroma_weight[refn1][1][1][1]);
693 int list = list1 ? 1 : 0;
694 int refn = h->ref_cache[list][scan8[n]];
695 Picture *ref = &h->ref_list[list][refn];
696 mc_dir_part(h, ref, n, square, height, delta, list,
697 dest_y, dest_cb, dest_cr, x_offset, y_offset,
698 qpix_put, chroma_put, pixel_shift, chroma_idc);
700 luma_weight_op(dest_y, h->mb_linesize, height,
701 h->luma_log2_weight_denom,
702 h->luma_weight[refn][list][0],
703 h->luma_weight[refn][list][1]);
704 if (h->use_weight_chroma) {
705 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
706 h->chroma_log2_weight_denom,
707 h->chroma_weight[refn][list][0][0],
708 h->chroma_weight[refn][list][0][1]);
709 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
710 h->chroma_log2_weight_denom,
711 h->chroma_weight[refn][list][1][0],
712 h->chroma_weight[refn][list][1][1]);
717 static av_always_inline void mc_part(H264Context *h, int n, int square,
718 int height, int delta,
719 uint8_t *dest_y, uint8_t *dest_cb,
721 int x_offset, int y_offset,
722 qpel_mc_func *qpix_put,
723 h264_chroma_mc_func chroma_put,
724 qpel_mc_func *qpix_avg,
725 h264_chroma_mc_func chroma_avg,
726 h264_weight_func *weight_op,
727 h264_biweight_func *weight_avg,
728 int list0, int list1,
729 int pixel_shift, int chroma_idc)
731 if ((h->use_weight == 2 && list0 && list1 &&
732 (h->implicit_weight[h->ref_cache[0][scan8[n]]][h->ref_cache[1][scan8[n]]][h->s.mb_y & 1] != 32)) ||
734 mc_part_weighted(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
735 x_offset, y_offset, qpix_put, chroma_put,
736 weight_op[0], weight_op[1], weight_avg[0],
737 weight_avg[1], list0, list1, pixel_shift, chroma_idc);
739 mc_part_std(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
740 x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
741 chroma_avg, list0, list1, pixel_shift, chroma_idc);
744 static av_always_inline void prefetch_motion(H264Context *h, int list,
745 int pixel_shift, int chroma_idc)
747 /* fetch pixels for estimated mv 4 macroblocks ahead
748 * optimized for 64byte cache lines */
749 MpegEncContext *const s = &h->s;
750 const int refn = h->ref_cache[list][scan8[0]];
752 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
753 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
754 uint8_t **src = h->ref_list[list][refn].f.data;
755 int off = (mx << pixel_shift) +
756 (my + (s->mb_x & 3) * 4) * h->mb_linesize +
758 s->dsp.prefetch(src[0] + off, s->linesize, 4);
759 if (chroma_idc == 3 /* yuv444 */) {
760 s->dsp.prefetch(src[1] + off, s->linesize, 4);
761 s->dsp.prefetch(src[2] + off, s->linesize, 4);
763 off = ((mx >> 1) << pixel_shift) +
764 ((my >> 1) + (s->mb_x & 7)) * s->uvlinesize +
766 s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
771 static av_always_inline void hl_motion(H264Context *h, uint8_t *dest_y,
772 uint8_t *dest_cb, uint8_t *dest_cr,
773 qpel_mc_func(*qpix_put)[16],
774 h264_chroma_mc_func(*chroma_put),
775 qpel_mc_func(*qpix_avg)[16],
776 h264_chroma_mc_func(*chroma_avg),
777 h264_weight_func *weight_op,
778 h264_biweight_func *weight_avg,
779 int pixel_shift, int chroma_idc)
781 MpegEncContext *const s = &h->s;
782 const int mb_xy = h->mb_xy;
783 const int mb_type = s->current_picture.f.mb_type[mb_xy];
785 assert(IS_INTER(mb_type));
787 if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
789 prefetch_motion(h, 0, pixel_shift, chroma_idc);
791 if (IS_16X16(mb_type)) {
792 mc_part(h, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0,
793 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
794 weight_op, weight_avg,
795 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
796 pixel_shift, chroma_idc);
797 } else if (IS_16X8(mb_type)) {
798 mc_part(h, 0, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 0,
799 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
800 weight_op, weight_avg,
801 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
802 pixel_shift, chroma_idc);
803 mc_part(h, 8, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 4,
804 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
805 weight_op, weight_avg,
806 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
807 pixel_shift, chroma_idc);
808 } else if (IS_8X16(mb_type)) {
809 mc_part(h, 0, 0, 16, 8 * h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
810 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
811 &weight_op[1], &weight_avg[1],
812 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
813 pixel_shift, chroma_idc);
814 mc_part(h, 4, 0, 16, 8 * h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
815 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
816 &weight_op[1], &weight_avg[1],
817 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
818 pixel_shift, chroma_idc);
822 assert(IS_8X8(mb_type));
824 for (i = 0; i < 4; i++) {
825 const int sub_mb_type = h->sub_mb_type[i];
827 int x_offset = (i & 1) << 2;
828 int y_offset = (i & 2) << 1;
830 if (IS_SUB_8X8(sub_mb_type)) {
831 mc_part(h, n, 1, 8, 0, dest_y, dest_cb, dest_cr,
833 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
834 &weight_op[1], &weight_avg[1],
835 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
836 pixel_shift, chroma_idc);
837 } else if (IS_SUB_8X4(sub_mb_type)) {
838 mc_part(h, n, 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr,
840 qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
841 &weight_op[1], &weight_avg[1],
842 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
843 pixel_shift, chroma_idc);
844 mc_part(h, n + 2, 0, 4, 4 << pixel_shift,
845 dest_y, dest_cb, dest_cr, x_offset, y_offset + 2,
846 qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
847 &weight_op[1], &weight_avg[1],
848 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
849 pixel_shift, chroma_idc);
850 } else if (IS_SUB_4X8(sub_mb_type)) {
851 mc_part(h, n, 0, 8, 4 * h->mb_linesize,
852 dest_y, dest_cb, dest_cr, x_offset, y_offset,
853 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
854 &weight_op[2], &weight_avg[2],
855 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
856 pixel_shift, chroma_idc);
857 mc_part(h, n + 1, 0, 8, 4 * h->mb_linesize,
858 dest_y, dest_cb, dest_cr, x_offset + 2, y_offset,
859 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
860 &weight_op[2], &weight_avg[2],
861 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
862 pixel_shift, chroma_idc);
865 assert(IS_SUB_4X4(sub_mb_type));
866 for (j = 0; j < 4; j++) {
867 int sub_x_offset = x_offset + 2 * (j & 1);
868 int sub_y_offset = y_offset + (j & 2);
869 mc_part(h, n + j, 1, 4, 0,
870 dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
871 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
872 &weight_op[2], &weight_avg[2],
873 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
874 pixel_shift, chroma_idc);
880 prefetch_motion(h, 1, pixel_shift, chroma_idc);
883 static av_always_inline void hl_motion_420(H264Context *h, uint8_t *dest_y,
884 uint8_t *dest_cb, uint8_t *dest_cr,
885 qpel_mc_func(*qpix_put)[16],
886 h264_chroma_mc_func(*chroma_put),
887 qpel_mc_func(*qpix_avg)[16],
888 h264_chroma_mc_func(*chroma_avg),
889 h264_weight_func *weight_op,
890 h264_biweight_func *weight_avg,
893 hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
894 qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 1);
897 static av_always_inline void hl_motion_422(H264Context *h, uint8_t *dest_y,
898 uint8_t *dest_cb, uint8_t *dest_cr,
899 qpel_mc_func(*qpix_put)[16],
900 h264_chroma_mc_func(*chroma_put),
901 qpel_mc_func(*qpix_avg)[16],
902 h264_chroma_mc_func(*chroma_avg),
903 h264_weight_func *weight_op,
904 h264_biweight_func *weight_avg,
907 hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
908 qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 2);
911 static void free_tables(H264Context *h, int free_rbsp)
916 av_freep(&h->intra4x4_pred_mode);
917 av_freep(&h->chroma_pred_mode_table);
918 av_freep(&h->cbp_table);
919 av_freep(&h->mvd_table[0]);
920 av_freep(&h->mvd_table[1]);
921 av_freep(&h->direct_table);
922 av_freep(&h->non_zero_count);
923 av_freep(&h->slice_table_base);
924 h->slice_table = NULL;
925 av_freep(&h->list_counts);
927 av_freep(&h->mb2b_xy);
928 av_freep(&h->mb2br_xy);
930 for (i = 0; i < MAX_THREADS; i++) {
931 hx = h->thread_context[i];
934 av_freep(&hx->top_borders[1]);
935 av_freep(&hx->top_borders[0]);
936 av_freep(&hx->s.obmc_scratchpad);
938 av_freep(&hx->rbsp_buffer[1]);
939 av_freep(&hx->rbsp_buffer[0]);
940 hx->rbsp_buffer_size[0] = 0;
941 hx->rbsp_buffer_size[1] = 0;
944 av_freep(&h->thread_context[i]);
948 static void init_dequant8_coeff_table(H264Context *h)
951 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
953 for (i = 0; i < 6; i++) {
954 h->dequant8_coeff[i] = h->dequant8_buffer[i];
955 for (j = 0; j < i; j++)
956 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
957 64 * sizeof(uint8_t))) {
958 h->dequant8_coeff[i] = h->dequant8_buffer[j];
964 for (q = 0; q < max_qp + 1; q++) {
967 for (x = 0; x < 64; x++)
968 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
969 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
970 h->pps.scaling_matrix8[i][x]) << shift;
975 static void init_dequant4_coeff_table(H264Context *h)
978 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
979 for (i = 0; i < 6; i++) {
980 h->dequant4_coeff[i] = h->dequant4_buffer[i];
981 for (j = 0; j < i; j++)
982 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
983 16 * sizeof(uint8_t))) {
984 h->dequant4_coeff[i] = h->dequant4_buffer[j];
990 for (q = 0; q < max_qp + 1; q++) {
991 int shift = div6[q] + 2;
993 for (x = 0; x < 16; x++)
994 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
995 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
996 h->pps.scaling_matrix4[i][x]) << shift;
1001 static void init_dequant_tables(H264Context *h)
1004 init_dequant4_coeff_table(h);
1005 if (h->pps.transform_8x8_mode)
1006 init_dequant8_coeff_table(h);
1007 if (h->sps.transform_bypass) {
1008 for (i = 0; i < 6; i++)
1009 for (x = 0; x < 16; x++)
1010 h->dequant4_coeff[i][0][x] = 1 << 6;
1011 if (h->pps.transform_8x8_mode)
1012 for (i = 0; i < 6; i++)
1013 for (x = 0; x < 64; x++)
1014 h->dequant8_coeff[i][0][x] = 1 << 6;
1018 int ff_h264_alloc_tables(H264Context *h)
1020 MpegEncContext *const s = &h->s;
1021 const int big_mb_num = s->mb_stride * (s->mb_height + 1);
1022 const int row_mb_num = s->mb_stride * 2 * s->avctx->thread_count;
1025 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
1026 row_mb_num * 8 * sizeof(uint8_t), fail)
1027 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
1028 big_mb_num * 48 * sizeof(uint8_t), fail)
1029 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
1030 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
1031 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
1032 big_mb_num * sizeof(uint16_t), fail)
1033 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
1034 big_mb_num * sizeof(uint8_t), fail)
1035 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
1036 16 * row_mb_num * sizeof(uint8_t), fail);
1037 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
1038 16 * row_mb_num * sizeof(uint8_t), fail);
1039 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
1040 4 * big_mb_num * sizeof(uint8_t), fail);
1041 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
1042 big_mb_num * sizeof(uint8_t), fail)
1044 memset(h->slice_table_base, -1,
1045 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
1046 h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
1048 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
1049 big_mb_num * sizeof(uint32_t), fail);
1050 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
1051 big_mb_num * sizeof(uint32_t), fail);
1052 for (y = 0; y < s->mb_height; y++)
1053 for (x = 0; x < s->mb_width; x++) {
1054 const int mb_xy = x + y * s->mb_stride;
1055 const int b_xy = 4 * x + 4 * y * h->b_stride;
1057 h->mb2b_xy[mb_xy] = b_xy;
1058 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
1061 s->obmc_scratchpad = NULL;
1063 if (!h->dequant4_coeff[0])
1064 init_dequant_tables(h);
1074 * Mimic alloc_tables(), but for every context thread.
1076 static void clone_tables(H264Context *dst, H264Context *src, int i)
1078 MpegEncContext *const s = &src->s;
1079 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
1080 dst->non_zero_count = src->non_zero_count;
1081 dst->slice_table = src->slice_table;
1082 dst->cbp_table = src->cbp_table;
1083 dst->mb2b_xy = src->mb2b_xy;
1084 dst->mb2br_xy = src->mb2br_xy;
1085 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1086 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
1087 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
1088 dst->direct_table = src->direct_table;
1089 dst->list_counts = src->list_counts;
1090 dst->s.obmc_scratchpad = NULL;
1091 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
1092 src->sps.chroma_format_idc);
1097 * Allocate buffers which are not shared amongst multiple threads.
1099 static int context_init(H264Context *h)
1101 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
1102 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1103 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
1104 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1106 h->ref_cache[0][scan8[5] + 1] =
1107 h->ref_cache[0][scan8[7] + 1] =
1108 h->ref_cache[0][scan8[13] + 1] =
1109 h->ref_cache[1][scan8[5] + 1] =
1110 h->ref_cache[1][scan8[7] + 1] =
1111 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1116 return -1; // free_tables will clean up for us
1119 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
1121 static av_cold void common_init(H264Context *h)
1123 MpegEncContext *const s = &h->s;
1125 s->width = s->avctx->width;
1126 s->height = s->avctx->height;
1127 s->codec_id = s->avctx->codec->id;
1129 ff_h264dsp_init(&h->h264dsp, 8, 1);
1130 ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);
1132 h->dequant_coeff_pps = -1;
1133 s->unrestricted_mv = 1;
1135 /* needed so that IDCT permutation is known early */
1136 ff_dsputil_init(&s->dsp, s->avctx);
1138 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1139 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1142 int ff_h264_decode_extradata(H264Context *h)
1144 AVCodecContext *avctx = h->s.avctx;
1146 if (avctx->extradata[0] == 1) {
1147 int i, cnt, nalsize;
1148 unsigned char *p = avctx->extradata;
1152 if (avctx->extradata_size < 7) {
1153 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1156 /* sps and pps in the avcC always have length coded with 2 bytes,
1157 * so put a fake nal_length_size = 2 while parsing them */
1158 h->nal_length_size = 2;
1159 // Decode sps from avcC
1160 cnt = *(p + 5) & 0x1f; // Number of sps
1162 for (i = 0; i < cnt; i++) {
1163 nalsize = AV_RB16(p) + 2;
1164 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1166 if (decode_nal_units(h, p, nalsize) < 0) {
1167 av_log(avctx, AV_LOG_ERROR,
1168 "Decoding sps %d from avcC failed\n", i);
1173 // Decode pps from avcC
1174 cnt = *(p++); // Number of pps
1175 for (i = 0; i < cnt; i++) {
1176 nalsize = AV_RB16(p) + 2;
1177 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1179 if (decode_nal_units(h, p, nalsize) < 0) {
1180 av_log(avctx, AV_LOG_ERROR,
1181 "Decoding pps %d from avcC failed\n", i);
1186 // Now store right nal length size, that will be used to parse all other nals
1187 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1190 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
1196 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1198 H264Context *h = avctx->priv_data;
1199 MpegEncContext *const s = &h->s;
1202 ff_MPV_decode_defaults(s);
1207 s->out_format = FMT_H264;
1208 s->workaround_bugs = avctx->workaround_bugs;
1211 // s->decode_mb = ff_h263_decode_mb;
1212 s->quarter_sample = 1;
1213 if (!avctx->has_b_frames)
1216 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1218 ff_h264_decode_init_vlc();
1221 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1223 h->thread_context[0] = h;
1224 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1225 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1226 h->last_pocs[i] = INT_MIN;
1227 h->prev_poc_msb = 1 << 16;
1229 ff_h264_reset_sei(h);
1230 if (avctx->codec_id == CODEC_ID_H264) {
1231 if (avctx->ticks_per_frame == 1)
1232 s->avctx->time_base.den *= 2;
1233 avctx->ticks_per_frame = 2;
1236 if (avctx->extradata_size > 0 && avctx->extradata &&
1237 ff_h264_decode_extradata(h))
1240 if (h->sps.bitstream_restriction_flag &&
1241 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1242 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1249 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1251 static void copy_picture_range(Picture **to, Picture **from, int count,
1252 MpegEncContext *new_base,
1253 MpegEncContext *old_base)
1257 for (i = 0; i < count; i++) {
1258 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1259 IN_RANGE(from[i], old_base->picture,
1260 sizeof(Picture) * old_base->picture_count) ||
1262 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1266 static void copy_parameter_set(void **to, void **from, int count, int size)
1270 for (i = 0; i < count; i++) {
1271 if (to[i] && !from[i])
1273 else if (from[i] && !to[i])
1274 to[i] = av_malloc(size);
1277 memcpy(to[i], from[i], size);
1281 static int decode_init_thread_copy(AVCodecContext *avctx)
1283 H264Context *h = avctx->priv_data;
1285 if (!avctx->internal->is_copy)
1287 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1288 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1293 #define copy_fields(to, from, start_field, end_field) \
1294 memcpy(&to->start_field, &from->start_field, \
1295 (char *)&to->end_field - (char *)&to->start_field)
1297 static int decode_update_thread_context(AVCodecContext *dst,
1298 const AVCodecContext *src)
1300 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1301 MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1302 int inited = s->context_initialized, err;
1305 if (dst == src || !s1->context_initialized)
1308 err = ff_mpeg_update_thread_context(dst, src);
1312 // FIXME handle width/height changing
1314 for (i = 0; i < MAX_SPS_COUNT; i++)
1315 av_freep(h->sps_buffers + i);
1317 for (i = 0; i < MAX_PPS_COUNT; i++)
1318 av_freep(h->pps_buffers + i);
1320 // copy all fields after MpegEnc
1321 memcpy(&h->s + 1, &h1->s + 1,
1322 sizeof(H264Context) - sizeof(MpegEncContext));
1323 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1324 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1325 if (ff_h264_alloc_tables(h) < 0) {
1326 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1327 return AVERROR(ENOMEM);
1331 for (i = 0; i < 2; i++) {
1332 h->rbsp_buffer[i] = NULL;
1333 h->rbsp_buffer_size[i] = 0;
1336 h->thread_context[0] = h;
1338 /* frame_start may not be called for the next thread (if it's decoding
1339 * a bottom field) so this has to be allocated here */
1340 h->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1342 s->dsp.clear_blocks(h->mb);
1343 s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1346 // extradata/NAL handling
1347 h->is_avc = h1->is_avc;
1350 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1351 MAX_SPS_COUNT, sizeof(SPS));
1353 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1354 MAX_PPS_COUNT, sizeof(PPS));
1357 // Dequantization matrices
1358 // FIXME these are big - can they be only copied when PPS changes?
1359 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1361 for (i = 0; i < 6; i++)
1362 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1363 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1365 for (i = 0; i < 6; i++)
1366 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1367 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1369 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1372 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1375 copy_fields(h, h1, ref_count, list_count);
1376 copy_fields(h, h1, ref_list, intra_gb);
1377 copy_fields(h, h1, short_ref, cabac_init_idc);
1379 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1380 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1381 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1382 MAX_DELAYED_PIC_COUNT + 2, s, s1);
1384 h->last_slice_type = h1->last_slice_type;
1386 if (!s->current_picture_ptr)
1390 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1391 h->prev_poc_msb = h->poc_msb;
1392 h->prev_poc_lsb = h->poc_lsb;
1394 h->prev_frame_num_offset = h->frame_num_offset;
1395 h->prev_frame_num = h->frame_num;
1396 h->outputed_poc = h->next_outputed_poc;
1401 int ff_h264_frame_start(H264Context *h)
1403 MpegEncContext *const s = &h->s;
1405 const int pixel_shift = h->pixel_shift;
1407 if (ff_MPV_frame_start(s, s->avctx) < 0)
1409 ff_er_frame_start(s);
1411 * ff_MPV_frame_start uses pict_type to derive key_frame.
1412 * This is incorrect for H.264; IDR markings must be used.
1413 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1414 * See decode_nal_units().
1416 s->current_picture_ptr->f.key_frame = 0;
1417 s->current_picture_ptr->mmco_reset = 0;
1419 assert(s->linesize && s->uvlinesize);
1421 for (i = 0; i < 16; i++) {
1422 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1423 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1425 for (i = 0; i < 16; i++) {
1426 h->block_offset[16 + i] =
1427 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1428 h->block_offset[48 + 16 + i] =
1429 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1432 /* can't be in alloc_tables because linesize isn't known there.
1433 * FIXME: redo bipred weight to not require extra buffer? */
1434 for (i = 0; i < s->slice_context_count; i++)
1435 if (h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1436 h->thread_context[i]->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1438 /* Some macroblocks can be accessed before they're available in case
1439 * of lost slices, MBAFF or threading. */
1440 memset(h->slice_table, -1,
1441 (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1443 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1444 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1446 /* We mark the current picture as non-reference after allocating it, so
1447 * that if we break out due to an error it can be released automatically
1448 * in the next ff_MPV_frame_start().
1449 * SVQ3 as well as most other codecs have only last/next/current and thus
1450 * get released even with set reference, besides SVQ3 and others do not
1451 * mark frames as reference later "naturally". */
1452 if (s->codec_id != CODEC_ID_SVQ3)
1453 s->current_picture_ptr->f.reference = 0;
1455 s->current_picture_ptr->field_poc[0] =
1456 s->current_picture_ptr->field_poc[1] = INT_MAX;
1458 h->next_output_pic = NULL;
1460 assert(s->current_picture_ptr->long_ref == 0);
1466 * Run setup operations that must be run after slice header decoding.
1467 * This includes finding the next displayed frame.
1469 * @param h h264 master context
1470 * @param setup_finished enough NALs have been read that we can call
1471 * ff_thread_finish_setup()
1473 static void decode_postinit(H264Context *h, int setup_finished)
1475 MpegEncContext *const s = &h->s;
1476 Picture *out = s->current_picture_ptr;
1477 Picture *cur = s->current_picture_ptr;
1478 int i, pics, out_of_order, out_idx;
1479 int invalid = 0, cnt = 0;
1481 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1482 s->current_picture_ptr->f.pict_type = s->pict_type;
1484 if (h->next_output_pic)
1487 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1488 /* FIXME: if we have two PAFF fields in one packet, we can't start
1489 * the next thread here. If we have one field per packet, we can.
1490 * The check in decode_nal_units() is not good enough to find this
1491 * yet, so we assume the worst for now. */
1492 // if (setup_finished)
1493 // ff_thread_finish_setup(s->avctx);
1497 cur->f.interlaced_frame = 0;
1498 cur->f.repeat_pict = 0;
1500 /* Signal interlacing information externally. */
1501 /* Prioritize picture timing SEI information over used
1502 * decoding process if it exists. */
1504 if (h->sps.pic_struct_present_flag) {
1505 switch (h->sei_pic_struct) {
1506 case SEI_PIC_STRUCT_FRAME:
1508 case SEI_PIC_STRUCT_TOP_FIELD:
1509 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1510 cur->f.interlaced_frame = 1;
1512 case SEI_PIC_STRUCT_TOP_BOTTOM:
1513 case SEI_PIC_STRUCT_BOTTOM_TOP:
1514 if (FIELD_OR_MBAFF_PICTURE)
1515 cur->f.interlaced_frame = 1;
1517 // try to flag soft telecine progressive
1518 cur->f.interlaced_frame = h->prev_interlaced_frame;
1520 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1521 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1522 /* Signal the possibility of telecined film externally
1523 * (pic_struct 5,6). From these hints, let the applications
1524 * decide if they apply deinterlacing. */
1525 cur->f.repeat_pict = 1;
1527 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1528 // Force progressive here, doubling interlaced frame is a bad idea.
1529 cur->f.repeat_pict = 2;
1531 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1532 cur->f.repeat_pict = 4;
1536 if ((h->sei_ct_type & 3) &&
1537 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1538 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1540 /* Derive interlacing flag from used decoding process. */
1541 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1543 h->prev_interlaced_frame = cur->f.interlaced_frame;
1545 if (cur->field_poc[0] != cur->field_poc[1]) {
1546 /* Derive top_field_first from field pocs. */
1547 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1549 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1550 /* Use picture timing SEI information. Even if it is a
1551 * information of a past frame, better than nothing. */
1552 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1553 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1554 cur->f.top_field_first = 1;
1556 cur->f.top_field_first = 0;
1558 /* Most likely progressive */
1559 cur->f.top_field_first = 0;
1563 // FIXME do something with unavailable reference frames
1565 /* Sort B-frames into display order */
1567 if (h->sps.bitstream_restriction_flag &&
1568 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1569 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1573 if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1574 !h->sps.bitstream_restriction_flag) {
1575 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1580 while (h->delayed_pic[pics])
1583 assert(pics <= MAX_DELAYED_PIC_COUNT);
1585 h->delayed_pic[pics++] = cur;
1586 if (cur->f.reference == 0)
1587 cur->f.reference = DELAYED_PIC_REF;
1589 /* Frame reordering. This code takes pictures from coding order and sorts
1590 * them by their incremental POC value into display order. It supports POC
1591 * gaps, MMCO reset codes and random resets.
1592 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1593 * and/or can be closed down with a MMCO reset code. In sequences where
1594 * there is no delay, we can't detect that (since the frame was already
1595 * output to the user), so we also set h->mmco_reset to detect the MMCO
1597 * FIXME: if we detect insufficient delays (as per s->avctx->has_b_frames),
1598 * we increase the delay between input and output. All frames affected by
1599 * the lag (e.g. those that should have been output before another frame
1600 * that we already returned to the user) will be dropped. This is a bug
1601 * that we will fix later. */
1602 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1603 cnt += out->poc < h->last_pocs[i];
1604 invalid += out->poc == INT_MIN;
1606 if (!h->mmco_reset && !cur->f.key_frame &&
1607 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1610 h->delayed_pic[pics - 2]->mmco_reset = 2;
1612 if (h->mmco_reset || cur->f.key_frame) {
1613 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1614 h->last_pocs[i] = INT_MIN;
1616 invalid = MAX_DELAYED_PIC_COUNT;
1618 out = h->delayed_pic[0];
1620 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1621 h->delayed_pic[i] &&
1622 !h->delayed_pic[i - 1]->mmco_reset &&
1623 !h->delayed_pic[i]->f.key_frame;
1625 if (h->delayed_pic[i]->poc < out->poc) {
1626 out = h->delayed_pic[i];
1629 if (s->avctx->has_b_frames == 0 &&
1630 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
1631 h->next_outputed_poc = INT_MIN;
1632 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1633 (out->poc < h->next_outputed_poc);
1635 if (h->sps.bitstream_restriction_flag &&
1636 s->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1637 } else if (out_of_order && pics - 1 == s->avctx->has_b_frames &&
1638 s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1639 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1640 s->avctx->has_b_frames = FFMAX(s->avctx->has_b_frames, cnt);
1643 } else if (s->low_delay &&
1644 ((h->next_outputed_poc != INT_MIN &&
1645 out->poc > h->next_outputed_poc + 2) ||
1646 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
1648 s->avctx->has_b_frames++;
1651 if (pics > s->avctx->has_b_frames) {
1652 out->f.reference &= ~DELAYED_PIC_REF;
1653 // for frame threading, the owner must be the second field's thread or
1654 // else the first thread can release the picture and reuse it unsafely
1656 for (i = out_idx; h->delayed_pic[i]; i++)
1657 h->delayed_pic[i] = h->delayed_pic[i + 1];
1659 memmove(h->last_pocs, &h->last_pocs[1],
1660 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1661 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1662 if (!out_of_order && pics > s->avctx->has_b_frames) {
1663 h->next_output_pic = out;
1664 if (out->mmco_reset) {
1666 h->next_outputed_poc = out->poc;
1667 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1669 h->next_outputed_poc = INT_MIN;
1672 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
1673 h->next_outputed_poc = INT_MIN;
1675 h->next_outputed_poc = out->poc;
1680 av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1684 ff_thread_finish_setup(s->avctx);
1687 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1688 uint8_t *src_cb, uint8_t *src_cr,
1689 int linesize, int uvlinesize,
1692 MpegEncContext *const s = &h->s;
1693 uint8_t *top_border;
1695 const int pixel_shift = h->pixel_shift;
1696 int chroma444 = CHROMA444;
1697 int chroma422 = CHROMA422;
1700 src_cb -= uvlinesize;
1701 src_cr -= uvlinesize;
1703 if (!simple && FRAME_MBAFF) {
1706 top_border = h->top_borders[0][s->mb_x];
1707 AV_COPY128(top_border, src_y + 15 * linesize);
1709 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1710 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1713 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1714 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1715 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1716 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1718 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1719 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1721 } else if (chroma422) {
1723 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1724 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1726 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1727 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1731 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1732 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1734 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1735 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1740 } else if (MB_MBAFF) {
1746 top_border = h->top_borders[top_idx][s->mb_x];
1747 /* There are two lines saved, the line above the the top macroblock
1748 * of a pair, and the line above the bottom macroblock. */
1749 AV_COPY128(top_border, src_y + 16 * linesize);
1751 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1753 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1756 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1757 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1758 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1759 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1761 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1762 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1764 } else if (chroma422) {
1766 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1767 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1769 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1770 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1774 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1775 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1777 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1778 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1784 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1785 uint8_t *src_cb, uint8_t *src_cr,
1786 int linesize, int uvlinesize,
1787 int xchg, int chroma444,
1788 int simple, int pixel_shift)
1790 MpegEncContext *const s = &h->s;
1791 int deblock_topleft;
1794 uint8_t *top_border_m1;
1795 uint8_t *top_border;
1797 if (!simple && FRAME_MBAFF) {
1802 top_idx = MB_MBAFF ? 0 : 1;
1806 if (h->deblocking_filter == 2) {
1807 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1808 deblock_top = h->top_type;
1810 deblock_topleft = (s->mb_x > 0);
1811 deblock_top = (s->mb_y > !!MB_FIELD);
1814 src_y -= linesize + 1 + pixel_shift;
1815 src_cb -= uvlinesize + 1 + pixel_shift;
1816 src_cr -= uvlinesize + 1 + pixel_shift;
1818 top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1819 top_border = h->top_borders[top_idx][s->mb_x];
1821 #define XCHG(a, b, xchg) \
1822 if (pixel_shift) { \
1824 AV_SWAP64(b + 0, a + 0); \
1825 AV_SWAP64(b + 8, a + 8); \
1835 if (deblock_topleft) {
1836 XCHG(top_border_m1 + (8 << pixel_shift),
1837 src_y - (7 << pixel_shift), 1);
1839 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1840 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1841 if (s->mb_x + 1 < s->mb_width) {
1842 XCHG(h->top_borders[top_idx][s->mb_x + 1],
1843 src_y + (17 << pixel_shift), 1);
1846 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1848 if (deblock_topleft) {
1849 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1850 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1852 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1853 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1854 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1855 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1856 if (s->mb_x + 1 < s->mb_width) {
1857 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1858 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1862 if (deblock_topleft) {
1863 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1864 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1866 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1867 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1873 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
1876 if (high_bit_depth) {
1877 return AV_RN32A(((int32_t *)mb) + index);
1879 return AV_RN16A(mb + index);
1882 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
1883 int index, int value)
1885 if (high_bit_depth) {
1886 AV_WN32A(((int32_t *)mb) + index, value);
1888 AV_WN16A(mb + index, value);
1891 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1892 int mb_type, int is_h264,
1894 int transform_bypass,
1898 uint8_t *dest_y, int p)
1900 MpegEncContext *const s = &h->s;
1901 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1902 void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1904 int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1905 block_offset += 16 * p;
1906 if (IS_INTRA4x4(mb_type)) {
1907 if (simple || !s->encoding) {
1908 if (IS_8x8DCT(mb_type)) {
1909 if (transform_bypass) {
1911 idct_add = s->dsp.add_pixels8;
1913 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1914 idct_add = h->h264dsp.h264_idct8_add;
1916 for (i = 0; i < 16; i += 4) {
1917 uint8_t *const ptr = dest_y + block_offset[i];
1918 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1919 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1920 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1922 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1923 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1924 (h->topright_samples_available << i) & 0x4000, linesize);
1926 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1927 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1929 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1934 if (transform_bypass) {
1936 idct_add = s->dsp.add_pixels4;
1938 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1939 idct_add = h->h264dsp.h264_idct_add;
1941 for (i = 0; i < 16; i++) {
1942 uint8_t *const ptr = dest_y + block_offset[i];
1943 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1945 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1946 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1951 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1952 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1953 assert(s->mb_y || linesize <= block_offset[i]);
1954 if (!topright_avail) {
1956 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1957 topright = (uint8_t *)&tr_high;
1959 tr = ptr[3 - linesize] * 0x01010101u;
1960 topright = (uint8_t *)&tr;
1963 topright = ptr + (4 << pixel_shift) - linesize;
1967 h->hpc.pred4x4[dir](ptr, topright, linesize);
1968 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1971 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1972 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1974 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1975 } else if (CONFIG_SVQ3_DECODER)
1976 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1983 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1985 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1986 if (!transform_bypass)
1987 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1989 h->dequant4_coeff[p][qscale][0]);
1991 static const uint8_t dc_mapping[16] = {
1992 0 * 16, 1 * 16, 4 * 16, 5 * 16,
1993 2 * 16, 3 * 16, 6 * 16, 7 * 16,
1994 8 * 16, 9 * 16, 12 * 16, 13 * 16,
1995 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1996 for (i = 0; i < 16; i++)
1997 dctcoef_set(h->mb + (p * 256 << pixel_shift),
1998 pixel_shift, dc_mapping[i],
1999 dctcoef_get(h->mb_luma_dc[p],
2003 } else if (CONFIG_SVQ3_DECODER)
2004 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2005 h->mb_luma_dc[p], qscale);
2009 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2010 int is_h264, int simple,
2011 int transform_bypass,
2015 uint8_t *dest_y, int p)
2017 MpegEncContext *const s = &h->s;
2018 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
2020 block_offset += 16 * p;
2021 if (!IS_INTRA4x4(mb_type)) {
2023 if (IS_INTRA16x16(mb_type)) {
2024 if (transform_bypass) {
2025 if (h->sps.profile_idc == 244 &&
2026 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2027 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2028 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2029 h->mb + (p * 256 << pixel_shift),
2032 for (i = 0; i < 16; i++)
2033 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2034 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2035 s->dsp.add_pixels4(dest_y + block_offset[i],
2036 h->mb + (i * 16 + p * 256 << pixel_shift),
2040 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2041 h->mb + (p * 256 << pixel_shift),
2043 h->non_zero_count_cache + p * 5 * 8);
2045 } else if (h->cbp & 15) {
2046 if (transform_bypass) {
2047 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2048 idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
2049 : s->dsp.add_pixels4;
2050 for (i = 0; i < 16; i += di)
2051 if (h->non_zero_count_cache[scan8[i + p * 16]])
2052 idct_add(dest_y + block_offset[i],
2053 h->mb + (i * 16 + p * 256 << pixel_shift),
2056 if (IS_8x8DCT(mb_type))
2057 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2058 h->mb + (p * 256 << pixel_shift),
2060 h->non_zero_count_cache + p * 5 * 8);
2062 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2063 h->mb + (p * 256 << pixel_shift),
2065 h->non_zero_count_cache + p * 5 * 8);
2068 } else if (CONFIG_SVQ3_DECODER) {
2069 for (i = 0; i < 16; i++)
2070 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2071 // FIXME benchmark weird rule, & below
2072 uint8_t *const ptr = dest_y + block_offset[i];
2073 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2074 s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2080 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple,
2083 MpegEncContext *const s = &h->s;
2084 const int mb_x = s->mb_x;
2085 const int mb_y = s->mb_y;
2086 const int mb_xy = h->mb_xy;
2087 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2088 uint8_t *dest_y, *dest_cb, *dest_cr;
2089 int linesize, uvlinesize /*dct_offset*/;
2091 int *block_offset = &h->block_offset[0];
2092 const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2093 /* is_h264 should always be true if SVQ3 is disabled. */
2094 const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
2095 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
2096 const int block_h = 16 >> s->chroma_y_shift;
2097 const int chroma422 = CHROMA422;
2099 dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2100 dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift) * 8 + mb_y * s->uvlinesize * block_h;
2101 dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift) * 8 + mb_y * s->uvlinesize * block_h;
2103 s->dsp.prefetch(dest_y + (s->mb_x & 3) * 4 * s->linesize + (64 << pixel_shift), s->linesize, 4);
2104 s->dsp.prefetch(dest_cb + (s->mb_x & 7) * s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
2106 h->list_counts[mb_xy] = h->list_count;
2108 if (!simple && MB_FIELD) {
2109 linesize = h->mb_linesize = s->linesize * 2;
2110 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2111 block_offset = &h->block_offset[48];
2112 if (mb_y & 1) { // FIXME move out of this function?
2113 dest_y -= s->linesize * 15;
2114 dest_cb -= s->uvlinesize * (block_h - 1);
2115 dest_cr -= s->uvlinesize * (block_h - 1);
2119 for (list = 0; list < h->list_count; list++) {
2120 if (!USES_LIST(mb_type, list))
2122 if (IS_16X16(mb_type)) {
2123 int8_t *ref = &h->ref_cache[list][scan8[0]];
2124 fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (s->mb_y & 1), 1);
2126 for (i = 0; i < 16; i += 4) {
2127 int ref = h->ref_cache[list][scan8[i]];
2129 fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,
2130 8, (16 + ref) ^ (s->mb_y & 1), 1);
2136 linesize = h->mb_linesize = s->linesize;
2137 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2138 // dct_offset = s->linesize * 16;
2141 if (!simple && IS_INTRA_PCM(mb_type)) {
2143 const int bit_depth = h->sps.bit_depth_luma;
2146 init_get_bits(&gb, (uint8_t *)h->mb,
2147 ff_h264_mb_sizes[h->sps.chroma_format_idc] * bit_depth);
2149 for (i = 0; i < 16; i++) {
2150 uint16_t *tmp_y = (uint16_t *)(dest_y + i * linesize);
2151 for (j = 0; j < 16; j++)
2152 tmp_y[j] = get_bits(&gb, bit_depth);
2154 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2155 if (!h->sps.chroma_format_idc) {
2156 for (i = 0; i < block_h; i++) {
2157 uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);
2158 for (j = 0; j < 8; j++)
2159 tmp_cb[j] = 1 << (bit_depth - 1);
2161 for (i = 0; i < block_h; i++) {
2162 uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);
2163 for (j = 0; j < 8; j++)
2164 tmp_cr[j] = 1 << (bit_depth - 1);
2167 for (i = 0; i < block_h; i++) {
2168 uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);
2169 for (j = 0; j < 8; j++)
2170 tmp_cb[j] = get_bits(&gb, bit_depth);
2172 for (i = 0; i < block_h; i++) {
2173 uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);
2174 for (j = 0; j < 8; j++)
2175 tmp_cr[j] = get_bits(&gb, bit_depth);
2180 for (i = 0; i < 16; i++)
2181 memcpy(dest_y + i * linesize, (uint8_t *)h->mb + i * 16, 16);
2182 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2183 if (!h->sps.chroma_format_idc) {
2184 for (i = 0; i < block_h; i++) {
2185 memset(dest_cb + i * uvlinesize, 128, 8);
2186 memset(dest_cr + i * uvlinesize, 128, 8);
2189 uint8_t *src_cb = (uint8_t *)h->mb + 256;
2190 uint8_t *src_cr = (uint8_t *)h->mb + 256 + block_h * 8;
2191 for (i = 0; i < block_h; i++) {
2192 memcpy(dest_cb + i * uvlinesize, src_cb + i * 8, 8);
2193 memcpy(dest_cr + i * uvlinesize, src_cr + i * 8, 8);
2199 if (IS_INTRA(mb_type)) {
2200 if (h->deblocking_filter)
2201 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
2202 uvlinesize, 1, 0, simple, pixel_shift);
2204 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2205 h->hpc.pred8x8[h->chroma_pred_mode](dest_cb, uvlinesize);
2206 h->hpc.pred8x8[h->chroma_pred_mode](dest_cr, uvlinesize);
2209 hl_decode_mb_predict_luma(h, mb_type, is_h264, simple,
2210 transform_bypass, pixel_shift,
2211 block_offset, linesize, dest_y, 0);
2213 if (h->deblocking_filter)
2214 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
2215 uvlinesize, 0, 0, simple, pixel_shift);
2216 } else if (is_h264) {
2218 hl_motion_422(h, dest_y, dest_cb, dest_cr,
2219 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2220 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2221 h->h264dsp.weight_h264_pixels_tab,
2222 h->h264dsp.biweight_h264_pixels_tab,
2225 hl_motion_420(h, dest_y, dest_cb, dest_cr,
2226 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2227 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2228 h->h264dsp.weight_h264_pixels_tab,
2229 h->h264dsp.biweight_h264_pixels_tab,
2234 hl_decode_mb_idct_luma(h, mb_type, is_h264, simple, transform_bypass,
2235 pixel_shift, block_offset, linesize, dest_y, 0);
2237 if ((simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) &&
2239 uint8_t *dest[2] = { dest_cb, dest_cr };
2240 if (transform_bypass) {
2241 if (IS_INTRA(mb_type) && h->sps.profile_idc == 244 &&
2242 (h->chroma_pred_mode == VERT_PRED8x8 ||
2243 h->chroma_pred_mode == HOR_PRED8x8)) {
2244 h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0],
2246 h->mb + (16 * 16 * 1 << pixel_shift),
2248 h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1],
2250 h->mb + (16 * 16 * 2 << pixel_shift),
2253 idct_add = s->dsp.add_pixels4;
2254 for (j = 1; j < 3; j++) {
2255 for (i = j * 16; i < j * 16 + 4; i++)
2256 if (h->non_zero_count_cache[scan8[i]] ||
2257 dctcoef_get(h->mb, pixel_shift, i * 16))
2258 idct_add(dest[j - 1] + block_offset[i],
2259 h->mb + (i * 16 << pixel_shift),
2262 for (i = j * 16 + 4; i < j * 16 + 8; i++)
2263 if (h->non_zero_count_cache[scan8[i + 4]] ||
2264 dctcoef_get(h->mb, pixel_shift, i * 16))
2265 idct_add(dest[j - 1] + block_offset[i + 4],
2266 h->mb + (i * 16 << pixel_shift),
2275 qp[0] = h->chroma_qp[0] + 3;
2276 qp[1] = h->chroma_qp[1] + 3;
2278 qp[0] = h->chroma_qp[0];
2279 qp[1] = h->chroma_qp[1];
2281 if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 0]])
2282 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 1 << pixel_shift),
2283 h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][qp[0]][0]);
2284 if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 1]])
2285 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 2 << pixel_shift),
2286 h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][qp[1]][0]);
2287 h->h264dsp.h264_idct_add8(dest, block_offset,
2289 h->non_zero_count_cache);
2290 } else if (CONFIG_SVQ3_DECODER) {
2291 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 1,
2292 h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][h->chroma_qp[0]][0]);
2293 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 2,
2294 h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][h->chroma_qp[1]][0]);
2295 for (j = 1; j < 3; j++) {
2296 for (i = j * 16; i < j * 16 + 4; i++)
2297 if (h->non_zero_count_cache[scan8[i]] || h->mb[i * 16]) {
2298 uint8_t *const ptr = dest[j - 1] + block_offset[i];
2299 ff_svq3_add_idct_c(ptr, h->mb + i * 16,
2301 ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
2308 if (h->cbp || IS_INTRA(mb_type)) {
2309 s->dsp.clear_blocks(h->mb);
2310 s->dsp.clear_blocks(h->mb + (24 * 16 << pixel_shift));
2314 static av_always_inline void hl_decode_mb_444_internal(H264Context *h,
2318 MpegEncContext *const s = &h->s;
2319 const int mb_x = s->mb_x;
2320 const int mb_y = s->mb_y;
2321 const int mb_xy = h->mb_xy;
2322 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2326 int *block_offset = &h->block_offset[0];
2327 const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2328 const int plane_count = (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) ? 3 : 1;
2330 for (p = 0; p < plane_count; p++) {
2331 dest[p] = s->current_picture.f.data[p] +
2332 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2333 s->dsp.prefetch(dest[p] + (s->mb_x & 3) * 4 * s->linesize + (64 << pixel_shift),
2337 h->list_counts[mb_xy] = h->list_count;
2339 if (!simple && MB_FIELD) {
2340 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize * 2;
2341 block_offset = &h->block_offset[48];
2342 if (mb_y & 1) // FIXME move out of this function?
2343 for (p = 0; p < 3; p++)
2344 dest[p] -= s->linesize * 15;
2347 for (list = 0; list < h->list_count; list++) {
2348 if (!USES_LIST(mb_type, list))
2350 if (IS_16X16(mb_type)) {
2351 int8_t *ref = &h->ref_cache[list][scan8[0]];
2352 fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (s->mb_y & 1), 1);
2354 for (i = 0; i < 16; i += 4) {
2355 int ref = h->ref_cache[list][scan8[i]];
2357 fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,
2358 8, (16 + ref) ^ (s->mb_y & 1), 1);
2364 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize;
2367 if (!simple && IS_INTRA_PCM(mb_type)) {
2369 const int bit_depth = h->sps.bit_depth_luma;
2371 init_get_bits(&gb, (uint8_t *)h->mb, 768 * bit_depth);
2373 for (p = 0; p < plane_count; p++)
2374 for (i = 0; i < 16; i++) {
2375 uint16_t *tmp = (uint16_t *)(dest[p] + i * linesize);
2376 for (j = 0; j < 16; j++)
2377 tmp[j] = get_bits(&gb, bit_depth);
2380 for (p = 0; p < plane_count; p++)
2381 for (i = 0; i < 16; i++)
2382 memcpy(dest[p] + i * linesize,
2383 (uint8_t *)h->mb + p * 256 + i * 16, 16);
2386 if (IS_INTRA(mb_type)) {
2387 if (h->deblocking_filter)
2388 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,
2389 linesize, 1, 1, simple, pixel_shift);
2391 for (p = 0; p < plane_count; p++)
2392 hl_decode_mb_predict_luma(h, mb_type, 1, simple,
2393 transform_bypass, pixel_shift,
2394 block_offset, linesize, dest[p], p);
2396 if (h->deblocking_filter)
2397 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,
2398 linesize, 0, 1, simple, pixel_shift);
2400 hl_motion(h, dest[0], dest[1], dest[2],
2401 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2402 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2403 h->h264dsp.weight_h264_pixels_tab,
2404 h->h264dsp.biweight_h264_pixels_tab, pixel_shift, 3);
2407 for (p = 0; p < plane_count; p++)
2408 hl_decode_mb_idct_luma(h, mb_type, 1, simple, transform_bypass,
2409 pixel_shift, block_offset, linesize,
2412 if (h->cbp || IS_INTRA(mb_type)) {
2413 s->dsp.clear_blocks(h->mb);
2414 s->dsp.clear_blocks(h->mb + (24 * 16 << pixel_shift));
2419 * Process a macroblock; this case avoids checks for expensive uncommon cases.
2421 #define hl_decode_mb_simple(sh, bits) \
2422 static void hl_decode_mb_simple_ ## bits(H264Context *h) \
2424 hl_decode_mb_internal(h, 1, sh); \
2427 hl_decode_mb_simple(0, 8)
2428 hl_decode_mb_simple(1, 16)
2431 * Process a macroblock; this handles edge cases, such as interlacing.
2433 static av_noinline void hl_decode_mb_complex(H264Context *h)
2435 hl_decode_mb_internal(h, 0, h->pixel_shift);
2438 static av_noinline void hl_decode_mb_444_complex(H264Context *h)
2440 hl_decode_mb_444_internal(h, 0, h->pixel_shift);
2443 static av_noinline void hl_decode_mb_444_simple(H264Context *h)
2445 hl_decode_mb_444_internal(h, 1, 0);
2448 void ff_h264_hl_decode_mb(H264Context *h)
2450 MpegEncContext *const s = &h->s;
2451 const int mb_xy = h->mb_xy;
2452 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2453 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2456 if (is_complex || h->pixel_shift)
2457 hl_decode_mb_444_complex(h);
2459 hl_decode_mb_444_simple(h);
2460 } else if (is_complex) {
2461 hl_decode_mb_complex(h);
2462 } else if (h->pixel_shift) {
2463 hl_decode_mb_simple_16(h);
2465 hl_decode_mb_simple_8(h);
2468 static int pred_weight_table(H264Context *h)
2470 MpegEncContext *const s = &h->s;
2472 int luma_def, chroma_def;
2475 h->use_weight_chroma = 0;
2476 h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
2477 if (h->sps.chroma_format_idc)
2478 h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
2479 luma_def = 1 << h->luma_log2_weight_denom;
2480 chroma_def = 1 << h->chroma_log2_weight_denom;
2482 for (list = 0; list < 2; list++) {
2483 h->luma_weight_flag[list] = 0;
2484 h->chroma_weight_flag[list] = 0;
2485 for (i = 0; i < h->ref_count[list]; i++) {
2486 int luma_weight_flag, chroma_weight_flag;
2488 luma_weight_flag = get_bits1(&s->gb);
2489 if (luma_weight_flag) {
2490 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
2491 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
2492 if (h->luma_weight[i][list][0] != luma_def ||
2493 h->luma_weight[i][list][1] != 0) {
2495 h->luma_weight_flag[list] = 1;
2498 h->luma_weight[i][list][0] = luma_def;
2499 h->luma_weight[i][list][1] = 0;
2502 if (h->sps.chroma_format_idc) {
2503 chroma_weight_flag = get_bits1(&s->gb);
2504 if (chroma_weight_flag) {
2506 for (j = 0; j < 2; j++) {
2507 h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
2508 h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
2509 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2510 h->chroma_weight[i][list][j][1] != 0) {
2511 h->use_weight_chroma = 1;
2512 h->chroma_weight_flag[list] = 1;
2517 for (j = 0; j < 2; j++) {
2518 h->chroma_weight[i][list][j][0] = chroma_def;
2519 h->chroma_weight[i][list][j][1] = 0;
2524 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2527 h->use_weight = h->use_weight || h->use_weight_chroma;
2532 * Initialize implicit_weight table.
2533 * @param field 0/1 initialize the weight for interlaced MBAFF
2534 * -1 initializes the rest
2536 static void implicit_weight_table(H264Context *h, int field)
2538 MpegEncContext *const s = &h->s;
2539 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2541 for (i = 0; i < 2; i++) {
2542 h->luma_weight_flag[i] = 0;
2543 h->chroma_weight_flag[i] = 0;
2547 if (s->picture_structure == PICT_FRAME) {
2548 cur_poc = s->current_picture_ptr->poc;
2550 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2552 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2553 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2555 h->use_weight_chroma = 0;
2559 ref_count0 = h->ref_count[0];
2560 ref_count1 = h->ref_count[1];
2562 cur_poc = s->current_picture_ptr->field_poc[field];
2564 ref_count0 = 16 + 2 * h->ref_count[0];
2565 ref_count1 = 16 + 2 * h->ref_count[1];
2569 h->use_weight_chroma = 2;
2570 h->luma_log2_weight_denom = 5;
2571 h->chroma_log2_weight_denom = 5;
2573 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2574 int poc0 = h->ref_list[0][ref0].poc;
2575 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2577 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2578 int poc1 = h->ref_list[1][ref1].poc;
2579 int td = av_clip(poc1 - poc0, -128, 127);
2581 int tb = av_clip(cur_poc - poc0, -128, 127);
2582 int tx = (16384 + (FFABS(td) >> 1)) / td;
2583 int dist_scale_factor = (tb * tx + 32) >> 8;
2584 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2585 w = 64 - dist_scale_factor;
2589 h->implicit_weight[ref0][ref1][0] =
2590 h->implicit_weight[ref0][ref1][1] = w;
2592 h->implicit_weight[ref0][ref1][field] = w;
2599 * instantaneous decoder refresh.
2601 static void idr(H264Context *h)
2603 ff_h264_remove_all_refs(h);
2604 h->prev_frame_num = 0;
2605 h->prev_frame_num_offset = 0;
2607 h->prev_poc_lsb = 0;
2610 /* forget old pics after a seek */
2611 static void flush_dpb(AVCodecContext *avctx)
2613 H264Context *h = avctx->priv_data;
2615 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2616 if (h->delayed_pic[i])
2617 h->delayed_pic[i]->f.reference = 0;
2618 h->delayed_pic[i] = NULL;
2620 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2621 h->last_pocs[i] = INT_MIN;
2622 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2623 h->prev_interlaced_frame = 1;
2625 if (h->s.current_picture_ptr)
2626 h->s.current_picture_ptr->f.reference = 0;
2627 h->s.first_field = 0;
2628 ff_h264_reset_sei(h);
2629 ff_mpeg_flush(avctx);
2632 static int init_poc(H264Context *h)
2634 MpegEncContext *const s = &h->s;
2635 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2637 Picture *cur = s->current_picture_ptr;
2639 h->frame_num_offset = h->prev_frame_num_offset;
2640 if (h->frame_num < h->prev_frame_num)
2641 h->frame_num_offset += max_frame_num;
2643 if (h->sps.poc_type == 0) {
2644 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2646 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2647 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2648 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2649 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2651 h->poc_msb = h->prev_poc_msb;
2652 // printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2654 field_poc[1] = h->poc_msb + h->poc_lsb;
2655 if (s->picture_structure == PICT_FRAME)
2656 field_poc[1] += h->delta_poc_bottom;
2657 } else if (h->sps.poc_type == 1) {
2658 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2661 if (h->sps.poc_cycle_length != 0)
2662 abs_frame_num = h->frame_num_offset + h->frame_num;
2666 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2669 expected_delta_per_poc_cycle = 0;
2670 for (i = 0; i < h->sps.poc_cycle_length; i++)
2671 // FIXME integrate during sps parse
2672 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2674 if (abs_frame_num > 0) {
2675 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2676 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2678 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2679 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2680 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2684 if (h->nal_ref_idc == 0)
2685 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2687 field_poc[0] = expectedpoc + h->delta_poc[0];
2688 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2690 if (s->picture_structure == PICT_FRAME)
2691 field_poc[1] += h->delta_poc[1];
2693 int poc = 2 * (h->frame_num_offset + h->frame_num);
2695 if (!h->nal_ref_idc)
2702 if (s->picture_structure != PICT_BOTTOM_FIELD)
2703 s->current_picture_ptr->field_poc[0] = field_poc[0];
2704 if (s->picture_structure != PICT_TOP_FIELD)
2705 s->current_picture_ptr->field_poc[1] = field_poc[1];
2706 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2712 * initialize scan tables
2714 static void init_scan_tables(H264Context *h)
2717 for (i = 0; i < 16; i++) {
2718 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2719 h->zigzag_scan[i] = T(zigzag_scan[i]);
2720 h->field_scan[i] = T(field_scan[i]);
2723 for (i = 0; i < 64; i++) {
2724 #define T(x) (x >> 3) | ((x & 7) << 3)
2725 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2726 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2727 h->field_scan8x8[i] = T(field_scan8x8[i]);
2728 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2731 if (h->sps.transform_bypass) { // FIXME same ugly
2732 h->zigzag_scan_q0 = zigzag_scan;
2733 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2734 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2735 h->field_scan_q0 = field_scan;
2736 h->field_scan8x8_q0 = field_scan8x8;
2737 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2739 h->zigzag_scan_q0 = h->zigzag_scan;
2740 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2741 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2742 h->field_scan_q0 = h->field_scan;
2743 h->field_scan8x8_q0 = h->field_scan8x8;
2744 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2748 static int field_end(H264Context *h, int in_setup)
2750 MpegEncContext *const s = &h->s;
2751 AVCodecContext *const avctx = s->avctx;
2755 if (!in_setup && !s->dropable)
2756 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2757 s->picture_structure == PICT_BOTTOM_FIELD);
2759 if (CONFIG_H264_VDPAU_DECODER &&
2760 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2761 ff_vdpau_h264_set_reference_frames(s);
2763 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2765 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2766 h->prev_poc_msb = h->poc_msb;
2767 h->prev_poc_lsb = h->poc_lsb;
2769 h->prev_frame_num_offset = h->frame_num_offset;
2770 h->prev_frame_num = h->frame_num;
2771 h->outputed_poc = h->next_outputed_poc;
2774 if (avctx->hwaccel) {
2775 if (avctx->hwaccel->end_frame(avctx) < 0)
2776 av_log(avctx, AV_LOG_ERROR,
2777 "hardware accelerator failed to decode picture\n");
2780 if (CONFIG_H264_VDPAU_DECODER &&
2781 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2782 ff_vdpau_h264_picture_complete(s);
2785 * FIXME: Error handling code does not seem to support interlaced
2786 * when slices span multiple rows
2787 * The ff_er_add_slice calls don't work right for bottom
2788 * fields; they cause massive erroneous error concealing
2789 * Error marking covers both fields (top and bottom).
2790 * This causes a mismatched s->error_count
2791 * and a bad error table. Further, the error count goes to
2792 * INT_MAX when called for bottom field, because mb_y is
2793 * past end by one (callers fault) and resync_mb_y != 0
2794 * causes problems for the first MB line, too.
2799 ff_MPV_frame_end(s);
2801 h->current_slice = 0;
2807 * Replicate H264 "master" context to thread contexts.
2809 static void clone_slice(H264Context *dst, H264Context *src)
2811 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2812 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2813 dst->s.current_picture = src->s.current_picture;
2814 dst->s.linesize = src->s.linesize;
2815 dst->s.uvlinesize = src->s.uvlinesize;
2816 dst->s.first_field = src->s.first_field;
2818 dst->prev_poc_msb = src->prev_poc_msb;
2819 dst->prev_poc_lsb = src->prev_poc_lsb;
2820 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2821 dst->prev_frame_num = src->prev_frame_num;
2822 dst->short_ref_count = src->short_ref_count;
2824 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2825 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2826 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2827 memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
2829 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2830 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2834 * Compute profile from profile_idc and constraint_set?_flags.
2838 * @return profile as defined by FF_PROFILE_H264_*
2840 int ff_h264_get_profile(SPS *sps)
2842 int profile = sps->profile_idc;
2844 switch (sps->profile_idc) {
2845 case FF_PROFILE_H264_BASELINE:
2846 // constraint_set1_flag set to 1
2847 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2849 case FF_PROFILE_H264_HIGH_10:
2850 case FF_PROFILE_H264_HIGH_422:
2851 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2852 // constraint_set3_flag set to 1
2853 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2861 * Decode a slice header.
2862 * This will also call ff_MPV_common_init() and frame_start() as needed.
2864 * @param h h264context
2865 * @param h0 h264 master context (differs from 'h' when doing sliced based
2866 * parallel decoding)
2868 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2870 static int decode_slice_header(H264Context *h, H264Context *h0)
2872 MpegEncContext *const s = &h->s;
2873 MpegEncContext *const s0 = &h0->s;
2874 unsigned int first_mb_in_slice;
2875 unsigned int pps_id;
2876 int num_ref_idx_active_override_flag;
2877 unsigned int slice_type, tmp, i, j;
2878 int default_ref_list_done = 0;
2879 int last_pic_structure, last_pic_dropable;
2881 /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2882 if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
2883 !h->nal_ref_idc && !h->pixel_shift) {
2884 s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
2885 s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
2887 s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
2888 s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
2891 first_mb_in_slice = get_ue_golomb(&s->gb);
2893 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2894 if (h0->current_slice && FIELD_PICTURE) {
2898 h0->current_slice = 0;
2899 if (!s0->first_field) {
2900 if (s->current_picture_ptr && !s->dropable &&
2901 s->current_picture_ptr->owner2 == s) {
2902 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2903 s->picture_structure == PICT_BOTTOM_FIELD);
2905 s->current_picture_ptr = NULL;
2909 slice_type = get_ue_golomb_31(&s->gb);
2910 if (slice_type > 9) {
2911 av_log(h->s.avctx, AV_LOG_ERROR,
2912 "slice type too large (%d) at %d %d\n",
2913 h->slice_type, s->mb_x, s->mb_y);
2916 if (slice_type > 4) {
2918 h->slice_type_fixed = 1;
2920 h->slice_type_fixed = 0;
2922 slice_type = golomb_to_pict_type[slice_type];
2923 if (slice_type == AV_PICTURE_TYPE_I ||
2924 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2925 default_ref_list_done = 1;
2927 h->slice_type = slice_type;
2928 h->slice_type_nos = slice_type & 3;
2930 // to make a few old functions happy, it's wrong though
2931 s->pict_type = h->slice_type;
2933 pps_id = get_ue_golomb(&s->gb);
2934 if (pps_id >= MAX_PPS_COUNT) {
2935 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2938 if (!h0->pps_buffers[pps_id]) {
2939 av_log(h->s.avctx, AV_LOG_ERROR,
2940 "non-existing PPS %u referenced\n",
2944 h->pps = *h0->pps_buffers[pps_id];
2946 if (!h0->sps_buffers[h->pps.sps_id]) {
2947 av_log(h->s.avctx, AV_LOG_ERROR,
2948 "non-existing SPS %u referenced\n",
2952 h->sps = *h0->sps_buffers[h->pps.sps_id];
2954 s->avctx->profile = ff_h264_get_profile(&h->sps);
2955 s->avctx->level = h->sps.level_idc;
2956 s->avctx->refs = h->sps.ref_frame_count;
2958 s->mb_width = h->sps.mb_width;
2959 s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2961 h->b_stride = s->mb_width * 4;
2963 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2965 s->width = 16 * s->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
2966 if (h->sps.frame_mbs_only_flag)
2967 s->height = 16 * s->mb_height - (1 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2969 s->height = 16 * s->mb_height - (2 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2971 if (s->context_initialized &&
2972 (s->width != s->avctx->width || s->height != s->avctx->height ||
2973 av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2975 av_log_missing_feature(s->avctx,
2976 "Width/height changing with threads is", 0);
2977 return -1; // width / height changed during parallelized decoding
2980 flush_dpb(s->avctx);
2981 ff_MPV_common_end(s);
2983 if (!s->context_initialized) {
2985 av_log(h->s.avctx, AV_LOG_ERROR,
2986 "Cannot (re-)initialize context during parallel decoding.\n");
2990 avcodec_set_dimensions(s->avctx, s->width, s->height);
2991 s->avctx->sample_aspect_ratio = h->sps.sar;
2992 av_assert0(s->avctx->sample_aspect_ratio.den);
2994 if (h->sps.video_signal_type_present_flag) {
2995 s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
2997 if (h->sps.colour_description_present_flag) {
2998 s->avctx->color_primaries = h->sps.color_primaries;
2999 s->avctx->color_trc = h->sps.color_trc;
3000 s->avctx->colorspace = h->sps.colorspace;
3004 if (h->sps.timing_info_present_flag) {
3005 int64_t den = h->sps.time_scale;
3006 if (h->x264_build < 44U)
3008 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
3009 h->sps.num_units_in_tick, den, 1 << 30);
3012 switch (h->sps.bit_depth_luma) {
3015 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3016 s->avctx->pix_fmt = PIX_FMT_GBRP9;
3018 s->avctx->pix_fmt = PIX_FMT_YUV444P9;
3019 } else if (CHROMA422)
3020 s->avctx->pix_fmt = PIX_FMT_YUV422P9;
3022 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
3026 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3027 s->avctx->pix_fmt = PIX_FMT_GBRP10;
3029 s->avctx->pix_fmt = PIX_FMT_YUV444P10;
3030 } else if (CHROMA422)
3031 s->avctx->pix_fmt = PIX_FMT_YUV422P10;
3033 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
3037 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
3038 s->avctx->pix_fmt = PIX_FMT_GBRP;
3040 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P
3042 } else if (CHROMA422) {
3043 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P
3046 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
3047 s->avctx->codec->pix_fmts ?
3048 s->avctx->codec->pix_fmts :
3049 s->avctx->color_range == AVCOL_RANGE_JPEG ?
3050 hwaccel_pixfmt_list_h264_jpeg_420 :
3051 ff_hwaccel_pixfmt_list_420);
3055 av_log(s->avctx, AV_LOG_ERROR,
3056 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3057 return AVERROR_INVALIDDATA;
3060 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
3063 if (ff_MPV_common_init(s) < 0) {
3064 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
3068 h->prev_interlaced_frame = 1;
3070 init_scan_tables(h);
3071 if (ff_h264_alloc_tables(h) < 0) {
3072 av_log(h->s.avctx, AV_LOG_ERROR,
3073 "Could not allocate memory for h264\n");
3074 return AVERROR(ENOMEM);
3077 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
3078 if (context_init(h) < 0) {
3079 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
3083 for (i = 1; i < s->slice_context_count; i++) {
3085 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
3086 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
3087 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
3088 c->h264dsp = h->h264dsp;
3091 c->pixel_shift = h->pixel_shift;
3092 init_scan_tables(c);
3093 clone_tables(c, h, i);
3096 for (i = 0; i < s->slice_context_count; i++)
3097 if (context_init(h->thread_context[i]) < 0) {
3098 av_log(h->s.avctx, AV_LOG_ERROR,
3099 "context_init() failed.\n");
3105 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3106 h->dequant_coeff_pps = pps_id;
3107 init_dequant_tables(h);
3110 h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
3113 h->mb_aff_frame = 0;
3114 last_pic_structure = s0->picture_structure;
3115 last_pic_dropable = s->dropable;
3116 s->dropable = h->nal_ref_idc == 0;
3117 if (h->sps.frame_mbs_only_flag) {
3118 s->picture_structure = PICT_FRAME;
3120 if (get_bits1(&s->gb)) { // field_pic_flag
3121 s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
3123 s->picture_structure = PICT_FRAME;
3124 h->mb_aff_frame = h->sps.mb_aff;
3127 h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
3129 if (h0->current_slice != 0) {
3130 if (last_pic_structure != s->picture_structure ||
3131 last_pic_dropable != s->dropable) {
3132 av_log(h->s.avctx, AV_LOG_ERROR,
3133 "Changing field mode (%d -> %d) between slices is not allowed\n",
3134 last_pic_structure, s->picture_structure);
3135 s->picture_structure = last_pic_structure;
3136 s->dropable = last_pic_dropable;
3137 return AVERROR_INVALIDDATA;
3140 /* Shorten frame num gaps so we don't have to allocate reference
3141 * frames just to throw them away */
3142 if (h->frame_num != h->prev_frame_num) {
3143 int unwrap_prev_frame_num = h->prev_frame_num;
3144 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3146 if (unwrap_prev_frame_num > h->frame_num)
3147 unwrap_prev_frame_num -= max_frame_num;
3149 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3150 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3151 if (unwrap_prev_frame_num < 0)
3152 unwrap_prev_frame_num += max_frame_num;
3154 h->prev_frame_num = unwrap_prev_frame_num;
3158 /* See if we have a decoded first field looking for a pair...
3159 * Here, we're using that to see if we should mark previously
3160 * decode frames as "finished".
3161 * We have to do that before the "dummy" in-between frame allocation,
3162 * since that can modify s->current_picture_ptr. */
3163 if (s0->first_field) {
3164 assert(s0->current_picture_ptr);
3165 assert(s0->current_picture_ptr->f.data[0]);
3166 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
3168 /* Mark old field/frame as completed */
3169 if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
3170 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
3171 last_pic_structure == PICT_BOTTOM_FIELD);
3174 /* figure out if we have a complementary field pair */
3175 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3176 /* Previous field is unmatched. Don't display it, but let it
3177 * remain for reference if marked as such. */
3178 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
3179 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
3180 last_pic_structure == PICT_TOP_FIELD);
3183 if (s0->current_picture_ptr->frame_num != h->frame_num) {
3184 /* This and previous field were reference, but had
3185 * different frame_nums. Consider this field first in
3186 * pair. Throw away previous field except for reference
3188 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
3189 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
3190 last_pic_structure == PICT_TOP_FIELD);
3193 /* Second field in complementary pair */
3194 if (!((last_pic_structure == PICT_TOP_FIELD &&
3195 s->picture_structure == PICT_BOTTOM_FIELD) ||
3196 (last_pic_structure == PICT_BOTTOM_FIELD &&
3197 s->picture_structure == PICT_TOP_FIELD))) {
3198 av_log(s->avctx, AV_LOG_ERROR,
3199 "Invalid field mode combination %d/%d\n",
3200 last_pic_structure, s->picture_structure);
3201 s->picture_structure = last_pic_structure;
3202 s->dropable = last_pic_dropable;
3203 return AVERROR_INVALIDDATA;
3204 } else if (last_pic_dropable != s->dropable) {
3205 av_log(s->avctx, AV_LOG_ERROR,
3206 "Cannot combine reference and non-reference fields in the same frame\n");
3207 av_log_ask_for_sample(s->avctx, NULL);
3208 s->picture_structure = last_pic_structure;
3209 s->dropable = last_pic_dropable;
3210 return AVERROR_INVALIDDATA;
3213 /* Take ownership of this buffer. Note that if another thread owned
3214 * the first field of this buffer, we're not operating on that pointer,
3215 * so the original thread is still responsible for reporting progress
3216 * on that first field (or if that was us, we just did that above).
3217 * By taking ownership, we assign responsibility to ourselves to
3218 * report progress on the second field. */
3219 s0->current_picture_ptr->owner2 = s0;
3224 while (h->frame_num != h->prev_frame_num &&
3225 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3226 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3227 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3228 h->frame_num, h->prev_frame_num);
3229 if (ff_h264_frame_start(h) < 0)
3231 h->prev_frame_num++;
3232 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3233 s->current_picture_ptr->frame_num = h->prev_frame_num;
3234 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
3235 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
3236 ff_generate_sliding_window_mmcos(h);
3237 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3238 (s->avctx->err_recognition & AV_EF_EXPLODE))
3239 return AVERROR_INVALIDDATA;
3240 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3241 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3242 * about there being no actual duplicates.
3243 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3244 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3246 if (h->short_ref_count) {
3248 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3249 (const uint8_t **)prev->f.data, prev->f.linesize,
3250 s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
3251 h->short_ref[0]->poc = prev->poc + 2;
3253 h->short_ref[0]->frame_num = h->prev_frame_num;
3257 /* See if we have a decoded first field looking for a pair...
3258 * We're using that to see whether to continue decoding in that
3259 * frame, or to allocate a new one. */
3260 if (s0->first_field) {
3261 assert(s0->current_picture_ptr);
3262 assert(s0->current_picture_ptr->f.data[0]);
3263 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
3265 /* figure out if we have a complementary field pair */
3266 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3267 /* Previous field is unmatched. Don't display it, but let it
3268 * remain for reference if marked as such. */
3269 s0->current_picture_ptr = NULL;
3270 s0->first_field = FIELD_PICTURE;
3272 if (s0->current_picture_ptr->frame_num != h->frame_num) {
3273 /* This and the previous field had different frame_nums.
3274 * Consider this field first in pair. Throw away previous
3275 * one except for reference purposes. */
3276 s0->first_field = 1;
3277 s0->current_picture_ptr = NULL;
3279 /* Second field in complementary pair */
3280 s0->first_field = 0;
3284 /* Frame or first field in a potentially complementary pair */
3285 assert(!s0->current_picture_ptr);
3286 s0->first_field = FIELD_PICTURE;
3289 if (!FIELD_PICTURE || s0->first_field) {
3290 if (ff_h264_frame_start(h) < 0) {
3291 s0->first_field = 0;
3295 ff_release_unused_pictures(s, 0);
3301 s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3303 assert(s->mb_num == s->mb_width * s->mb_height);
3304 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
3305 first_mb_in_slice >= s->mb_num) {
3306 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3309 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3310 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3311 if (s->picture_structure == PICT_BOTTOM_FIELD)
3312 s->resync_mb_y = s->mb_y = s->mb_y + 1;
3313 assert(s->mb_y < s->mb_height);
3315 if (s->picture_structure == PICT_FRAME) {
3316 h->curr_pic_num = h->frame_num;
3317 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3319 h->curr_pic_num = 2 * h->frame_num + 1;
3320 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3323 if (h->nal_unit_type == NAL_IDR_SLICE)
3324 get_ue_golomb(&s->gb); /* idr_pic_id */
3326 if (h->sps.poc_type == 0) {
3327 h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3329 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3330 h->delta_poc_bottom = get_se_golomb(&s->gb);
3333 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3334 h->delta_poc[0] = get_se_golomb(&s->gb);
3336 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3337 h->delta_poc[1] = get_se_golomb(&s->gb);
3342 if (h->pps.redundant_pic_cnt_present)
3343 h->redundant_pic_count = get_ue_golomb(&s->gb);
3345 // set defaults, might be overridden a few lines later
3346 h->ref_count[0] = h->pps.ref_count[0];
3347 h->ref_count[1] = h->pps.ref_count[1];
3349 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3350 int max_refs = s->picture_structure == PICT_FRAME ? 16 : 32;
3352 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3353 h->direct_spatial_mv_pred = get_bits1(&s->gb);
3354 num_ref_idx_active_override_flag = get_bits1(&s->gb);
3356 if (num_ref_idx_active_override_flag) {
3357 h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
3358 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3359 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
3362 if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
3363 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3364 h->ref_count[0] = h->ref_count[1] = 1;
3365 return AVERROR_INVALIDDATA;
3368 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3375 if (!default_ref_list_done)
3376 ff_h264_fill_default_ref_list(h);
3378 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
3379 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3380 h->ref_count[1] = h->ref_count[0] = 0;
3384 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3385 s->last_picture_ptr = &h->ref_list[0][0];
3386 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3388 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3389 s->next_picture_ptr = &h->ref_list[1][0];
3390 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3393 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3394 (h->pps.weighted_bipred_idc == 1 &&
3395 h->slice_type_nos == AV_PICTURE_TYPE_B))
3396 pred_weight_table(h);
3397 else if (h->pps.weighted_bipred_idc == 2 &&
3398 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3399 implicit_weight_table(h, -1);
3402 for (i = 0; i < 2; i++) {
3403 h->luma_weight_flag[i] = 0;
3404 h->chroma_weight_flag[i] = 0;
3408 if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
3409 (s->avctx->err_recognition & AV_EF_EXPLODE))
3410 return AVERROR_INVALIDDATA;
3413 ff_h264_fill_mbaff_ref_list(h);
3415 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3416 implicit_weight_table(h, 0);
3417 implicit_weight_table(h, 1);
3421 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3422 ff_h264_direct_dist_scale_factor(h);
3423 ff_h264_direct_ref_list_init(h);
3425 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3426 tmp = get_ue_golomb_31(&s->gb);
3428 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3431 h->cabac_init_idc = tmp;
3434 h->last_qscale_diff = 0;
3435 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3436 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3437 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3441 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3442 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3443 // FIXME qscale / qp ... stuff
3444 if (h->slice_type == AV_PICTURE_TYPE_SP)
3445 get_bits1(&s->gb); /* sp_for_switch_flag */
3446 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3447 h->slice_type == AV_PICTURE_TYPE_SI)
3448 get_se_golomb(&s->gb); /* slice_qs_delta */
3450 h->deblocking_filter = 1;
3451 h->slice_alpha_c0_offset = 52;
3452 h->slice_beta_offset = 52;
3453 if (h->pps.deblocking_filter_parameters_present) {
3454 tmp = get_ue_golomb_31(&s->gb);
3456 av_log(s->avctx, AV_LOG_ERROR,
3457 "deblocking_filter_idc %u out of range\n", tmp);
3460 h->deblocking_filter = tmp;
3461 if (h->deblocking_filter < 2)
3462 h->deblocking_filter ^= 1; // 1<->0
3464 if (h->deblocking_filter) {
3465 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3466 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3467 if (h->slice_alpha_c0_offset > 104U ||
3468 h->slice_beta_offset > 104U) {
3469 av_log(s->avctx, AV_LOG_ERROR,
3470 "deblocking filter parameters %d %d out of range\n",
3471 h->slice_alpha_c0_offset, h->slice_beta_offset);
3477 if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3478 (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3479 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3480 (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3481 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3482 (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3483 h->nal_ref_idc == 0))
3484 h->deblocking_filter = 0;
3486 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3487 if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3488 /* Cheat slightly for speed:
3489 * Do not bother to deblock across slices. */
3490 h->deblocking_filter = 2;
3492 h0->max_contexts = 1;
3493 if (!h0->single_decode_warning) {
3494 av_log(s->avctx, AV_LOG_INFO,
3495 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3496 h0->single_decode_warning = 1;
3499 av_log(h->s.avctx, AV_LOG_ERROR,
3500 "Deblocking switched inside frame.\n");
3505 h->qp_thresh = 15 + 52 -
3506 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3508 h->pps.chroma_qp_index_offset[0],
3509 h->pps.chroma_qp_index_offset[1]) +
3510 6 * (h->sps.bit_depth_luma - 8);
3512 h0->last_slice_type = slice_type;
3513 h->slice_num = ++h0->current_slice;
3514 if (h->slice_num >= MAX_SLICES) {
3515 av_log(s->avctx, AV_LOG_ERROR,
3516 "Too many slices, increase MAX_SLICES and recompile\n");
3519 for (j = 0; j < 2; j++) {
3521 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3522 for (i = 0; i < 16; i++) {
3524 if (h->ref_list[j][i].f.data[0]) {
3526 uint8_t *base = h->ref_list[j][i].f.base[0];
3527 for (k = 0; k < h->short_ref_count; k++)
3528 if (h->short_ref[k]->f.base[0] == base) {
3532 for (k = 0; k < h->long_ref_count; k++)
3533 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3534 id_list[i] = h->short_ref_count + k;
3542 for (i = 0; i < 16; i++)
3543 ref2frm[i + 2] = 4 * id_list[i] +
3544 (h->ref_list[j][i].f.reference & 3);
3546 ref2frm[18 + 1] = -1;
3547 for (i = 16; i < 48; i++)
3548 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3549 (h->ref_list[j][i].f.reference & 3);
3552 // FIXME: fix draw_edges + PAFF + frame threads
3553 h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
3554 (!h->sps.frame_mbs_only_flag &&
3555 s->avctx->active_thread_type))
3557 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3559 if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3560 av_log(h->s.avctx, AV_LOG_DEBUG,
3561 "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",
3563 (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3565 av_get_picture_type_char(h->slice_type),
3566 h->slice_type_fixed ? " fix" : "",
3567 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3568 pps_id, h->frame_num,
3569 s->current_picture_ptr->field_poc[0],
3570 s->current_picture_ptr->field_poc[1],
3571 h->ref_count[0], h->ref_count[1],
3573 h->deblocking_filter,
3574 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3576 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3577 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3583 int ff_h264_get_slice_type(const H264Context *h)
3585 switch (h->slice_type) {
3586 case AV_PICTURE_TYPE_P:
3588 case AV_PICTURE_TYPE_B:
3590 case AV_PICTURE_TYPE_I:
3592 case AV_PICTURE_TYPE_SP:
3594 case AV_PICTURE_TYPE_SI:
3601 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3602 MpegEncContext *const s,
3603 int mb_type, int top_xy,
3604 int left_xy[LEFT_MBS],
3606 int left_type[LEFT_MBS],
3607 int mb_xy, int list)
3609 int b_stride = h->b_stride;
3610 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3611 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3612 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3613 if (USES_LIST(top_type, list)) {
3614 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3615 const int b8_xy = 4 * top_xy + 2;
3616 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3617 AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
3618 ref_cache[0 - 1 * 8] =
3619 ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3620 ref_cache[2 - 1 * 8] =
3621 ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3623 AV_ZERO128(mv_dst - 1 * 8);
3624 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3627 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3628 if (USES_LIST(left_type[LTOP], list)) {
3629 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3630 const int b8_xy = 4 * left_xy[LTOP] + 1;
3631 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3632 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
3633 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
3634 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
3635 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
3637 ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
3638 ref_cache[-1 + 16] =
3639 ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
3641 AV_ZERO32(mv_dst - 1 + 0);
3642 AV_ZERO32(mv_dst - 1 + 8);
3643 AV_ZERO32(mv_dst - 1 + 16);
3644 AV_ZERO32(mv_dst - 1 + 24);
3647 ref_cache[-1 + 16] =
3648 ref_cache[-1 + 24] = LIST_NOT_USED;
3653 if (!USES_LIST(mb_type, list)) {
3654 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3655 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3656 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3657 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3658 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3663 int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
3664 int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3665 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3666 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3667 AV_WN32A(&ref_cache[0 * 8], ref01);
3668 AV_WN32A(&ref_cache[1 * 8], ref01);
3669 AV_WN32A(&ref_cache[2 * 8], ref23);
3670 AV_WN32A(&ref_cache[3 * 8], ref23);
3674 int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
3675 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3676 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3677 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3678 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3684 * @return non zero if the loop filter can be skipped
3686 static int fill_filter_caches(H264Context *h, int mb_type)
3688 MpegEncContext *const s = &h->s;
3689 const int mb_xy = h->mb_xy;
3690 int top_xy, left_xy[LEFT_MBS];
3691 int top_type, left_type[LEFT_MBS];
3695 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3697 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3698 * stuff, I can't imagine that these complex rules are worth it. */
3700 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3702 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3703 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3705 if (left_mb_field_flag != curr_mb_field_flag)
3706 left_xy[LTOP] -= s->mb_stride;
3708 if (curr_mb_field_flag)
3709 top_xy += s->mb_stride &
3710 (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3711 if (left_mb_field_flag != curr_mb_field_flag)
3712 left_xy[LBOT] += s->mb_stride;
3716 h->top_mb_xy = top_xy;
3717 h->left_mb_xy[LTOP] = left_xy[LTOP];
3718 h->left_mb_xy[LBOT] = left_xy[LBOT];
3720 /* For sufficiently low qp, filtering wouldn't do anything.
3721 * This is a conservative estimate: could also check beta_offset
3722 * and more accurate chroma_qp. */
3723 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3724 int qp = s->current_picture.f.qscale_table[mb_xy];
3725 if (qp <= qp_thresh &&
3726 (left_xy[LTOP] < 0 ||
3727 ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3729 ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3732 if ((left_xy[LTOP] < 0 ||
3733 ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3734 (top_xy < s->mb_stride ||
3735 ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3740 top_type = s->current_picture.f.mb_type[top_xy];
3741 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3742 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3743 if (h->deblocking_filter == 2) {
3744 if (h->slice_table[top_xy] != h->slice_num)
3746 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3747 left_type[LTOP] = left_type[LBOT] = 0;
3749 if (h->slice_table[top_xy] == 0xFFFF)
3751 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3752 left_type[LTOP] = left_type[LBOT] = 0;
3754 h->top_type = top_type;
3755 h->left_type[LTOP] = left_type[LTOP];
3756 h->left_type[LBOT] = left_type[LBOT];
3758 if (IS_INTRA(mb_type))
3761 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3762 top_type, left_type, mb_xy, 0);
3763 if (h->list_count == 2)
3764 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3765 top_type, left_type, mb_xy, 1);
3767 nnz = h->non_zero_count[mb_xy];
3768 nnz_cache = h->non_zero_count_cache;
3769 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3770 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3771 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3772 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3773 h->cbp = h->cbp_table[mb_xy];
3776 nnz = h->non_zero_count[top_xy];
3777 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3780 if (left_type[LTOP]) {
3781 nnz = h->non_zero_count[left_xy[LTOP]];
3782 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3783 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3784 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3785 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3788 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3789 * from what the loop filter needs */
3790 if (!CABAC && h->pps.transform_8x8_mode) {
3791 if (IS_8x8DCT(top_type)) {
3792 nnz_cache[4 + 8 * 0] =
3793 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3794 nnz_cache[6 + 8 * 0] =
3795 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3797 if (IS_8x8DCT(left_type[LTOP])) {
3798 nnz_cache[3 + 8 * 1] =
3799 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3801 if (IS_8x8DCT(left_type[LBOT])) {
3802 nnz_cache[3 + 8 * 3] =
3803 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3806 if (IS_8x8DCT(mb_type)) {
3807 nnz_cache[scan8[0]] =
3808 nnz_cache[scan8[1]] =
3809 nnz_cache[scan8[2]] =
3810 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3812 nnz_cache[scan8[0 + 4]] =
3813 nnz_cache[scan8[1 + 4]] =
3814 nnz_cache[scan8[2 + 4]] =
3815 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3817 nnz_cache[scan8[0 + 8]] =
3818 nnz_cache[scan8[1 + 8]] =
3819 nnz_cache[scan8[2 + 8]] =
3820 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3822 nnz_cache[scan8[0 + 12]] =
3823 nnz_cache[scan8[1 + 12]] =
3824 nnz_cache[scan8[2 + 12]] =
3825 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3832 static void loop_filter(H264Context *h, int start_x, int end_x)
3834 MpegEncContext *const s = &h->s;
3835 uint8_t *dest_y, *dest_cb, *dest_cr;
3836 int linesize, uvlinesize, mb_x, mb_y;
3837 const int end_mb_y = s->mb_y + FRAME_MBAFF;
3838 const int old_slice_type = h->slice_type;
3839 const int pixel_shift = h->pixel_shift;
3840 const int block_h = 16 >> s->chroma_y_shift;
3842 if (h->deblocking_filter) {
3843 for (mb_x = start_x; mb_x < end_x; mb_x++)
3844 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
3846 mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
3847 h->slice_num = h->slice_table[mb_xy];
3848 mb_type = s->current_picture.f.mb_type[mb_xy];
3849 h->list_count = h->list_counts[mb_xy];
3853 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3857 dest_y = s->current_picture.f.data[0] +
3858 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
3859 dest_cb = s->current_picture.f.data[1] +
3860 (mb_x << pixel_shift) * (8 << CHROMA444) +
3861 mb_y * s->uvlinesize * block_h;
3862 dest_cr = s->current_picture.f.data[2] +
3863 (mb_x << pixel_shift) * (8 << CHROMA444) +
3864 mb_y * s->uvlinesize * block_h;
3865 // FIXME simplify above
3868 linesize = h->mb_linesize = s->linesize * 2;
3869 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3870 if (mb_y & 1) { // FIXME move out of this function?
3871 dest_y -= s->linesize * 15;
3872 dest_cb -= s->uvlinesize * (block_h - 1);
3873 dest_cr -= s->uvlinesize * (block_h - 1);
3876 linesize = h->mb_linesize = s->linesize;
3877 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3879 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
3881 if (fill_filter_caches(h, mb_type))
3883 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3884 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3887 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
3888 linesize, uvlinesize);
3890 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
3891 dest_cr, linesize, uvlinesize);
3895 h->slice_type = old_slice_type;
3897 s->mb_y = end_mb_y - FRAME_MBAFF;
3898 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3899 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3902 static void predict_field_decoding_flag(H264Context *h)
3904 MpegEncContext *const s = &h->s;
3905 const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
3906 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
3907 s->current_picture.f.mb_type[mb_xy - 1] :
3908 (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
3909 s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
3910 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3914 * Draw edges and report progress for the last MB row.
3916 static void decode_finish_row(H264Context *h)
3918 MpegEncContext *const s = &h->s;
3919 int top = 16 * (s->mb_y >> FIELD_PICTURE);
3920 int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
3921 int height = 16 << FRAME_MBAFF;
3922 int deblock_border = (16 + 4) << FRAME_MBAFF;
3924 if (h->deblocking_filter) {
3925 if ((top + height) >= pic_height)
3926 height += deblock_border;
3927 top -= deblock_border;
3930 if (top >= pic_height || (top + height) < h->emu_edge_height)
3933 height = FFMIN(height, pic_height - top);
3934 if (top < h->emu_edge_height) {
3935 height = top + height;
3939 ff_draw_horiz_band(s, top, height);
3944 ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
3945 s->picture_structure == PICT_BOTTOM_FIELD);
3948 static int decode_slice(struct AVCodecContext *avctx, void *arg)
3950 H264Context *h = *(void **)arg;
3951 MpegEncContext *const s = &h->s;
3952 const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
3954 int lf_x_start = s->mb_x;
3956 s->mb_skip_run = -1;
3958 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
3959 s->codec_id != CODEC_ID_H264 ||
3960 (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
3964 align_get_bits(&s->gb);
3967 ff_init_cabac_states(&h->cabac);
3968 ff_init_cabac_decoder(&h->cabac,
3969 s->gb.buffer + get_bits_count(&s->gb) / 8,
3970 (get_bits_left(&s->gb) + 7) / 8);
3972 ff_h264_init_cabac_states(h);
3976 int ret = ff_h264_decode_mb_cabac(h);
3978 // STOP_TIMER("decode_mb_cabac")
3981 ff_h264_hl_decode_mb(h);
3983 // FIXME optimal? or let mb_decode decode 16x32 ?
3984 if (ret >= 0 && FRAME_MBAFF) {
3987 ret = ff_h264_decode_mb_cabac(h);
3990 ff_h264_hl_decode_mb(h);
3993 eos = get_cabac_terminate(&h->cabac);
3995 if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
3996 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3997 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3998 s->mb_y, ER_MB_END & part_mask);
3999 if (s->mb_x >= lf_x_start)
4000 loop_filter(h, lf_x_start, s->mb_x + 1);
4003 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4004 av_log(h->s.avctx, AV_LOG_ERROR,
4005 "error while decoding MB %d %d, bytestream (%td)\n",
4007 h->cabac.bytestream_end - h->cabac.bytestream);
4008 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
4009 s->mb_y, ER_MB_ERROR & part_mask);
4013 if (++s->mb_x >= s->mb_width) {
4014 loop_filter(h, lf_x_start, s->mb_x);
4015 s->mb_x = lf_x_start = 0;
4016 decode_finish_row(h);
4018 if (FIELD_OR_MBAFF_PICTURE) {
4020 if (FRAME_MBAFF && s->mb_y < s->mb_height)
4021 predict_field_decoding_flag(h);
4025 if (eos || s->mb_y >= s->mb_height) {
4026 tprintf(s->avctx, "slice end %d %d\n",
4027 get_bits_count(&s->gb), s->gb.size_in_bits);
4028 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
4029 s->mb_y, ER_MB_END & part_mask);
4030 if (s->mb_x > lf_x_start)
4031 loop_filter(h, lf_x_start, s->mb_x);
4037 int ret = ff_h264_decode_mb_cavlc(h);
4040 ff_h264_hl_decode_mb(h);
4042 // FIXME optimal? or let mb_decode decode 16x32 ?
4043 if (ret >= 0 && FRAME_MBAFF) {
4045 ret = ff_h264_decode_mb_cavlc(h);
4048 ff_h264_hl_decode_mb(h);
4053 av_log(h->s.avctx, AV_LOG_ERROR,
4054 "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
4055 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
4056 s->mb_y, ER_MB_ERROR & part_mask);
4060 if (++s->mb_x >= s->mb_width) {
4061 loop_filter(h, lf_x_start, s->mb_x);
4062 s->mb_x = lf_x_start = 0;
4063 decode_finish_row(h);
4065 if (FIELD_OR_MBAFF_PICTURE) {
4067 if (FRAME_MBAFF && s->mb_y < s->mb_height)
4068 predict_field_decoding_flag(h);
4070 if (s->mb_y >= s->mb_height) {
4071 tprintf(s->avctx, "slice end %d %d\n",
4072 get_bits_count(&s->gb), s->gb.size_in_bits);
4074 if (get_bits_left(&s->gb) == 0) {
4075 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
4076 s->mb_x - 1, s->mb_y,
4077 ER_MB_END & part_mask);
4081 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
4083 ER_MB_END & part_mask);
4090 if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
4091 tprintf(s->avctx, "slice end %d %d\n",
4092 get_bits_count(&s->gb), s->gb.size_in_bits);
4093 if (get_bits_left(&s->gb) == 0) {
4094 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
4095 s->mb_x - 1, s->mb_y,
4096 ER_MB_END & part_mask);
4097 if (s->mb_x > lf_x_start)
4098 loop_filter(h, lf_x_start, s->mb_x);
4102 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
4103 s->mb_y, ER_MB_ERROR & part_mask);
4113 * Call decode_slice() for each context.
4115 * @param h h264 master context
4116 * @param context_count number of contexts to execute
4118 static int execute_decode_slices(H264Context *h, int context_count)
4120 MpegEncContext *const s = &h->s;
4121 AVCodecContext *const avctx = s->avctx;
4125 if (s->avctx->hwaccel ||
4126 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4128 if (context_count == 1) {
4129 return decode_slice(avctx, &h);
4131 for (i = 1; i < context_count; i++) {
4132 hx = h->thread_context[i];
4133 hx->s.err_recognition = avctx->err_recognition;
4134 hx->s.error_count = 0;
4137 avctx->execute(avctx, decode_slice, h->thread_context,
4138 NULL, context_count, sizeof(void *));
4140 /* pull back stuff from slices to master context */
4141 hx = h->thread_context[context_count - 1];
4142 s->mb_x = hx->s.mb_x;
4143 s->mb_y = hx->s.mb_y;
4144 s->dropable = hx->s.dropable;
4145 s->picture_structure = hx->s.picture_structure;
4146 for (i = 1; i < context_count; i++)
4147 h->s.error_count += h->thread_context[i]->s.error_count;
4153 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
4155 MpegEncContext *const s = &h->s;
4156 AVCodecContext *const avctx = s->avctx;
4157 H264Context *hx; ///< thread context
4161 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4162 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4165 h->max_contexts = s->slice_context_count;
4166 if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
4167 h->current_slice = 0;
4168 if (!s->first_field)
4169 s->current_picture_ptr = NULL;
4170 ff_h264_reset_sei(h);
4173 for (; pass <= 1; pass++) {
4176 next_avc = h->is_avc ? 0 : buf_size;
4186 if (buf_index >= next_avc) {
4187 if (buf_index >= buf_size - h->nal_length_size)
4190 for (i = 0; i < h->nal_length_size; i++)
4191 nalsize = (nalsize << 8) | buf[buf_index++];
4192 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4193 av_log(h->s.avctx, AV_LOG_ERROR,
4194 "AVC: nal size %d\n", nalsize);
4197 next_avc = buf_index + nalsize;
4199 // start code prefix search
4200 for (; buf_index + 3 < next_avc; buf_index++)
4201 // This should always succeed in the first iteration.
4202 if (buf[buf_index] == 0 &&
4203 buf[buf_index + 1] == 0 &&
4204 buf[buf_index + 2] == 1)
4207 if (buf_index + 3 >= buf_size)
4211 if (buf_index >= next_avc)
4215 hx = h->thread_context[context_count];
4217 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4218 &consumed, next_avc - buf_index);
4219 if (ptr == NULL || dst_length < 0) {
4223 i = buf_index + consumed;
4224 if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4225 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4226 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4227 s->workaround_bugs |= FF_BUG_TRUNCATED;
4229 if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
4230 while (ptr[dst_length - 1] == 0 && dst_length > 0)
4232 bit_length = !dst_length ? 0
4234 decode_rbsp_trailing(h, ptr + dst_length - 1));
4236 if (s->avctx->debug & FF_DEBUG_STARTCODE)
4237 av_log(h->s.avctx, AV_LOG_DEBUG,
4238 "NAL %d at %d/%d length %d\n",
4239 hx->nal_unit_type, buf_index, buf_size, dst_length);
4241 if (h->is_avc && (nalsize != consumed) && nalsize)
4242 av_log(h->s.avctx, AV_LOG_DEBUG,
4243 "AVC: Consumed only %d bytes instead of %d\n",
4246 buf_index += consumed;
4250 /* packets can sometimes contain multiple PPS/SPS,
4251 * e.g. two PAFF field pictures in one packet, or a demuxer
4252 * which splits NALs strangely if so, when frame threading we
4253 * can't start the next thread until we've read all of them */
4254 switch (hx->nal_unit_type) {
4257 nals_needed = nal_index;
4261 init_get_bits(&hx->s.gb, ptr, bit_length);
4262 if (!get_ue_golomb(&hx->s.gb))
4263 nals_needed = nal_index;
4268 // FIXME do not discard SEI id
4269 if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
4274 switch (hx->nal_unit_type) {
4276 if (h->nal_unit_type != NAL_IDR_SLICE) {
4277 av_log(h->s.avctx, AV_LOG_ERROR,
4278 "Invalid mix of idr and non-idr slices");
4282 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4284 init_get_bits(&hx->s.gb, ptr, bit_length);
4286 hx->inter_gb_ptr = &hx->s.gb;
4287 hx->s.data_partitioning = 0;
4289 if ((err = decode_slice_header(hx, h)))
4292 s->current_picture_ptr->f.key_frame |=
4293 (hx->nal_unit_type == NAL_IDR_SLICE) ||
4294 (h->sei_recovery_frame_cnt >= 0);
4296 if (h->current_slice == 1) {
4297 if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
4298 decode_postinit(h, nal_index >= nals_needed);
4300 if (s->avctx->hwaccel &&
4301 s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
4303 if (CONFIG_H264_VDPAU_DECODER &&
4304 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4305 ff_vdpau_h264_picture_start(s);
4308 if (hx->redundant_pic_count == 0 &&
4309 (avctx->skip_frame < AVDISCARD_NONREF ||
4311 (avctx->skip_frame < AVDISCARD_BIDIR ||
4312 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4313 (avctx->skip_frame < AVDISCARD_NONKEY ||
4314 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4315 avctx->skip_frame < AVDISCARD_ALL) {
4316 if (avctx->hwaccel) {
4317 if (avctx->hwaccel->decode_slice(avctx,
4318 &buf[buf_index - consumed],
4321 } else if (CONFIG_H264_VDPAU_DECODER &&
4322 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4323 static const uint8_t start_code[] = {
4325 ff_vdpau_add_data_chunk(s, start_code,
4326 sizeof(start_code));
4327 ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
4334 init_get_bits(&hx->s.gb, ptr, bit_length);
4336 hx->inter_gb_ptr = NULL;
4338 if ((err = decode_slice_header(hx, h)) < 0)
4341 hx->s.data_partitioning = 1;
4344 init_get_bits(&hx->intra_gb, ptr, bit_length);
4345 hx->intra_gb_ptr = &hx->intra_gb;
4348 init_get_bits(&hx->inter_gb, ptr, bit_length);
4349 hx->inter_gb_ptr = &hx->inter_gb;
4351 if (hx->redundant_pic_count == 0 &&
4353 hx->s.data_partitioning &&
4354 s->context_initialized &&
4355 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4356 (avctx->skip_frame < AVDISCARD_BIDIR ||
4357 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4358 (avctx->skip_frame < AVDISCARD_NONKEY ||
4359 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4360 avctx->skip_frame < AVDISCARD_ALL)
4364 init_get_bits(&s->gb, ptr, bit_length);
4365 ff_h264_decode_sei(h);
4368 init_get_bits(&s->gb, ptr, bit_length);
4369 if (ff_h264_decode_seq_parameter_set(h) < 0 &&
4370 h->is_avc && (nalsize != consumed) && nalsize) {
4371 av_log(h->s.avctx, AV_LOG_DEBUG,
4372 "SPS decoding failure, try parsing the coomplete NAL\n");
4373 init_get_bits(&s->gb, buf + buf_index + 1 - consumed,
4375 ff_h264_decode_seq_parameter_set(h);
4378 if (s->flags & CODEC_FLAG_LOW_DELAY ||
4379 (h->sps.bitstream_restriction_flag &&
4380 !h->sps.num_reorder_frames))
4383 if (avctx->has_b_frames < 2)
4384 avctx->has_b_frames = !s->low_delay;
4386 if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
4387 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
4388 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
4389 avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
4390 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
4391 h->pixel_shift = h->sps.bit_depth_luma > 8;
4393 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
4394 h->sps.chroma_format_idc);
4395 ff_h264_pred_init(&h->hpc, s->codec_id,
4396 h->sps.bit_depth_luma,
4397 h->sps.chroma_format_idc);
4398 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
4399 ff_dsputil_init(&s->dsp, s->avctx);
4401 av_log(avctx, AV_LOG_ERROR,
4402 "Unsupported bit depth: %d\n",
4403 h->sps.bit_depth_luma);
4410 init_get_bits(&s->gb, ptr, bit_length);
4411 ff_h264_decode_picture_parameter_set(h, bit_length);
4414 case NAL_END_SEQUENCE:
4415 case NAL_END_STREAM:
4416 case NAL_FILLER_DATA:
4418 case NAL_AUXILIARY_SLICE:
4421 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4422 hx->nal_unit_type, bit_length);
4425 if (context_count == h->max_contexts) {
4426 execute_decode_slices(h, context_count);
4431 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4432 else if (err == 1) {
4433 /* Slice could not be decoded in parallel mode, copy down
4434 * NAL unit stuff to context 0 and restart. Note that
4435 * rbsp_buffer is not transferred, but since we no longer
4436 * run in parallel mode this should not be an issue. */
4437 h->nal_unit_type = hx->nal_unit_type;
4438 h->nal_ref_idc = hx->nal_ref_idc;
4445 execute_decode_slices(h, context_count);
4449 if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
4451 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
4452 s->picture_structure == PICT_BOTTOM_FIELD);
4459 * Return the number of bytes consumed for building the current frame.
4461 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
4464 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4465 if (pos + 10 > buf_size)
4466 pos = buf_size; // oops ;)
4471 static int decode_frame(AVCodecContext *avctx, void *data,
4472 int *data_size, AVPacket *avpkt)
4474 const uint8_t *buf = avpkt->data;
4475 int buf_size = avpkt->size;
4476 H264Context *h = avctx->priv_data;
4477 MpegEncContext *s = &h->s;
4478 AVFrame *pict = data;
4481 s->flags = avctx->flags;
4482 s->flags2 = avctx->flags2;
4484 /* end of stream, output what is still in the buffers */
4486 if (buf_size == 0) {
4490 s->current_picture_ptr = NULL;
4492 // FIXME factorize this with the output code below
4493 out = h->delayed_pic[0];
4496 h->delayed_pic[i] &&
4497 !h->delayed_pic[i]->f.key_frame &&
4498 !h->delayed_pic[i]->mmco_reset;
4500 if (h->delayed_pic[i]->poc < out->poc) {
4501 out = h->delayed_pic[i];
4505 for (i = out_idx; h->delayed_pic[i]; i++)
4506 h->delayed_pic[i] = h->delayed_pic[i + 1];
4509 *data_size = sizeof(AVFrame);
4516 buf_index = decode_nal_units(h, buf, buf_size);
4520 if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4525 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
4526 if (avctx->skip_frame >= AVDISCARD_NONREF)
4528 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4532 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
4533 (s->mb_y >= s->mb_height && s->mb_height)) {
4534 if (s->flags2 & CODEC_FLAG2_CHUNKS)
4535 decode_postinit(h, 1);
4539 if (!h->next_output_pic) {
4540 /* Wait for second field. */
4543 *data_size = sizeof(AVFrame);
4544 *pict = h->next_output_pic->f;
4548 assert(pict->data[0] || !*data_size);
4549 ff_print_debug_info(s, pict);
4550 // printf("out %d\n", (int)pict->data[0]);
4552 return get_consumed_bytes(s, buf_index, buf_size);
4555 av_cold void ff_h264_free_context(H264Context *h)
4559 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4561 for (i = 0; i < MAX_SPS_COUNT; i++)
4562 av_freep(h->sps_buffers + i);
4564 for (i = 0; i < MAX_PPS_COUNT; i++)
4565 av_freep(h->pps_buffers + i);
4568 static av_cold int h264_decode_end(AVCodecContext *avctx)
4570 H264Context *h = avctx->priv_data;
4571 MpegEncContext *s = &h->s;
4573 ff_h264_free_context(h);
4575 ff_MPV_common_end(s);
4577 // memset(h, 0, sizeof(H264Context));
4582 static const AVProfile profiles[] = {
4583 { FF_PROFILE_H264_BASELINE, "Baseline" },
4584 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4585 { FF_PROFILE_H264_MAIN, "Main" },
4586 { FF_PROFILE_H264_EXTENDED, "Extended" },
4587 { FF_PROFILE_H264_HIGH, "High" },
4588 { FF_PROFILE_H264_HIGH_10, "High 10" },
4589 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4590 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4591 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4592 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4593 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4594 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4595 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4596 { FF_PROFILE_UNKNOWN },
4599 AVCodec ff_h264_decoder = {
4601 .type = AVMEDIA_TYPE_VIDEO,
4602 .id = CODEC_ID_H264,
4603 .priv_data_size = sizeof(H264Context),
4604 .init = ff_h264_decode_init,
4605 .close = h264_decode_end,
4606 .decode = decode_frame,
4607 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4608 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4609 CODEC_CAP_FRAME_THREADS,
4611 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4612 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4613 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4614 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4617 #if CONFIG_H264_VDPAU_DECODER
4618 AVCodec ff_h264_vdpau_decoder = {
4619 .name = "h264_vdpau",
4620 .type = AVMEDIA_TYPE_VIDEO,
4621 .id = CODEC_ID_H264,
4622 .priv_data_size = sizeof(H264Context),
4623 .init = ff_h264_decode_init,
4624 .close = h264_decode_end,
4625 .decode = decode_frame,
4626 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4628 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4629 .pix_fmts = (const enum PixelFormat[]) { PIX_FMT_VDPAU_H264,
4631 .profiles = NULL_IF_CONFIG_SMALL(profiles),