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 FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
34 #include "cabac_functions.h"
37 #include "mpegvideo.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
44 #include "rectangle.h"
47 #include "vdpau_internal.h"
48 #include "libavutil/avassert.h"
53 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
55 static const uint8_t rem6[QP_MAX_NUM + 1] = {
56 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
57 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
58 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
59 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
63 static const uint8_t div6[QP_MAX_NUM + 1] = {
64 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
65 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
66 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
67 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
71 static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
72 #if CONFIG_H264_DXVA2_HWACCEL
75 #if CONFIG_H264_VAAPI_HWACCEL
78 #if CONFIG_H264_VDA_HWACCEL
81 #if CONFIG_H264_VDPAU_HWACCEL
88 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
90 H264Context *h = avctx->priv_data;
91 return h ? h->sps.num_reorder_frames : 0;
95 * Check if the top & left blocks are available if needed and
96 * change the dc mode so it only uses the available blocks.
98 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
100 MpegEncContext *const s = &h->s;
101 static const int8_t top[12] = {
102 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
104 static const int8_t left[12] = {
105 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
109 if (!(h->top_samples_available & 0x8000)) {
110 for (i = 0; i < 4; i++) {
111 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
113 av_log(h->s.avctx, AV_LOG_ERROR,
114 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
115 status, s->mb_x, s->mb_y);
118 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
123 if ((h->left_samples_available & 0x8888) != 0x8888) {
124 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
125 for (i = 0; i < 4; i++)
126 if (!(h->left_samples_available & mask[i])) {
127 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
129 av_log(h->s.avctx, AV_LOG_ERROR,
130 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
131 status, s->mb_x, s->mb_y);
134 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
140 } // FIXME cleanup like ff_h264_check_intra_pred_mode
143 * Check if the top & left blocks are available if needed and
144 * change the dc mode so it only uses the available blocks.
146 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
148 MpegEncContext *const s = &h->s;
149 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
150 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
153 av_log(h->s.avctx, AV_LOG_ERROR,
154 "out of range intra chroma pred mode at %d %d\n",
159 if (!(h->top_samples_available & 0x8000)) {
162 av_log(h->s.avctx, AV_LOG_ERROR,
163 "top block unavailable for requested intra mode at %d %d\n",
169 if ((h->left_samples_available & 0x8080) != 0x8080) {
171 if (is_chroma && (h->left_samples_available & 0x8080)) {
172 // mad cow disease mode, aka MBAFF + constrained_intra_pred
173 mode = ALZHEIMER_DC_L0T_PRED8x8 +
174 (!(h->left_samples_available & 0x8000)) +
175 2 * (mode == DC_128_PRED8x8);
178 av_log(h->s.avctx, AV_LOG_ERROR,
179 "left block unavailable for requested intra mode at %d %d\n",
188 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
189 int *dst_length, int *consumed, int length)
195 // src[0]&0x80; // forbidden bit
196 h->nal_ref_idc = src[0] >> 5;
197 h->nal_unit_type = src[0] & 0x1F;
202 #define STARTCODE_TEST \
203 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
204 if (src[i + 2] != 3) { \
205 /* startcode, so we must be past the end */ \
210 #if HAVE_FAST_UNALIGNED
211 #define FIND_FIRST_ZERO \
212 if (i > 0 && !src[i]) \
217 for (i = 0; i + 1 < length; i += 9) {
218 if (!((~AV_RN64A(src + i) &
219 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
220 0x8000800080008080ULL))
227 for (i = 0; i + 1 < length; i += 5) {
228 if (!((~AV_RN32A(src + i) &
229 (AV_RN32A(src + i) - 0x01000101U)) &
238 for (i = 0; i + 1 < length; i += 2) {
241 if (i > 0 && src[i - 1] == 0)
247 // use second escape buffer for inter data
248 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
250 si = h->rbsp_buffer_size[bufidx];
251 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
252 dst = h->rbsp_buffer[bufidx];
257 if(i>=length-1){ //no escaped 0
259 *consumed= length+1; //+1 for the header
260 if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
263 memcpy(dst, src, length);
270 while (si + 2 < length) {
271 // remove escapes (very rare 1:2^22)
272 if (src[si + 2] > 3) {
273 dst[di++] = src[si++];
274 dst[di++] = src[si++];
275 } else if (src[si] == 0 && src[si + 1] == 0) {
276 if (src[si + 2] == 3) { // escape
281 } else // next start code
285 dst[di++] = src[si++];
288 dst[di++] = src[si++];
291 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
294 *consumed = si + 1; // +1 for the header
295 /* FIXME store exact number of bits in the getbitcontext
296 * (it is needed for decoding) */
301 * Identify the exact end of the bitstream
302 * @return the length of the trailing, or 0 if damaged
304 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
309 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
311 for (r = 1; r < 9; r++) {
319 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
320 int height, int y_offset, int list)
322 int raw_my = h->mv_cache[list][scan8[n]][1];
323 int filter_height_down = (raw_my & 3) ? 3 : 0;
324 int full_my = (raw_my >> 2) + y_offset;
325 int bottom = full_my + filter_height_down + height;
327 av_assert2(height >= 0);
329 return FFMAX(0, bottom);
332 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
333 int height, int y_offset, int list0,
334 int list1, int *nrefs)
336 MpegEncContext *const s = &h->s;
339 y_offset += 16 * (s->mb_y >> MB_FIELD);
342 int ref_n = h->ref_cache[0][scan8[n]];
343 Picture *ref = &h->ref_list[0][ref_n];
345 // Error resilience puts the current picture in the ref list.
346 // Don't try to wait on these as it will cause a deadlock.
347 // Fields can wait on each other, though.
348 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
349 (ref->f.reference & 3) != s->picture_structure) {
350 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
351 if (refs[0][ref_n] < 0)
353 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
358 int ref_n = h->ref_cache[1][scan8[n]];
359 Picture *ref = &h->ref_list[1][ref_n];
361 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
362 (ref->f.reference & 3) != s->picture_structure) {
363 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
364 if (refs[1][ref_n] < 0)
366 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
372 * Wait until all reference frames are available for MC operations.
374 * @param h the H264 context
376 static void await_references(H264Context *h)
378 MpegEncContext *const s = &h->s;
379 const int mb_xy = h->mb_xy;
380 const int mb_type = s->current_picture.f.mb_type[mb_xy];
382 int nrefs[2] = { 0 };
385 memset(refs, -1, sizeof(refs));
387 if (IS_16X16(mb_type)) {
388 get_lowest_part_y(h, refs, 0, 16, 0,
389 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
390 } else if (IS_16X8(mb_type)) {
391 get_lowest_part_y(h, refs, 0, 8, 0,
392 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
393 get_lowest_part_y(h, refs, 8, 8, 8,
394 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
395 } else if (IS_8X16(mb_type)) {
396 get_lowest_part_y(h, refs, 0, 16, 0,
397 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
398 get_lowest_part_y(h, refs, 4, 16, 0,
399 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
403 av_assert2(IS_8X8(mb_type));
405 for (i = 0; i < 4; i++) {
406 const int sub_mb_type = h->sub_mb_type[i];
408 int y_offset = (i & 2) << 2;
410 if (IS_SUB_8X8(sub_mb_type)) {
411 get_lowest_part_y(h, refs, n, 8, y_offset,
412 IS_DIR(sub_mb_type, 0, 0),
413 IS_DIR(sub_mb_type, 0, 1),
415 } else if (IS_SUB_8X4(sub_mb_type)) {
416 get_lowest_part_y(h, refs, n, 4, y_offset,
417 IS_DIR(sub_mb_type, 0, 0),
418 IS_DIR(sub_mb_type, 0, 1),
420 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
421 IS_DIR(sub_mb_type, 0, 0),
422 IS_DIR(sub_mb_type, 0, 1),
424 } else if (IS_SUB_4X8(sub_mb_type)) {
425 get_lowest_part_y(h, refs, n, 8, y_offset,
426 IS_DIR(sub_mb_type, 0, 0),
427 IS_DIR(sub_mb_type, 0, 1),
429 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
430 IS_DIR(sub_mb_type, 0, 0),
431 IS_DIR(sub_mb_type, 0, 1),
435 av_assert2(IS_SUB_4X4(sub_mb_type));
436 for (j = 0; j < 4; j++) {
437 int sub_y_offset = y_offset + 2 * (j & 2);
438 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
439 IS_DIR(sub_mb_type, 0, 0),
440 IS_DIR(sub_mb_type, 0, 1),
447 for (list = h->list_count - 1; list >= 0; list--)
448 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
449 int row = refs[list][ref];
451 Picture *ref_pic = &h->ref_list[list][ref];
452 int ref_field = ref_pic->f.reference - 1;
453 int ref_field_picture = ref_pic->field_picture;
454 int pic_height = 16 * s->mb_height >> ref_field_picture;
459 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
460 ff_thread_await_progress(&ref_pic->f,
461 FFMIN((row >> 1) - !(row & 1),
464 ff_thread_await_progress(&ref_pic->f,
465 FFMIN((row >> 1), pic_height - 1),
467 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
468 ff_thread_await_progress(&ref_pic->f,
469 FFMIN(row * 2 + ref_field,
472 } else if (FIELD_PICTURE) {
473 ff_thread_await_progress(&ref_pic->f,
474 FFMIN(row, pic_height - 1),
477 ff_thread_await_progress(&ref_pic->f,
478 FFMIN(row, pic_height - 1),
485 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
486 int n, int square, int height,
488 uint8_t *dest_y, uint8_t *dest_cb,
490 int src_x_offset, int src_y_offset,
491 qpel_mc_func *qpix_op,
492 h264_chroma_mc_func chroma_op,
493 int pixel_shift, int chroma_idc)
495 MpegEncContext *const s = &h->s;
496 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
497 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
498 const int luma_xy = (mx & 3) + ((my & 3) << 2);
499 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
500 uint8_t *src_y = pic->f.data[0] + offset;
501 uint8_t *src_cb, *src_cr;
502 int extra_width = h->emu_edge_width;
503 int extra_height = h->emu_edge_height;
505 const int full_mx = mx >> 2;
506 const int full_my = my >> 2;
507 const int pic_width = 16 * s->mb_width;
508 const int pic_height = 16 * s->mb_height >> MB_FIELD;
516 if (full_mx < 0 - extra_width ||
517 full_my < 0 - extra_height ||
518 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
519 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
520 s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
521 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
523 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
524 full_my - 2, pic_width, pic_height);
525 src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
529 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
531 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
533 if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
536 if (chroma_idc == 3 /* yuv444 */) {
537 src_cb = pic->f.data[1] + offset;
539 s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
540 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
542 16 + 5, 16 + 5 /*FIXME*/,
543 full_mx - 2, full_my - 2,
544 pic_width, pic_height);
545 src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
547 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
549 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
551 src_cr = pic->f.data[2] + offset;
553 s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
554 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
556 16 + 5, 16 + 5 /*FIXME*/,
557 full_mx - 2, full_my - 2,
558 pic_width, pic_height);
559 src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
561 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
563 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
567 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
568 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
569 // chroma offset when predicting from a field of opposite parity
570 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
571 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
574 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
575 (my >> ysh) * h->mb_uvlinesize;
576 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
577 (my >> ysh) * h->mb_uvlinesize;
580 s->vdsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
581 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
582 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
583 src_cb = s->edge_emu_buffer;
585 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
586 height >> (chroma_idc == 1 /* yuv420 */),
587 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
590 s->vdsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
591 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
592 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
593 src_cr = s->edge_emu_buffer;
595 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
596 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
599 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
600 int height, int delta,
601 uint8_t *dest_y, uint8_t *dest_cb,
603 int x_offset, int y_offset,
604 qpel_mc_func *qpix_put,
605 h264_chroma_mc_func chroma_put,
606 qpel_mc_func *qpix_avg,
607 h264_chroma_mc_func chroma_avg,
608 int list0, int list1,
609 int pixel_shift, int chroma_idc)
611 MpegEncContext *const s = &h->s;
612 qpel_mc_func *qpix_op = qpix_put;
613 h264_chroma_mc_func chroma_op = chroma_put;
615 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
616 if (chroma_idc == 3 /* yuv444 */) {
617 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
618 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
619 } else if (chroma_idc == 2 /* yuv422 */) {
620 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
621 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
622 } else { /* yuv420 */
623 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
624 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
626 x_offset += 8 * s->mb_x;
627 y_offset += 8 * (s->mb_y >> MB_FIELD);
630 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
631 mc_dir_part(h, ref, n, square, height, delta, 0,
632 dest_y, dest_cb, dest_cr, x_offset, y_offset,
633 qpix_op, chroma_op, pixel_shift, chroma_idc);
636 chroma_op = chroma_avg;
640 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
641 mc_dir_part(h, ref, n, square, height, delta, 1,
642 dest_y, dest_cb, dest_cr, x_offset, y_offset,
643 qpix_op, chroma_op, pixel_shift, chroma_idc);
647 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
648 int height, int delta,
649 uint8_t *dest_y, uint8_t *dest_cb,
651 int x_offset, int y_offset,
652 qpel_mc_func *qpix_put,
653 h264_chroma_mc_func chroma_put,
654 h264_weight_func luma_weight_op,
655 h264_weight_func chroma_weight_op,
656 h264_biweight_func luma_weight_avg,
657 h264_biweight_func chroma_weight_avg,
658 int list0, int list1,
659 int pixel_shift, int chroma_idc)
661 MpegEncContext *const s = &h->s;
664 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
665 if (chroma_idc == 3 /* yuv444 */) {
666 chroma_height = height;
667 chroma_weight_avg = luma_weight_avg;
668 chroma_weight_op = luma_weight_op;
669 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
670 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
671 } else if (chroma_idc == 2 /* yuv422 */) {
672 chroma_height = height;
673 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
674 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
675 } else { /* yuv420 */
676 chroma_height = height >> 1;
677 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
678 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
680 x_offset += 8 * s->mb_x;
681 y_offset += 8 * (s->mb_y >> MB_FIELD);
683 if (list0 && list1) {
684 /* don't optimize for luma-only case, since B-frames usually
685 * use implicit weights => chroma too. */
686 uint8_t *tmp_cb = h->bipred_scratchpad;
687 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
688 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
689 int refn0 = h->ref_cache[0][scan8[n]];
690 int refn1 = h->ref_cache[1][scan8[n]];
692 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
693 dest_y, dest_cb, dest_cr,
694 x_offset, y_offset, qpix_put, chroma_put,
695 pixel_shift, chroma_idc);
696 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
697 tmp_y, tmp_cb, tmp_cr,
698 x_offset, y_offset, qpix_put, chroma_put,
699 pixel_shift, chroma_idc);
701 if (h->use_weight == 2) {
702 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
703 int weight1 = 64 - weight0;
704 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
705 height, 5, weight0, weight1, 0);
706 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
707 chroma_height, 5, weight0, weight1, 0);
708 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
709 chroma_height, 5, weight0, weight1, 0);
711 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
712 h->luma_log2_weight_denom,
713 h->luma_weight[refn0][0][0],
714 h->luma_weight[refn1][1][0],
715 h->luma_weight[refn0][0][1] +
716 h->luma_weight[refn1][1][1]);
717 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
718 h->chroma_log2_weight_denom,
719 h->chroma_weight[refn0][0][0][0],
720 h->chroma_weight[refn1][1][0][0],
721 h->chroma_weight[refn0][0][0][1] +
722 h->chroma_weight[refn1][1][0][1]);
723 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
724 h->chroma_log2_weight_denom,
725 h->chroma_weight[refn0][0][1][0],
726 h->chroma_weight[refn1][1][1][0],
727 h->chroma_weight[refn0][0][1][1] +
728 h->chroma_weight[refn1][1][1][1]);
731 int list = list1 ? 1 : 0;
732 int refn = h->ref_cache[list][scan8[n]];
733 Picture *ref = &h->ref_list[list][refn];
734 mc_dir_part(h, ref, n, square, height, delta, list,
735 dest_y, dest_cb, dest_cr, x_offset, y_offset,
736 qpix_put, chroma_put, pixel_shift, chroma_idc);
738 luma_weight_op(dest_y, h->mb_linesize, height,
739 h->luma_log2_weight_denom,
740 h->luma_weight[refn][list][0],
741 h->luma_weight[refn][list][1]);
742 if (h->use_weight_chroma) {
743 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
744 h->chroma_log2_weight_denom,
745 h->chroma_weight[refn][list][0][0],
746 h->chroma_weight[refn][list][0][1]);
747 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
748 h->chroma_log2_weight_denom,
749 h->chroma_weight[refn][list][1][0],
750 h->chroma_weight[refn][list][1][1]);
755 static av_always_inline void prefetch_motion(H264Context *h, int list,
756 int pixel_shift, int chroma_idc)
758 /* fetch pixels for estimated mv 4 macroblocks ahead
759 * optimized for 64byte cache lines */
760 MpegEncContext *const s = &h->s;
761 const int refn = h->ref_cache[list][scan8[0]];
763 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
764 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
765 uint8_t **src = h->ref_list[list][refn].f.data;
766 int off = (mx << pixel_shift) +
767 (my + (s->mb_x & 3) * 4) * h->mb_linesize +
769 s->vdsp.prefetch(src[0] + off, s->linesize, 4);
770 if (chroma_idc == 3 /* yuv444 */) {
771 s->vdsp.prefetch(src[1] + off, s->linesize, 4);
772 s->vdsp.prefetch(src[2] + off, s->linesize, 4);
774 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
775 s->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
780 static void free_tables(H264Context *h, int free_rbsp)
785 av_freep(&h->intra4x4_pred_mode);
786 av_freep(&h->chroma_pred_mode_table);
787 av_freep(&h->cbp_table);
788 av_freep(&h->mvd_table[0]);
789 av_freep(&h->mvd_table[1]);
790 av_freep(&h->direct_table);
791 av_freep(&h->non_zero_count);
792 av_freep(&h->slice_table_base);
793 h->slice_table = NULL;
794 av_freep(&h->list_counts);
796 av_freep(&h->mb2b_xy);
797 av_freep(&h->mb2br_xy);
799 for (i = 0; i < MAX_THREADS; i++) {
800 hx = h->thread_context[i];
803 av_freep(&hx->top_borders[1]);
804 av_freep(&hx->top_borders[0]);
805 av_freep(&hx->bipred_scratchpad);
807 av_freep(&hx->rbsp_buffer[1]);
808 av_freep(&hx->rbsp_buffer[0]);
809 hx->rbsp_buffer_size[0] = 0;
810 hx->rbsp_buffer_size[1] = 0;
813 av_freep(&h->thread_context[i]);
817 static void init_dequant8_coeff_table(H264Context *h)
820 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
822 for (i = 0; i < 6; i++) {
823 h->dequant8_coeff[i] = h->dequant8_buffer[i];
824 for (j = 0; j < i; j++)
825 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
826 64 * sizeof(uint8_t))) {
827 h->dequant8_coeff[i] = h->dequant8_buffer[j];
833 for (q = 0; q < max_qp + 1; q++) {
836 for (x = 0; x < 64; x++)
837 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
838 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
839 h->pps.scaling_matrix8[i][x]) << shift;
844 static void init_dequant4_coeff_table(H264Context *h)
847 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
848 for (i = 0; i < 6; i++) {
849 h->dequant4_coeff[i] = h->dequant4_buffer[i];
850 for (j = 0; j < i; j++)
851 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
852 16 * sizeof(uint8_t))) {
853 h->dequant4_coeff[i] = h->dequant4_buffer[j];
859 for (q = 0; q < max_qp + 1; q++) {
860 int shift = div6[q] + 2;
862 for (x = 0; x < 16; x++)
863 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
864 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
865 h->pps.scaling_matrix4[i][x]) << shift;
870 static void init_dequant_tables(H264Context *h)
873 init_dequant4_coeff_table(h);
874 if (h->pps.transform_8x8_mode)
875 init_dequant8_coeff_table(h);
876 if (h->sps.transform_bypass) {
877 for (i = 0; i < 6; i++)
878 for (x = 0; x < 16; x++)
879 h->dequant4_coeff[i][0][x] = 1 << 6;
880 if (h->pps.transform_8x8_mode)
881 for (i = 0; i < 6; i++)
882 for (x = 0; x < 64; x++)
883 h->dequant8_coeff[i][0][x] = 1 << 6;
887 int ff_h264_alloc_tables(H264Context *h)
889 MpegEncContext *const s = &h->s;
890 const int big_mb_num = s->mb_stride * (s->mb_height + 1);
891 const int row_mb_num = 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
894 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
895 row_mb_num * 8 * sizeof(uint8_t), fail)
896 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
897 big_mb_num * 48 * sizeof(uint8_t), fail)
898 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
899 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
900 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
901 big_mb_num * sizeof(uint16_t), fail)
902 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
903 big_mb_num * sizeof(uint8_t), fail)
904 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
905 16 * row_mb_num * sizeof(uint8_t), fail);
906 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
907 16 * row_mb_num * sizeof(uint8_t), fail);
908 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
909 4 * big_mb_num * sizeof(uint8_t), fail);
910 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
911 big_mb_num * sizeof(uint8_t), fail)
913 memset(h->slice_table_base, -1,
914 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
915 h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
917 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
918 big_mb_num * sizeof(uint32_t), fail);
919 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
920 big_mb_num * sizeof(uint32_t), fail);
921 for (y = 0; y < s->mb_height; y++)
922 for (x = 0; x < s->mb_width; x++) {
923 const int mb_xy = x + y * s->mb_stride;
924 const int b_xy = 4 * x + 4 * y * h->b_stride;
926 h->mb2b_xy[mb_xy] = b_xy;
927 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
930 if (!h->dequant4_coeff[0])
931 init_dequant_tables(h);
941 * Mimic alloc_tables(), but for every context thread.
943 static void clone_tables(H264Context *dst, H264Context *src, int i)
945 MpegEncContext *const s = &src->s;
946 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
947 dst->non_zero_count = src->non_zero_count;
948 dst->slice_table = src->slice_table;
949 dst->cbp_table = src->cbp_table;
950 dst->mb2b_xy = src->mb2b_xy;
951 dst->mb2br_xy = src->mb2br_xy;
952 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
953 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
954 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
955 dst->direct_table = src->direct_table;
956 dst->list_counts = src->list_counts;
957 dst->bipred_scratchpad = NULL;
958 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
959 src->sps.chroma_format_idc);
964 * Allocate buffers which are not shared amongst multiple threads.
966 static int context_init(H264Context *h)
968 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
969 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
970 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
971 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
973 h->ref_cache[0][scan8[5] + 1] =
974 h->ref_cache[0][scan8[7] + 1] =
975 h->ref_cache[0][scan8[13] + 1] =
976 h->ref_cache[1][scan8[5] + 1] =
977 h->ref_cache[1][scan8[7] + 1] =
978 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
983 return -1; // free_tables will clean up for us
986 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
987 int parse_extradata);
989 static av_cold void common_init(H264Context *h)
991 MpegEncContext *const s = &h->s;
993 s->width = s->avctx->width;
994 s->height = s->avctx->height;
995 s->codec_id = s->avctx->codec->id;
997 s->avctx->bits_per_raw_sample = 8;
998 h->cur_chroma_format_idc = 1;
1000 ff_h264dsp_init(&h->h264dsp, 8, 1);
1001 av_assert0(h->sps.bit_depth_chroma == 0);
1002 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1003 ff_h264qpel_init(&h->h264qpel, 8);
1004 ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);
1006 h->dequant_coeff_pps = -1;
1007 s->unrestricted_mv = 1;
1009 s->dsp.dct_bits = 16;
1010 /* needed so that IDCT permutation is known early */
1011 ff_dsputil_init(&s->dsp, s->avctx);
1012 ff_videodsp_init(&s->vdsp, 8);
1014 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1015 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1018 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1020 AVCodecContext *avctx = h->s.avctx;
1022 if (!buf || size <= 0)
1026 int i, cnt, nalsize;
1027 const unsigned char *p = buf;
1032 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1035 /* sps and pps in the avcC always have length coded with 2 bytes,
1036 * so put a fake nal_length_size = 2 while parsing them */
1037 h->nal_length_size = 2;
1038 // Decode sps from avcC
1039 cnt = *(p + 5) & 0x1f; // Number of sps
1041 for (i = 0; i < cnt; i++) {
1042 nalsize = AV_RB16(p) + 2;
1043 if(nalsize > size - (p-buf))
1045 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1046 av_log(avctx, AV_LOG_ERROR,
1047 "Decoding sps %d from avcC failed\n", i);
1052 // Decode pps from avcC
1053 cnt = *(p++); // Number of pps
1054 for (i = 0; i < cnt; i++) {
1055 nalsize = AV_RB16(p) + 2;
1056 if(nalsize > size - (p-buf))
1058 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1059 av_log(avctx, AV_LOG_ERROR,
1060 "Decoding pps %d from avcC failed\n", i);
1065 // Now store right nal length size, that will be used to parse all other nals
1066 h->nal_length_size = (buf[4] & 0x03) + 1;
1069 if (decode_nal_units(h, buf, size, 1) < 0)
1075 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1077 H264Context *h = avctx->priv_data;
1078 MpegEncContext *const s = &h->s;
1081 ff_MPV_decode_defaults(s);
1086 s->out_format = FMT_H264;
1087 s->workaround_bugs = avctx->workaround_bugs;
1090 // s->decode_mb = ff_h263_decode_mb;
1091 s->quarter_sample = 1;
1092 if (!avctx->has_b_frames)
1095 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1097 ff_h264_decode_init_vlc();
1100 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1102 h->thread_context[0] = h;
1103 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1104 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1105 h->last_pocs[i] = INT_MIN;
1106 h->prev_poc_msb = 1 << 16;
1107 h->prev_frame_num = -1;
1109 ff_h264_reset_sei(h);
1110 if (avctx->codec_id == AV_CODEC_ID_H264) {
1111 if (avctx->ticks_per_frame == 1) {
1112 if(s->avctx->time_base.den < INT_MAX/2) {
1113 s->avctx->time_base.den *= 2;
1115 s->avctx->time_base.num /= 2;
1117 avctx->ticks_per_frame = 2;
1120 if (avctx->extradata_size > 0 && avctx->extradata &&
1121 ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
1122 ff_h264_free_context(h);
1126 if (h->sps.bitstream_restriction_flag &&
1127 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1128 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1132 ff_init_cabac_states();
1137 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1139 static void copy_picture_range(Picture **to, Picture **from, int count,
1140 MpegEncContext *new_base,
1141 MpegEncContext *old_base)
1145 for (i = 0; i < count; i++) {
1146 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1147 IN_RANGE(from[i], old_base->picture,
1148 sizeof(Picture) * old_base->picture_count) ||
1150 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1154 static void copy_parameter_set(void **to, void **from, int count, int size)
1158 for (i = 0; i < count; i++) {
1159 if (to[i] && !from[i])
1161 else if (from[i] && !to[i])
1162 to[i] = av_malloc(size);
1165 memcpy(to[i], from[i], size);
1169 static int decode_init_thread_copy(AVCodecContext *avctx)
1171 H264Context *h = avctx->priv_data;
1173 if (!avctx->internal->is_copy)
1175 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1176 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1178 h->s.context_initialized = 0;
1183 #define copy_fields(to, from, start_field, end_field) \
1184 memcpy(&to->start_field, &from->start_field, \
1185 (char *)&to->end_field - (char *)&to->start_field)
1187 static int h264_slice_header_init(H264Context *, int);
1189 static int h264_set_parameter_from_sps(H264Context *h);
1191 static int decode_update_thread_context(AVCodecContext *dst,
1192 const AVCodecContext *src)
1194 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1195 MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1196 int inited = s->context_initialized, err;
1203 (s->width != s1->width ||
1204 s->height != s1->height ||
1205 s->mb_width != s1->mb_width ||
1206 s->mb_height != s1->mb_height ||
1207 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1208 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1209 h->sps.colorspace != h1->sps.colorspace)) {
1211 av_freep(&h->bipred_scratchpad);
1213 s->width = s1->width;
1214 s->height = s1->height;
1215 s->mb_height = s1->mb_height;
1216 h->b_stride = h1->b_stride;
1218 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1219 MAX_SPS_COUNT, sizeof(SPS));
1221 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1222 MAX_PPS_COUNT, sizeof(PPS));
1225 if ((err = h264_slice_header_init(h, 1)) < 0) {
1226 av_log(h->s.avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1229 h->context_reinitialized = 1;
1231 h264_set_parameter_from_sps(h);
1232 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1233 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1235 /* update linesize on resize for h264. The h264 decoder doesn't
1236 * necessarily call ff_MPV_frame_start in the new thread */
1237 s->linesize = s1->linesize;
1238 s->uvlinesize = s1->uvlinesize;
1240 /* copy block_offset since frame_start may not be called */
1241 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1243 err = ff_mpeg_update_thread_context(dst, src);
1248 for (i = 0; i < MAX_SPS_COUNT; i++)
1249 av_freep(h->sps_buffers + i);
1251 for (i = 0; i < MAX_PPS_COUNT; i++)
1252 av_freep(h->pps_buffers + i);
1254 // copy all fields after MpegEnc, except mb
1255 memcpy(&h->s + 1, &h1->s + 1,
1256 offsetof(H264Context, mb) - sizeof(MpegEncContext));
1257 av_assert0(&h->cabac == &h->mb_padding + 1);
1258 memcpy(&h->cabac, &h1->cabac,
1259 sizeof(H264Context) - offsetof(H264Context, cabac));
1260 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1261 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1263 if (s1->context_initialized) {
1264 if (ff_h264_alloc_tables(h) < 0) {
1265 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1266 return AVERROR(ENOMEM);
1272 for (i = 0; i < 2; i++) {
1273 h->rbsp_buffer[i] = NULL;
1274 h->rbsp_buffer_size[i] = 0;
1276 h->bipred_scratchpad = NULL;
1278 h->thread_context[0] = h;
1281 /* frame_start may not be called for the next thread (if it's decoding
1282 * a bottom field) so this has to be allocated here */
1283 if (!h->bipred_scratchpad && s->linesize)
1284 h->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
1286 // extradata/NAL handling
1287 h->is_avc = h1->is_avc;
1290 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1291 MAX_SPS_COUNT, sizeof(SPS));
1293 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1294 MAX_PPS_COUNT, sizeof(PPS));
1297 // Dequantization matrices
1298 // FIXME these are big - can they be only copied when PPS changes?
1299 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1301 for (i = 0; i < 6; i++)
1302 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1303 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1305 for (i = 0; i < 6; i++)
1306 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1307 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1309 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1312 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1315 copy_fields(h, h1, ref_count, list_count);
1316 copy_fields(h, h1, ref2frm, intra_gb);
1317 copy_fields(h, h1, short_ref, cabac_init_idc);
1319 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1320 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1321 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1322 MAX_DELAYED_PIC_COUNT + 2, s, s1);
1324 h->last_slice_type = h1->last_slice_type;
1327 if (!s->current_picture_ptr)
1330 if (!s->droppable) {
1331 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1332 h->prev_poc_msb = h->poc_msb;
1333 h->prev_poc_lsb = h->poc_lsb;
1335 h->prev_frame_num_offset = h->frame_num_offset;
1336 h->prev_frame_num = h->frame_num;
1337 h->outputed_poc = h->next_outputed_poc;
1342 int ff_h264_frame_start(H264Context *h)
1344 MpegEncContext *const s = &h->s;
1346 const int pixel_shift = h->pixel_shift;
1348 1<<(h->sps.bit_depth_luma-1),
1349 1<<(h->sps.bit_depth_chroma-1),
1350 1<<(h->sps.bit_depth_chroma-1),
1354 if (ff_MPV_frame_start(s, s->avctx) < 0)
1357 avpriv_color_frame(&h->s.current_picture_ptr->f, c);
1358 ff_er_frame_start(s);
1360 * ff_MPV_frame_start uses pict_type to derive key_frame.
1361 * This is incorrect for H.264; IDR markings must be used.
1362 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1363 * See decode_nal_units().
1365 s->current_picture_ptr->f.key_frame = 0;
1366 s->current_picture_ptr->sync = 0;
1367 s->current_picture_ptr->mmco_reset = 0;
1369 assert(s->linesize && s->uvlinesize);
1371 for (i = 0; i < 16; i++) {
1372 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1373 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1375 for (i = 0; i < 16; i++) {
1376 h->block_offset[16 + i] =
1377 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1378 h->block_offset[48 + 16 + i] =
1379 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1382 /* can't be in alloc_tables because linesize isn't known there.
1383 * FIXME: redo bipred weight to not require extra buffer? */
1384 for (i = 0; i < s->slice_context_count; i++)
1385 if (h->thread_context[i] && !h->thread_context[i]->bipred_scratchpad)
1386 h->thread_context[i]->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
1388 /* Some macroblocks can be accessed before they're available in case
1389 * of lost slices, MBAFF or threading. */
1390 memset(h->slice_table, -1,
1391 (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1393 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1394 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1396 /* We mark the current picture as non-reference after allocating it, so
1397 * that if we break out due to an error it can be released automatically
1398 * in the next ff_MPV_frame_start().
1399 * SVQ3 as well as most other codecs have only last/next/current and thus
1400 * get released even with set reference, besides SVQ3 and others do not
1401 * mark frames as reference later "naturally". */
1402 if (s->codec_id != AV_CODEC_ID_SVQ3)
1403 s->current_picture_ptr->f.reference = 0;
1405 s->current_picture_ptr->field_poc[0] =
1406 s->current_picture_ptr->field_poc[1] = INT_MAX;
1408 h->next_output_pic = NULL;
1410 assert(s->current_picture_ptr->long_ref == 0);
1416 * Run setup operations that must be run after slice header decoding.
1417 * This includes finding the next displayed frame.
1419 * @param h h264 master context
1420 * @param setup_finished enough NALs have been read that we can call
1421 * ff_thread_finish_setup()
1423 static void decode_postinit(H264Context *h, int setup_finished)
1425 MpegEncContext *const s = &h->s;
1426 Picture *out = s->current_picture_ptr;
1427 Picture *cur = s->current_picture_ptr;
1428 int i, pics, out_of_order, out_idx;
1430 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1431 s->current_picture_ptr->f.pict_type = s->pict_type;
1433 if (h->next_output_pic)
1436 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1437 /* FIXME: if we have two PAFF fields in one packet, we can't start
1438 * the next thread here. If we have one field per packet, we can.
1439 * The check in decode_nal_units() is not good enough to find this
1440 * yet, so we assume the worst for now. */
1441 // if (setup_finished)
1442 // ff_thread_finish_setup(s->avctx);
1446 cur->f.interlaced_frame = 0;
1447 cur->f.repeat_pict = 0;
1449 /* Signal interlacing information externally. */
1450 /* Prioritize picture timing SEI information over used
1451 * decoding process if it exists. */
1453 if (h->sps.pic_struct_present_flag) {
1454 switch (h->sei_pic_struct) {
1455 case SEI_PIC_STRUCT_FRAME:
1457 case SEI_PIC_STRUCT_TOP_FIELD:
1458 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1459 cur->f.interlaced_frame = 1;
1461 case SEI_PIC_STRUCT_TOP_BOTTOM:
1462 case SEI_PIC_STRUCT_BOTTOM_TOP:
1463 if (FIELD_OR_MBAFF_PICTURE)
1464 cur->f.interlaced_frame = 1;
1466 // try to flag soft telecine progressive
1467 cur->f.interlaced_frame = h->prev_interlaced_frame;
1469 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1470 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1471 /* Signal the possibility of telecined film externally
1472 * (pic_struct 5,6). From these hints, let the applications
1473 * decide if they apply deinterlacing. */
1474 cur->f.repeat_pict = 1;
1476 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1477 cur->f.repeat_pict = 2;
1479 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1480 cur->f.repeat_pict = 4;
1484 if ((h->sei_ct_type & 3) &&
1485 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1486 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1488 /* Derive interlacing flag from used decoding process. */
1489 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1491 h->prev_interlaced_frame = cur->f.interlaced_frame;
1493 if (cur->field_poc[0] != cur->field_poc[1]) {
1494 /* Derive top_field_first from field pocs. */
1495 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1497 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1498 /* Use picture timing SEI information. Even if it is a
1499 * information of a past frame, better than nothing. */
1500 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1501 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1502 cur->f.top_field_first = 1;
1504 cur->f.top_field_first = 0;
1506 /* Most likely progressive */
1507 cur->f.top_field_first = 0;
1511 cur->mmco_reset = h->mmco_reset;
1513 // FIXME do something with unavailable reference frames
1515 /* Sort B-frames into display order */
1517 if (h->sps.bitstream_restriction_flag &&
1518 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1519 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1523 if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1524 !h->sps.bitstream_restriction_flag) {
1525 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1529 for (i = 0; 1; i++) {
1530 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1532 h->last_pocs[i-1] = cur->poc;
1535 h->last_pocs[i-1]= h->last_pocs[i];
1538 out_of_order = MAX_DELAYED_PIC_COUNT - i;
1539 if( cur->f.pict_type == AV_PICTURE_TYPE_B
1540 || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
1541 out_of_order = FFMAX(out_of_order, 1);
1542 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
1543 av_log(s->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
1544 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
1545 h->last_pocs[i] = INT_MIN;
1546 h->last_pocs[0] = cur->poc;
1547 cur->mmco_reset = 1;
1548 } else if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1549 av_log(s->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
1550 s->avctx->has_b_frames = out_of_order;
1555 while (h->delayed_pic[pics])
1558 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1560 h->delayed_pic[pics++] = cur;
1561 if (cur->f.reference == 0)
1562 cur->f.reference = DELAYED_PIC_REF;
1564 out = h->delayed_pic[0];
1566 for (i = 1; h->delayed_pic[i] &&
1567 !h->delayed_pic[i]->f.key_frame &&
1568 !h->delayed_pic[i]->mmco_reset;
1570 if (h->delayed_pic[i]->poc < out->poc) {
1571 out = h->delayed_pic[i];
1574 if (s->avctx->has_b_frames == 0 &&
1575 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1576 h->next_outputed_poc = INT_MIN;
1577 out_of_order = out->poc < h->next_outputed_poc;
1579 if (out_of_order || pics > s->avctx->has_b_frames) {
1580 out->f.reference &= ~DELAYED_PIC_REF;
1581 // for frame threading, the owner must be the second field's thread or
1582 // else the first thread can release the picture and reuse it unsafely
1584 for (i = out_idx; h->delayed_pic[i]; i++)
1585 h->delayed_pic[i] = h->delayed_pic[i + 1];
1587 if (!out_of_order && pics > s->avctx->has_b_frames) {
1588 h->next_output_pic = out;
1589 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1590 h->next_outputed_poc = INT_MIN;
1592 h->next_outputed_poc = out->poc;
1594 av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1597 if (h->next_output_pic && h->next_output_pic->sync) {
1602 ff_thread_finish_setup(s->avctx);
1605 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1606 uint8_t *src_cb, uint8_t *src_cr,
1607 int linesize, int uvlinesize,
1610 MpegEncContext *const s = &h->s;
1611 uint8_t *top_border;
1613 const int pixel_shift = h->pixel_shift;
1614 int chroma444 = CHROMA444;
1615 int chroma422 = CHROMA422;
1618 src_cb -= uvlinesize;
1619 src_cr -= uvlinesize;
1621 if (!simple && FRAME_MBAFF) {
1624 top_border = h->top_borders[0][s->mb_x];
1625 AV_COPY128(top_border, src_y + 15 * linesize);
1627 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1628 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1631 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1632 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1633 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1634 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1636 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1637 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1639 } else if (chroma422) {
1641 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1642 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1644 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1645 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1649 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1650 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1652 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1653 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1658 } else if (MB_MBAFF) {
1664 top_border = h->top_borders[top_idx][s->mb_x];
1665 /* There are two lines saved, the line above the top macroblock
1666 * of a pair, and the line above the bottom macroblock. */
1667 AV_COPY128(top_border, src_y + 16 * linesize);
1669 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1671 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1674 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1675 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1676 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1677 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1679 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1680 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1682 } else if (chroma422) {
1684 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1685 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1687 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1688 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1692 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1693 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1695 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1696 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1702 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1703 uint8_t *src_cb, uint8_t *src_cr,
1704 int linesize, int uvlinesize,
1705 int xchg, int chroma444,
1706 int simple, int pixel_shift)
1708 MpegEncContext *const s = &h->s;
1709 int deblock_topleft;
1712 uint8_t *top_border_m1;
1713 uint8_t *top_border;
1715 if (!simple && FRAME_MBAFF) {
1720 top_idx = MB_MBAFF ? 0 : 1;
1724 if (h->deblocking_filter == 2) {
1725 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1726 deblock_top = h->top_type;
1728 deblock_topleft = (s->mb_x > 0);
1729 deblock_top = (s->mb_y > !!MB_FIELD);
1732 src_y -= linesize + 1 + pixel_shift;
1733 src_cb -= uvlinesize + 1 + pixel_shift;
1734 src_cr -= uvlinesize + 1 + pixel_shift;
1736 top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1737 top_border = h->top_borders[top_idx][s->mb_x];
1739 #define XCHG(a, b, xchg) \
1740 if (pixel_shift) { \
1742 AV_SWAP64(b + 0, a + 0); \
1743 AV_SWAP64(b + 8, a + 8); \
1753 if (deblock_topleft) {
1754 XCHG(top_border_m1 + (8 << pixel_shift),
1755 src_y - (7 << pixel_shift), 1);
1757 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1758 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1759 if (s->mb_x + 1 < s->mb_width) {
1760 XCHG(h->top_borders[top_idx][s->mb_x + 1],
1761 src_y + (17 << pixel_shift), 1);
1764 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1766 if (deblock_topleft) {
1767 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1768 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1770 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1771 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1772 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1773 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1774 if (s->mb_x + 1 < s->mb_width) {
1775 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1776 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1780 if (deblock_topleft) {
1781 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1782 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1784 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1785 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1791 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
1794 if (high_bit_depth) {
1795 return AV_RN32A(((int32_t *)mb) + index);
1797 return AV_RN16A(mb + index);
1800 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
1801 int index, int value)
1803 if (high_bit_depth) {
1804 AV_WN32A(((int32_t *)mb) + index, value);
1806 AV_WN16A(mb + index, value);
1809 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1810 int mb_type, int is_h264,
1812 int transform_bypass,
1816 uint8_t *dest_y, int p)
1818 MpegEncContext *const s = &h->s;
1819 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
1820 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
1822 int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1823 block_offset += 16 * p;
1824 if (IS_INTRA4x4(mb_type)) {
1825 if (simple || !s->encoding) {
1826 if (IS_8x8DCT(mb_type)) {
1827 if (transform_bypass) {
1829 idct_add = h->h264dsp.h264_add_pixels8;
1831 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1832 idct_add = h->h264dsp.h264_idct8_add;
1834 for (i = 0; i < 16; i += 4) {
1835 uint8_t *const ptr = dest_y + block_offset[i];
1836 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1837 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1838 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1840 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1841 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1842 (h->topright_samples_available << i) & 0x4000, linesize);
1844 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1845 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1847 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1852 if (transform_bypass) {
1854 idct_add = h->h264dsp.h264_add_pixels4;
1856 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1857 idct_add = h->h264dsp.h264_idct_add;
1859 for (i = 0; i < 16; i++) {
1860 uint8_t *const ptr = dest_y + block_offset[i];
1861 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1863 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1864 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1869 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1870 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1871 av_assert2(s->mb_y || linesize <= block_offset[i]);
1872 if (!topright_avail) {
1874 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1875 topright = (uint8_t *)&tr_high;
1877 tr = ptr[3 - linesize] * 0x01010101u;
1878 topright = (uint8_t *)&tr;
1881 topright = ptr + (4 << pixel_shift) - linesize;
1885 h->hpc.pred4x4[dir](ptr, topright, linesize);
1886 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1889 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1890 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1892 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1893 } else if (CONFIG_SVQ3_DECODER)
1894 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1901 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1903 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1904 if (!transform_bypass)
1905 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1907 h->dequant4_coeff[p][qscale][0]);
1909 static const uint8_t dc_mapping[16] = {
1910 0 * 16, 1 * 16, 4 * 16, 5 * 16,
1911 2 * 16, 3 * 16, 6 * 16, 7 * 16,
1912 8 * 16, 9 * 16, 12 * 16, 13 * 16,
1913 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1914 for (i = 0; i < 16; i++)
1915 dctcoef_set(h->mb + (p * 256 << pixel_shift),
1916 pixel_shift, dc_mapping[i],
1917 dctcoef_get(h->mb_luma_dc[p],
1921 } else if (CONFIG_SVQ3_DECODER)
1922 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
1923 h->mb_luma_dc[p], qscale);
1927 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
1928 int is_h264, int simple,
1929 int transform_bypass,
1933 uint8_t *dest_y, int p)
1935 MpegEncContext *const s = &h->s;
1936 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
1938 block_offset += 16 * p;
1939 if (!IS_INTRA4x4(mb_type)) {
1941 if (IS_INTRA16x16(mb_type)) {
1942 if (transform_bypass) {
1943 if (h->sps.profile_idc == 244 &&
1944 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
1945 h->intra16x16_pred_mode == HOR_PRED8x8)) {
1946 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
1947 h->mb + (p * 256 << pixel_shift),
1950 for (i = 0; i < 16; i++)
1951 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
1952 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1953 h->h264dsp.h264_add_pixels4(dest_y + block_offset[i],
1954 h->mb + (i * 16 + p * 256 << pixel_shift),
1958 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
1959 h->mb + (p * 256 << pixel_shift),
1961 h->non_zero_count_cache + p * 5 * 8);
1963 } else if (h->cbp & 15) {
1964 if (transform_bypass) {
1965 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1966 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8
1967 : h->h264dsp.h264_add_pixels4;
1968 for (i = 0; i < 16; i += di)
1969 if (h->non_zero_count_cache[scan8[i + p * 16]])
1970 idct_add(dest_y + block_offset[i],
1971 h->mb + (i * 16 + p * 256 << pixel_shift),
1974 if (IS_8x8DCT(mb_type))
1975 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
1976 h->mb + (p * 256 << pixel_shift),
1978 h->non_zero_count_cache + p * 5 * 8);
1980 h->h264dsp.h264_idct_add16(dest_y, block_offset,
1981 h->mb + (p * 256 << pixel_shift),
1983 h->non_zero_count_cache + p * 5 * 8);
1986 } else if (CONFIG_SVQ3_DECODER) {
1987 for (i = 0; i < 16; i++)
1988 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
1989 // FIXME benchmark weird rule, & below
1990 uint8_t *const ptr = dest_y + block_offset[i];
1991 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
1992 s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2000 #include "h264_mb_template.c"
2004 #include "h264_mb_template.c"
2008 #include "h264_mb_template.c"
2010 void ff_h264_hl_decode_mb(H264Context *h)
2012 MpegEncContext *const s = &h->s;
2013 const int mb_xy = h->mb_xy;
2014 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2015 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2018 if (is_complex || h->pixel_shift)
2019 hl_decode_mb_444_complex(h);
2021 hl_decode_mb_444_simple_8(h);
2022 } else if (is_complex) {
2023 hl_decode_mb_complex(h);
2024 } else if (h->pixel_shift) {
2025 hl_decode_mb_simple_16(h);
2027 hl_decode_mb_simple_8(h);
2030 static int pred_weight_table(H264Context *h)
2032 MpegEncContext *const s = &h->s;
2034 int luma_def, chroma_def;
2037 h->use_weight_chroma = 0;
2038 h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
2039 if (h->sps.chroma_format_idc)
2040 h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
2041 luma_def = 1 << h->luma_log2_weight_denom;
2042 chroma_def = 1 << h->chroma_log2_weight_denom;
2044 for (list = 0; list < 2; list++) {
2045 h->luma_weight_flag[list] = 0;
2046 h->chroma_weight_flag[list] = 0;
2047 for (i = 0; i < h->ref_count[list]; i++) {
2048 int luma_weight_flag, chroma_weight_flag;
2050 luma_weight_flag = get_bits1(&s->gb);
2051 if (luma_weight_flag) {
2052 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
2053 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
2054 if (h->luma_weight[i][list][0] != luma_def ||
2055 h->luma_weight[i][list][1] != 0) {
2057 h->luma_weight_flag[list] = 1;
2060 h->luma_weight[i][list][0] = luma_def;
2061 h->luma_weight[i][list][1] = 0;
2064 if (h->sps.chroma_format_idc) {
2065 chroma_weight_flag = get_bits1(&s->gb);
2066 if (chroma_weight_flag) {
2068 for (j = 0; j < 2; j++) {
2069 h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
2070 h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
2071 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2072 h->chroma_weight[i][list][j][1] != 0) {
2073 h->use_weight_chroma = 1;
2074 h->chroma_weight_flag[list] = 1;
2079 for (j = 0; j < 2; j++) {
2080 h->chroma_weight[i][list][j][0] = chroma_def;
2081 h->chroma_weight[i][list][j][1] = 0;
2086 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2089 h->use_weight = h->use_weight || h->use_weight_chroma;
2094 * Initialize implicit_weight table.
2095 * @param field 0/1 initialize the weight for interlaced MBAFF
2096 * -1 initializes the rest
2098 static void implicit_weight_table(H264Context *h, int field)
2100 MpegEncContext *const s = &h->s;
2101 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2103 for (i = 0; i < 2; i++) {
2104 h->luma_weight_flag[i] = 0;
2105 h->chroma_weight_flag[i] = 0;
2109 if (s->picture_structure == PICT_FRAME) {
2110 cur_poc = s->current_picture_ptr->poc;
2112 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2114 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2115 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2117 h->use_weight_chroma = 0;
2121 ref_count0 = h->ref_count[0];
2122 ref_count1 = h->ref_count[1];
2124 cur_poc = s->current_picture_ptr->field_poc[field];
2126 ref_count0 = 16 + 2 * h->ref_count[0];
2127 ref_count1 = 16 + 2 * h->ref_count[1];
2131 h->use_weight_chroma = 2;
2132 h->luma_log2_weight_denom = 5;
2133 h->chroma_log2_weight_denom = 5;
2135 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2136 int poc0 = h->ref_list[0][ref0].poc;
2137 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2139 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2140 int poc1 = h->ref_list[1][ref1].poc;
2141 int td = av_clip(poc1 - poc0, -128, 127);
2143 int tb = av_clip(cur_poc - poc0, -128, 127);
2144 int tx = (16384 + (FFABS(td) >> 1)) / td;
2145 int dist_scale_factor = (tb * tx + 32) >> 8;
2146 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2147 w = 64 - dist_scale_factor;
2151 h->implicit_weight[ref0][ref1][0] =
2152 h->implicit_weight[ref0][ref1][1] = w;
2154 h->implicit_weight[ref0][ref1][field] = w;
2161 * instantaneous decoder refresh.
2163 static void idr(H264Context *h)
2166 ff_h264_remove_all_refs(h);
2167 h->prev_frame_num = 0;
2168 h->prev_frame_num_offset = 0;
2169 h->prev_poc_msb = 1<<16;
2170 h->prev_poc_lsb = 0;
2171 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2172 h->last_pocs[i] = INT_MIN;
2175 /* forget old pics after a seek */
2176 static void flush_change(H264Context *h)
2180 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2181 h->prev_interlaced_frame = 1;
2183 h->prev_frame_num = -1;
2184 if (h->s.current_picture_ptr) {
2185 h->s.current_picture_ptr->f.reference = 0;
2186 for (j=i=0; h->delayed_pic[i]; i++)
2187 if (h->delayed_pic[i] != h->s.current_picture_ptr)
2188 h->delayed_pic[j++] = h->delayed_pic[i];
2189 h->delayed_pic[j] = NULL;
2191 h->s.first_field = 0;
2192 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2193 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2194 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2195 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2196 ff_h264_reset_sei(h);
2197 h->recovery_frame= -1;
2200 h->current_slice = 0;
2203 /* forget old pics after a seek */
2204 static void flush_dpb(AVCodecContext *avctx)
2206 H264Context *h = avctx->priv_data;
2209 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2210 if (h->delayed_pic[i])
2211 h->delayed_pic[i]->f.reference = 0;
2212 h->delayed_pic[i] = NULL;
2216 ff_mpeg_flush(avctx);
2219 static int init_poc(H264Context *h)
2221 MpegEncContext *const s = &h->s;
2222 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2224 Picture *cur = s->current_picture_ptr;
2226 h->frame_num_offset = h->prev_frame_num_offset;
2227 if (h->frame_num < h->prev_frame_num)
2228 h->frame_num_offset += max_frame_num;
2230 if (h->sps.poc_type == 0) {
2231 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2233 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2234 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2235 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2236 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2238 h->poc_msb = h->prev_poc_msb;
2240 field_poc[1] = h->poc_msb + h->poc_lsb;
2241 if (s->picture_structure == PICT_FRAME)
2242 field_poc[1] += h->delta_poc_bottom;
2243 } else if (h->sps.poc_type == 1) {
2244 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2247 if (h->sps.poc_cycle_length != 0)
2248 abs_frame_num = h->frame_num_offset + h->frame_num;
2252 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2255 expected_delta_per_poc_cycle = 0;
2256 for (i = 0; i < h->sps.poc_cycle_length; i++)
2257 // FIXME integrate during sps parse
2258 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2260 if (abs_frame_num > 0) {
2261 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2262 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2264 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2265 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2266 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2270 if (h->nal_ref_idc == 0)
2271 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2273 field_poc[0] = expectedpoc + h->delta_poc[0];
2274 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2276 if (s->picture_structure == PICT_FRAME)
2277 field_poc[1] += h->delta_poc[1];
2279 int poc = 2 * (h->frame_num_offset + h->frame_num);
2281 if (!h->nal_ref_idc)
2288 if (s->picture_structure != PICT_BOTTOM_FIELD)
2289 s->current_picture_ptr->field_poc[0] = field_poc[0];
2290 if (s->picture_structure != PICT_TOP_FIELD)
2291 s->current_picture_ptr->field_poc[1] = field_poc[1];
2292 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2298 * initialize scan tables
2300 static void init_scan_tables(H264Context *h)
2303 for (i = 0; i < 16; i++) {
2304 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2305 h->zigzag_scan[i] = T(zigzag_scan[i]);
2306 h->field_scan[i] = T(field_scan[i]);
2309 for (i = 0; i < 64; i++) {
2310 #define T(x) (x >> 3) | ((x & 7) << 3)
2311 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2312 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2313 h->field_scan8x8[i] = T(field_scan8x8[i]);
2314 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2317 if (h->sps.transform_bypass) { // FIXME same ugly
2318 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2319 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2320 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2321 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2322 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2323 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2325 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2326 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2327 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2328 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2329 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2330 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2334 static int field_end(H264Context *h, int in_setup)
2336 MpegEncContext *const s = &h->s;
2337 AVCodecContext *const avctx = s->avctx;
2341 if (!in_setup && !s->droppable)
2342 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2343 s->picture_structure == PICT_BOTTOM_FIELD);
2345 if (CONFIG_H264_VDPAU_DECODER &&
2346 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2347 ff_vdpau_h264_set_reference_frames(s);
2349 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2350 if (!s->droppable) {
2351 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2352 h->prev_poc_msb = h->poc_msb;
2353 h->prev_poc_lsb = h->poc_lsb;
2355 h->prev_frame_num_offset = h->frame_num_offset;
2356 h->prev_frame_num = h->frame_num;
2357 h->outputed_poc = h->next_outputed_poc;
2360 if (avctx->hwaccel) {
2361 if (avctx->hwaccel->end_frame(avctx) < 0)
2362 av_log(avctx, AV_LOG_ERROR,
2363 "hardware accelerator failed to decode picture\n");
2366 if (CONFIG_H264_VDPAU_DECODER &&
2367 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2368 ff_vdpau_h264_picture_complete(s);
2371 * FIXME: Error handling code does not seem to support interlaced
2372 * when slices span multiple rows
2373 * The ff_er_add_slice calls don't work right for bottom
2374 * fields; they cause massive erroneous error concealing
2375 * Error marking covers both fields (top and bottom).
2376 * This causes a mismatched s->error_count
2377 * and a bad error table. Further, the error count goes to
2378 * INT_MAX when called for bottom field, because mb_y is
2379 * past end by one (callers fault) and resync_mb_y != 0
2380 * causes problems for the first MB line, too.
2382 if (!FIELD_PICTURE && h->current_slice && !h->sps.new)
2385 ff_MPV_frame_end(s);
2387 h->current_slice = 0;
2393 * Replicate H264 "master" context to thread contexts.
2395 static int clone_slice(H264Context *dst, H264Context *src)
2399 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2400 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2401 dst->s.current_picture = src->s.current_picture;
2402 dst->s.linesize = src->s.linesize;
2403 dst->s.uvlinesize = src->s.uvlinesize;
2404 dst->s.first_field = src->s.first_field;
2406 if (!dst->s.edge_emu_buffer &&
2407 (ret = ff_mpv_frame_size_alloc(&dst->s, dst->s.linesize))) {
2408 av_log(dst->s.avctx, AV_LOG_ERROR,
2409 "Failed to allocate scratch buffers\n");
2413 dst->prev_poc_msb = src->prev_poc_msb;
2414 dst->prev_poc_lsb = src->prev_poc_lsb;
2415 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2416 dst->prev_frame_num = src->prev_frame_num;
2417 dst->short_ref_count = src->short_ref_count;
2419 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2420 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2421 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2423 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2424 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2430 * Compute profile from profile_idc and constraint_set?_flags.
2434 * @return profile as defined by FF_PROFILE_H264_*
2436 int ff_h264_get_profile(SPS *sps)
2438 int profile = sps->profile_idc;
2440 switch (sps->profile_idc) {
2441 case FF_PROFILE_H264_BASELINE:
2442 // constraint_set1_flag set to 1
2443 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2445 case FF_PROFILE_H264_HIGH_10:
2446 case FF_PROFILE_H264_HIGH_422:
2447 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2448 // constraint_set3_flag set to 1
2449 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2456 static int h264_set_parameter_from_sps(H264Context *h)
2458 MpegEncContext *s = &h->s;
2460 if (s->flags & CODEC_FLAG_LOW_DELAY ||
2461 (h->sps.bitstream_restriction_flag &&
2462 !h->sps.num_reorder_frames)) {
2463 if (s->avctx->has_b_frames > 1 || h->delayed_pic[0])
2464 av_log(h->s.avctx, AV_LOG_WARNING, "Delayed frames seen. "
2465 "Reenabling low delay requires a codec flush.\n");
2470 if (s->avctx->has_b_frames < 2)
2471 s->avctx->has_b_frames = !s->low_delay;
2473 if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2474 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2475 if (s->avctx->codec &&
2476 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2477 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2478 av_log(s->avctx, AV_LOG_ERROR,
2479 "VDPAU decoding does not support video colorspace.\n");
2480 return AVERROR_INVALIDDATA;
2482 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
2483 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
2484 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2485 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2486 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2487 h->pixel_shift = h->sps.bit_depth_luma > 8;
2489 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2490 h->sps.chroma_format_idc);
2491 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2492 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2493 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma,
2494 h->sps.chroma_format_idc);
2495 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2496 ff_dsputil_init(&s->dsp, s->avctx);
2497 ff_videodsp_init(&s->vdsp, h->sps.bit_depth_luma);
2499 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2500 h->sps.bit_depth_luma);
2501 return AVERROR_INVALIDDATA;
2507 static enum PixelFormat get_pixel_format(H264Context *h)
2509 MpegEncContext *const s = &h->s;
2510 switch (h->sps.bit_depth_luma) {
2513 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2514 return AV_PIX_FMT_GBRP9;
2516 return AV_PIX_FMT_YUV444P9;
2517 } else if (CHROMA422)
2518 return AV_PIX_FMT_YUV422P9;
2520 return AV_PIX_FMT_YUV420P9;
2524 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2525 return AV_PIX_FMT_GBRP10;
2527 return AV_PIX_FMT_YUV444P10;
2528 } else if (CHROMA422)
2529 return AV_PIX_FMT_YUV422P10;
2531 return AV_PIX_FMT_YUV420P10;
2535 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2536 return AV_PIX_FMT_GBRP12;
2538 return AV_PIX_FMT_YUV444P12;
2539 } else if (CHROMA422)
2540 return AV_PIX_FMT_YUV422P12;
2542 return AV_PIX_FMT_YUV420P12;
2546 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2547 return AV_PIX_FMT_GBRP14;
2549 return AV_PIX_FMT_YUV444P14;
2550 } else if (CHROMA422)
2551 return AV_PIX_FMT_YUV422P14;
2553 return AV_PIX_FMT_YUV420P14;
2557 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2558 av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2559 return AV_PIX_FMT_GBR24P;
2560 } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
2561 av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2563 return s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2564 : AV_PIX_FMT_YUV444P;
2565 } else if (CHROMA422) {
2566 return s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2567 : AV_PIX_FMT_YUV422P;
2569 return s->avctx->get_format(s->avctx, s->avctx->codec->pix_fmts ?
2570 s->avctx->codec->pix_fmts :
2571 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2572 hwaccel_pixfmt_list_h264_jpeg_420 :
2573 ff_hwaccel_pixfmt_list_420);
2577 av_log(s->avctx, AV_LOG_ERROR,
2578 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2579 return AVERROR_INVALIDDATA;
2583 static int h264_slice_header_init(H264Context *h, int reinit)
2585 MpegEncContext *const s = &h->s;
2588 if( FFALIGN(s->avctx->width , 16 ) == s->width
2589 && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height
2590 && !h->sps.crop_right && !h->sps.crop_bottom
2591 && (s->avctx->width != s->width || s->avctx->height && s->height)
2593 av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
2594 s->avctx->coded_width = s->width;
2595 s->avctx->coded_height = s->height;
2597 avcodec_set_dimensions(s->avctx, s->width, s->height);
2598 s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2599 s->avctx->height -= (1<<s->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>s->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);
2602 s->avctx->sample_aspect_ratio = h->sps.sar;
2603 av_assert0(s->avctx->sample_aspect_ratio.den);
2605 if (h->sps.timing_info_present_flag) {
2606 int64_t den = h->sps.time_scale;
2607 if (h->x264_build < 44U)
2609 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2610 h->sps.num_units_in_tick, den, 1 << 30);
2613 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2617 if ((ret = ff_MPV_common_frame_size_change(s)) < 0) {
2618 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_frame_size_change() failed.\n");
2622 if ((ret = ff_MPV_common_init(s)) < 0) {
2623 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
2628 h->prev_interlaced_frame = 1;
2630 init_scan_tables(h);
2631 if (ff_h264_alloc_tables(h) < 0) {
2632 av_log(h->s.avctx, AV_LOG_ERROR,
2633 "Could not allocate memory for h264\n");
2634 return AVERROR(ENOMEM);
2637 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
2638 if (context_init(h) < 0) {
2639 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2643 for (i = 1; i < s->slice_context_count; i++) {
2645 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2646 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2647 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2648 c->h264dsp = h->h264dsp;
2649 c->h264qpel = h->h264qpel;
2650 c->h264chroma = h->h264chroma;
2653 c->pixel_shift = h->pixel_shift;
2654 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
2655 init_scan_tables(c);
2656 clone_tables(c, h, i);
2659 for (i = 0; i < s->slice_context_count; i++)
2660 if (context_init(h->thread_context[i]) < 0) {
2661 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2670 * Decode a slice header.
2671 * This will also call ff_MPV_common_init() and frame_start() as needed.
2673 * @param h h264context
2674 * @param h0 h264 master context (differs from 'h' when doing sliced based
2675 * parallel decoding)
2677 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2679 static int decode_slice_header(H264Context *h, H264Context *h0)
2681 MpegEncContext *const s = &h->s;
2682 MpegEncContext *const s0 = &h0->s;
2683 unsigned int first_mb_in_slice;
2684 unsigned int pps_id;
2685 int num_ref_idx_active_override_flag, ret;
2686 unsigned int slice_type, tmp, i, j;
2687 int default_ref_list_done = 0;
2688 int last_pic_structure, last_pic_droppable;
2690 int needs_reinit = 0;
2692 s->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
2693 s->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
2695 first_mb_in_slice = get_ue_golomb_long(&s->gb);
2697 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2698 if (h0->current_slice && FIELD_PICTURE) {
2702 h0->current_slice = 0;
2703 if (!s0->first_field) {
2704 if (s->current_picture_ptr && !s->droppable &&
2705 s->current_picture_ptr->owner2 == s) {
2706 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2707 s->picture_structure == PICT_BOTTOM_FIELD);
2709 s->current_picture_ptr = NULL;
2713 slice_type = get_ue_golomb_31(&s->gb);
2714 if (slice_type > 9) {
2715 av_log(h->s.avctx, AV_LOG_ERROR,
2716 "slice type too large (%d) at %d %d\n",
2717 slice_type, s->mb_x, s->mb_y);
2720 if (slice_type > 4) {
2722 h->slice_type_fixed = 1;
2724 h->slice_type_fixed = 0;
2726 slice_type = golomb_to_pict_type[slice_type];
2727 if (slice_type == AV_PICTURE_TYPE_I ||
2728 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2729 default_ref_list_done = 1;
2731 h->slice_type = slice_type;
2732 h->slice_type_nos = slice_type & 3;
2734 // to make a few old functions happy, it's wrong though
2735 s->pict_type = h->slice_type;
2737 pps_id = get_ue_golomb(&s->gb);
2738 if (pps_id >= MAX_PPS_COUNT) {
2739 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
2742 if (!h0->pps_buffers[pps_id]) {
2743 av_log(h->s.avctx, AV_LOG_ERROR,
2744 "non-existing PPS %u referenced\n",
2748 h->pps = *h0->pps_buffers[pps_id];
2750 if (!h0->sps_buffers[h->pps.sps_id]) {
2751 av_log(h->s.avctx, AV_LOG_ERROR,
2752 "non-existing SPS %u referenced\n",
2757 if (h->pps.sps_id != h->current_sps_id ||
2758 h->context_reinitialized ||
2759 h0->sps_buffers[h->pps.sps_id]->new) {
2760 SPS *new_sps = h0->sps_buffers[h->pps.sps_id];
2762 h0->sps_buffers[h->pps.sps_id]->new = 0;
2764 if (h->sps.chroma_format_idc != new_sps->chroma_format_idc ||
2765 h->sps.bit_depth_luma != new_sps->bit_depth_luma)
2768 h->current_sps_id = h->pps.sps_id;
2769 h->sps = *h0->sps_buffers[h->pps.sps_id];
2771 if (s->mb_width != h->sps.mb_width ||
2772 s->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
2773 s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2774 h->cur_chroma_format_idc != h->sps.chroma_format_idc
2778 if ((ret = h264_set_parameter_from_sps(h)) < 0)
2782 s->avctx->profile = ff_h264_get_profile(&h->sps);
2783 s->avctx->level = h->sps.level_idc;
2784 s->avctx->refs = h->sps.ref_frame_count;
2786 must_reinit = (s->context_initialized &&
2787 ( 16*h->sps.mb_width != s->avctx->coded_width
2788 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != s->avctx->coded_height
2789 || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
2790 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
2791 || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio)));
2792 if (h0->s.avctx->pix_fmt != get_pixel_format(h0))
2795 s->mb_width = h->sps.mb_width;
2796 s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2798 h->b_stride = s->mb_width * 4;
2800 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2802 s->width = 16 * s->mb_width;
2803 s->height = 16 * s->mb_height;
2805 if (h->sps.video_signal_type_present_flag) {
2806 s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
2808 if (h->sps.colour_description_present_flag) {
2809 if (s->avctx->colorspace != h->sps.colorspace)
2811 s->avctx->color_primaries = h->sps.color_primaries;
2812 s->avctx->color_trc = h->sps.color_trc;
2813 s->avctx->colorspace = h->sps.colorspace;
2817 if (s->context_initialized &&
2823 av_log(s->avctx, AV_LOG_ERROR, "changing width/height on "
2824 "slice %d\n", h0->current_slice + 1);
2825 return AVERROR_INVALIDDATA;
2830 if ((ret = get_pixel_format(h)) < 0)
2832 s->avctx->pix_fmt = ret;
2834 av_log(h->s.avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
2835 "pix_fmt: %d\n", s->width, s->height, s->avctx->pix_fmt);
2837 if ((ret = h264_slice_header_init(h, 1)) < 0) {
2838 av_log(h->s.avctx, AV_LOG_ERROR,
2839 "h264_slice_header_init() failed\n");
2842 h->context_reinitialized = 1;
2844 if (!s->context_initialized) {
2846 av_log(h->s.avctx, AV_LOG_ERROR,
2847 "Cannot (re-)initialize context during parallel decoding.\n");
2851 if ((ret = get_pixel_format(h)) < 0)
2853 s->avctx->pix_fmt = ret;
2855 if ((ret = h264_slice_header_init(h, 0)) < 0) {
2856 av_log(h->s.avctx, AV_LOG_ERROR,
2857 "h264_slice_header_init() failed\n");
2862 if (h == h0 && h->dequant_coeff_pps != pps_id) {
2863 h->dequant_coeff_pps = pps_id;
2864 init_dequant_tables(h);
2867 h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
2870 h->mb_aff_frame = 0;
2871 last_pic_structure = s0->picture_structure;
2872 last_pic_droppable = s0->droppable;
2873 s->droppable = h->nal_ref_idc == 0;
2874 if (h->sps.frame_mbs_only_flag) {
2875 s->picture_structure = PICT_FRAME;
2877 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
2878 av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
2881 if (get_bits1(&s->gb)) { // field_pic_flag
2882 s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
2884 s->picture_structure = PICT_FRAME;
2885 h->mb_aff_frame = h->sps.mb_aff;
2888 h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
2890 if (h0->current_slice != 0) {
2891 if (last_pic_structure != s->picture_structure ||
2892 last_pic_droppable != s->droppable) {
2893 av_log(h->s.avctx, AV_LOG_ERROR,
2894 "Changing field mode (%d -> %d) between slices is not allowed\n",
2895 last_pic_structure, s->picture_structure);
2896 s->picture_structure = last_pic_structure;
2897 s->droppable = last_pic_droppable;
2898 return AVERROR_INVALIDDATA;
2899 } else if (!s0->current_picture_ptr) {
2900 av_log(s->avctx, AV_LOG_ERROR,
2901 "unset current_picture_ptr on %d. slice\n",
2902 h0->current_slice + 1);
2903 return AVERROR_INVALIDDATA;
2906 /* Shorten frame num gaps so we don't have to allocate reference
2907 * frames just to throw them away */
2908 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
2909 int unwrap_prev_frame_num = h->prev_frame_num;
2910 int max_frame_num = 1 << h->sps.log2_max_frame_num;
2912 if (unwrap_prev_frame_num > h->frame_num)
2913 unwrap_prev_frame_num -= max_frame_num;
2915 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2916 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2917 if (unwrap_prev_frame_num < 0)
2918 unwrap_prev_frame_num += max_frame_num;
2920 h->prev_frame_num = unwrap_prev_frame_num;
2924 /* See if we have a decoded first field looking for a pair...
2925 * Here, we're using that to see if we should mark previously
2926 * decode frames as "finished".
2927 * We have to do that before the "dummy" in-between frame allocation,
2928 * since that can modify s->current_picture_ptr. */
2929 if (s0->first_field) {
2930 assert(s0->current_picture_ptr);
2931 assert(s0->current_picture_ptr->f.data[0]);
2932 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2934 /* Mark old field/frame as completed */
2935 if (!last_pic_droppable && s0->current_picture_ptr->owner2 == s0) {
2936 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2937 last_pic_structure == PICT_BOTTOM_FIELD);
2940 /* figure out if we have a complementary field pair */
2941 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2942 /* Previous field is unmatched. Don't display it, but let it
2943 * remain for reference if marked as such. */
2944 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
2945 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2946 last_pic_structure == PICT_TOP_FIELD);
2949 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2950 /* This and previous field were reference, but had
2951 * different frame_nums. Consider this field first in
2952 * pair. Throw away previous field except for reference
2954 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
2955 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2956 last_pic_structure == PICT_TOP_FIELD);
2959 /* Second field in complementary pair */
2960 if (!((last_pic_structure == PICT_TOP_FIELD &&
2961 s->picture_structure == PICT_BOTTOM_FIELD) ||
2962 (last_pic_structure == PICT_BOTTOM_FIELD &&
2963 s->picture_structure == PICT_TOP_FIELD))) {
2964 av_log(s->avctx, AV_LOG_ERROR,
2965 "Invalid field mode combination %d/%d\n",
2966 last_pic_structure, s->picture_structure);
2967 s->picture_structure = last_pic_structure;
2968 s->droppable = last_pic_droppable;
2969 return AVERROR_INVALIDDATA;
2970 } else if (last_pic_droppable != s->droppable) {
2971 av_log(s->avctx, AV_LOG_ERROR,
2972 "Cannot combine reference and non-reference fields in the same frame\n");
2973 av_log_ask_for_sample(s->avctx, NULL);
2974 s->picture_structure = last_pic_structure;
2975 s->droppable = last_pic_droppable;
2976 return AVERROR_PATCHWELCOME;
2979 /* Take ownership of this buffer. Note that if another thread owned
2980 * the first field of this buffer, we're not operating on that pointer,
2981 * so the original thread is still responsible for reporting progress
2982 * on that first field (or if that was us, we just did that above).
2983 * By taking ownership, we assign responsibility to ourselves to
2984 * report progress on the second field. */
2985 s0->current_picture_ptr->owner2 = s0;
2990 while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !s0->first_field &&
2991 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
2992 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2993 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
2994 h->frame_num, h->prev_frame_num);
2995 if (!h->sps.gaps_in_frame_num_allowed_flag)
2996 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
2997 h->last_pocs[i] = INT_MIN;
2998 if (ff_h264_frame_start(h) < 0)
3000 h->prev_frame_num++;
3001 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3002 s->current_picture_ptr->frame_num = h->prev_frame_num;
3003 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
3004 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
3005 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
3006 s->avctx->err_recognition & AV_EF_EXPLODE)
3008 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3009 (s->avctx->err_recognition & AV_EF_EXPLODE))
3010 return AVERROR_INVALIDDATA;
3011 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3012 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3013 * about there being no actual duplicates.
3014 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3015 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3017 if (h->short_ref_count) {
3019 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3020 (const uint8_t **)prev->f.data, prev->f.linesize,
3021 s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
3022 h->short_ref[0]->poc = prev->poc + 2;
3024 h->short_ref[0]->frame_num = h->prev_frame_num;
3028 /* See if we have a decoded first field looking for a pair...
3029 * We're using that to see whether to continue decoding in that
3030 * frame, or to allocate a new one. */
3031 if (s0->first_field) {
3032 assert(s0->current_picture_ptr);
3033 assert(s0->current_picture_ptr->f.data[0]);
3034 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
3036 /* figure out if we have a complementary field pair */
3037 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3038 /* Previous field is unmatched. Don't display it, but let it
3039 * remain for reference if marked as such. */
3040 s0->current_picture_ptr = NULL;
3041 s0->first_field = FIELD_PICTURE;
3043 if (s0->current_picture_ptr->frame_num != h->frame_num) {
3044 ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
3045 s0->picture_structure==PICT_BOTTOM_FIELD);
3046 /* This and the previous field had different frame_nums.
3047 * Consider this field first in pair. Throw away previous
3048 * one except for reference purposes. */
3049 s0->first_field = 1;
3050 s0->current_picture_ptr = NULL;
3052 /* Second field in complementary pair */
3053 s0->first_field = 0;
3057 /* Frame or first field in a potentially complementary pair */
3058 s0->first_field = FIELD_PICTURE;
3061 if (!FIELD_PICTURE || s0->first_field) {
3062 if (ff_h264_frame_start(h) < 0) {
3063 s0->first_field = 0;
3067 ff_release_unused_pictures(s, 0);
3070 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3073 s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3075 av_assert1(s->mb_num == s->mb_width * s->mb_height);
3076 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
3077 first_mb_in_slice >= s->mb_num) {
3078 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3081 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3082 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3083 if (s->picture_structure == PICT_BOTTOM_FIELD)
3084 s->resync_mb_y = s->mb_y = s->mb_y + 1;
3085 av_assert1(s->mb_y < s->mb_height);
3087 if (s->picture_structure == PICT_FRAME) {
3088 h->curr_pic_num = h->frame_num;
3089 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3091 h->curr_pic_num = 2 * h->frame_num + 1;
3092 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3095 if (h->nal_unit_type == NAL_IDR_SLICE)
3096 get_ue_golomb(&s->gb); /* idr_pic_id */
3098 if (h->sps.poc_type == 0) {
3099 h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3101 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3102 h->delta_poc_bottom = get_se_golomb(&s->gb);
3105 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3106 h->delta_poc[0] = get_se_golomb(&s->gb);
3108 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3109 h->delta_poc[1] = get_se_golomb(&s->gb);
3114 if (h->pps.redundant_pic_cnt_present)
3115 h->redundant_pic_count = get_ue_golomb(&s->gb);
3117 // set defaults, might be overridden a few lines later
3118 h->ref_count[0] = h->pps.ref_count[0];
3119 h->ref_count[1] = h->pps.ref_count[1];
3121 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3123 max[0] = max[1] = s->picture_structure == PICT_FRAME ? 15 : 31;
3125 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3126 h->direct_spatial_mv_pred = get_bits1(&s->gb);
3127 num_ref_idx_active_override_flag = get_bits1(&s->gb);
3129 if (num_ref_idx_active_override_flag) {
3130 h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
3131 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3132 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
3134 // full range is spec-ok in this case, even for frames
3135 h->ref_count[1] = 1;
3138 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3139 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
3140 h->ref_count[0] = h->ref_count[1] = 1;
3141 return AVERROR_INVALIDDATA;
3144 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3149 h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
3151 if (!default_ref_list_done)
3152 ff_h264_fill_default_ref_list(h);
3154 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
3155 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3156 h->ref_count[1] = h->ref_count[0] = 0;
3160 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3161 s->last_picture_ptr = &h->ref_list[0][0];
3162 s->last_picture_ptr->owner2 = s;
3163 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3165 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3166 s->next_picture_ptr = &h->ref_list[1][0];
3167 s->next_picture_ptr->owner2 = s;
3168 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3171 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3172 (h->pps.weighted_bipred_idc == 1 &&
3173 h->slice_type_nos == AV_PICTURE_TYPE_B))
3174 pred_weight_table(h);
3175 else if (h->pps.weighted_bipred_idc == 2 &&
3176 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3177 implicit_weight_table(h, -1);
3180 for (i = 0; i < 2; i++) {
3181 h->luma_weight_flag[i] = 0;
3182 h->chroma_weight_flag[i] = 0;
3186 // If frame-mt is enabled, only update mmco tables for the first slice
3187 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3188 // or h->mmco, which will cause ref list mix-ups and decoding errors
3189 // further down the line. This may break decoding if the first slice is
3190 // corrupt, thus we only do this if frame-mt is enabled.
3191 if (h->nal_ref_idc &&
3192 ff_h264_decode_ref_pic_marking(h0, &s->gb,
3193 !(s->avctx->active_thread_type & FF_THREAD_FRAME) ||
3194 h0->current_slice == 0) < 0 &&
3195 (s->avctx->err_recognition & AV_EF_EXPLODE))
3196 return AVERROR_INVALIDDATA;
3199 ff_h264_fill_mbaff_ref_list(h);
3201 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3202 implicit_weight_table(h, 0);
3203 implicit_weight_table(h, 1);
3207 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3208 ff_h264_direct_dist_scale_factor(h);
3209 ff_h264_direct_ref_list_init(h);
3211 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3212 tmp = get_ue_golomb_31(&s->gb);
3214 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3217 h->cabac_init_idc = tmp;
3220 h->last_qscale_diff = 0;
3221 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3222 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3223 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3227 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3228 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3229 // FIXME qscale / qp ... stuff
3230 if (h->slice_type == AV_PICTURE_TYPE_SP)
3231 get_bits1(&s->gb); /* sp_for_switch_flag */
3232 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3233 h->slice_type == AV_PICTURE_TYPE_SI)
3234 get_se_golomb(&s->gb); /* slice_qs_delta */
3236 h->deblocking_filter = 1;
3237 h->slice_alpha_c0_offset = 52;
3238 h->slice_beta_offset = 52;
3239 if (h->pps.deblocking_filter_parameters_present) {
3240 tmp = get_ue_golomb_31(&s->gb);
3242 av_log(s->avctx, AV_LOG_ERROR,
3243 "deblocking_filter_idc %u out of range\n", tmp);
3246 h->deblocking_filter = tmp;
3247 if (h->deblocking_filter < 2)
3248 h->deblocking_filter ^= 1; // 1<->0
3250 if (h->deblocking_filter) {
3251 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3252 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3253 if (h->slice_alpha_c0_offset > 104U ||
3254 h->slice_beta_offset > 104U) {
3255 av_log(s->avctx, AV_LOG_ERROR,
3256 "deblocking filter parameters %d %d out of range\n",
3257 h->slice_alpha_c0_offset, h->slice_beta_offset);
3263 if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3264 (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3265 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3266 (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3267 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3268 (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3269 h->nal_ref_idc == 0))
3270 h->deblocking_filter = 0;
3272 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3273 if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3274 /* Cheat slightly for speed:
3275 * Do not bother to deblock across slices. */
3276 h->deblocking_filter = 2;
3278 h0->max_contexts = 1;
3279 if (!h0->single_decode_warning) {
3280 av_log(s->avctx, AV_LOG_INFO,
3281 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3282 h0->single_decode_warning = 1;
3285 av_log(h->s.avctx, AV_LOG_ERROR,
3286 "Deblocking switched inside frame.\n");
3291 h->qp_thresh = 15 + 52 -
3292 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3294 h->pps.chroma_qp_index_offset[0],
3295 h->pps.chroma_qp_index_offset[1]) +
3296 6 * (h->sps.bit_depth_luma - 8);
3298 h0->last_slice_type = slice_type;
3299 h->slice_num = ++h0->current_slice;
3302 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
3303 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
3304 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
3305 && h->slice_num >= MAX_SLICES) {
3306 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3307 av_log(s->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
3310 for (j = 0; j < 2; j++) {
3312 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3313 for (i = 0; i < 16; i++) {
3315 if (h->ref_list[j][i].f.data[0]) {
3317 uint8_t *base = h->ref_list[j][i].f.base[0];
3318 for (k = 0; k < h->short_ref_count; k++)
3319 if (h->short_ref[k]->f.base[0] == base) {
3323 for (k = 0; k < h->long_ref_count; k++)
3324 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3325 id_list[i] = h->short_ref_count + k;
3333 for (i = 0; i < 16; i++)
3334 ref2frm[i + 2] = 4 * id_list[i] +
3335 (h->ref_list[j][i].f.reference & 3);
3337 ref2frm[18 + 1] = -1;
3338 for (i = 16; i < 48; i++)
3339 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3340 (h->ref_list[j][i].f.reference & 3);
3343 // FIXME: fix draw_edges + PAFF + frame threads
3344 h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
3345 (!h->sps.frame_mbs_only_flag &&
3346 s->avctx->active_thread_type))
3348 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3350 if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3351 av_log(h->s.avctx, AV_LOG_DEBUG,
3352 "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",
3354 (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3356 av_get_picture_type_char(h->slice_type),
3357 h->slice_type_fixed ? " fix" : "",
3358 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3359 pps_id, h->frame_num,
3360 s->current_picture_ptr->field_poc[0],
3361 s->current_picture_ptr->field_poc[1],
3362 h->ref_count[0], h->ref_count[1],
3364 h->deblocking_filter,
3365 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3367 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3368 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");