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 "h264_mvpred.h"
43 #include "rectangle.h"
45 #include "vdpau_internal.h"
46 #include "libavutil/avassert.h"
51 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
53 static const uint8_t rem6[QP_MAX_NUM + 1] = {
54 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
55 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
56 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
59 static const uint8_t div6[QP_MAX_NUM + 1] = {
60 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
61 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
62 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
65 static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
73 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
75 H264Context *h = avctx->priv_data;
76 return h ? h->sps.num_reorder_frames : 0;
80 * Check if the top & left blocks are available if needed and
81 * change the dc mode so it only uses the available blocks.
83 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
85 MpegEncContext *const s = &h->s;
86 static const int8_t top[12] = {
87 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
89 static const int8_t left[12] = {
90 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
94 if (!(h->top_samples_available & 0x8000)) {
95 for (i = 0; i < 4; i++) {
96 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
98 av_log(h->s.avctx, AV_LOG_ERROR,
99 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
100 status, s->mb_x, s->mb_y);
103 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
108 if ((h->left_samples_available & 0x8888) != 0x8888) {
109 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
110 for (i = 0; i < 4; i++)
111 if (!(h->left_samples_available & mask[i])) {
112 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
114 av_log(h->s.avctx, AV_LOG_ERROR,
115 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
116 status, s->mb_x, s->mb_y);
119 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
125 } // FIXME cleanup like ff_h264_check_intra_pred_mode
128 * Check if the top & left blocks are available if needed and
129 * change the dc mode so it only uses the available blocks.
131 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
133 MpegEncContext *const s = &h->s;
134 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
135 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
138 av_log(h->s.avctx, AV_LOG_ERROR,
139 "out of range intra chroma pred mode at %d %d\n",
144 if (!(h->top_samples_available & 0x8000)) {
147 av_log(h->s.avctx, AV_LOG_ERROR,
148 "top block unavailable for requested intra mode at %d %d\n",
154 if ((h->left_samples_available & 0x8080) != 0x8080) {
156 if (is_chroma && (h->left_samples_available & 0x8080)) {
157 // mad cow disease mode, aka MBAFF + constrained_intra_pred
158 mode = ALZHEIMER_DC_L0T_PRED8x8 +
159 (!(h->left_samples_available & 0x8000)) +
160 2 * (mode == DC_128_PRED8x8);
163 av_log(h->s.avctx, AV_LOG_ERROR,
164 "left block unavailable for requested intra mode at %d %d\n",
173 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
174 int *dst_length, int *consumed, int length)
180 // src[0]&0x80; // forbidden bit
181 h->nal_ref_idc = src[0] >> 5;
182 h->nal_unit_type = src[0] & 0x1F;
187 #if HAVE_FAST_UNALIGNED
190 for (i = 0; i + 1 < length; i += 9) {
191 if (!((~AV_RN64A(src + i) &
192 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
193 0x8000800080008080ULL))
196 for (i = 0; i + 1 < length; i += 5) {
197 if (!((~AV_RN32A(src + i) &
198 (AV_RN32A(src + i) - 0x01000101U)) &
202 if (i > 0 && !src[i])
208 for (i = 0; i + 1 < length; i += 2) {
211 if (i > 0 && src[i - 1] == 0)
214 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {
215 if (src[i + 2] != 3) {
216 /* startcode, so we must be past the end */
224 // use second escape buffer for inter data
225 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
227 si = h->rbsp_buffer_size[bufidx];
228 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
229 dst = h->rbsp_buffer[bufidx];
234 if(i>=length-1){ //no escaped 0
236 *consumed= length+1; //+1 for the header
237 if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
240 memcpy(dst, src, length);
245 // printf("decoding esc\n");
248 while (si + 2 < length) {
249 // remove escapes (very rare 1:2^22)
250 if (src[si + 2] > 3) {
251 dst[di++] = src[si++];
252 dst[di++] = src[si++];
253 } else if (src[si] == 0 && src[si + 1] == 0) {
254 if (src[si + 2] == 3) { // escape
259 } else // next start code
263 dst[di++] = src[si++];
266 dst[di++] = src[si++];
269 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
272 *consumed = si + 1; // +1 for the header
273 /* FIXME store exact number of bits in the getbitcontext
274 * (it is needed for decoding) */
279 * Identify the exact end of the bitstream
280 * @return the length of the trailing, or 0 if damaged
282 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
287 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
289 for (r = 1; r < 9; r++) {
297 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
298 int height, int y_offset, int list)
300 int raw_my = h->mv_cache[list][scan8[n]][1];
301 int filter_height = (raw_my & 3) ? 2 : 0;
302 int full_my = (raw_my >> 2) + y_offset;
303 int top = full_my - filter_height;
304 int bottom = full_my + filter_height + height;
306 return FFMAX(abs(top), bottom);
309 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
310 int height, int y_offset, int list0,
311 int list1, int *nrefs)
313 MpegEncContext *const s = &h->s;
316 y_offset += 16 * (s->mb_y >> MB_FIELD);
319 int ref_n = h->ref_cache[0][scan8[n]];
320 Picture *ref = &h->ref_list[0][ref_n];
322 // Error resilience puts the current picture in the ref list.
323 // Don't try to wait on these as it will cause a deadlock.
324 // Fields can wait on each other, though.
325 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
326 (ref->f.reference & 3) != s->picture_structure) {
327 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
328 if (refs[0][ref_n] < 0)
330 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
335 int ref_n = h->ref_cache[1][scan8[n]];
336 Picture *ref = &h->ref_list[1][ref_n];
338 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
339 (ref->f.reference & 3) != s->picture_structure) {
340 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
341 if (refs[1][ref_n] < 0)
343 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
349 * Wait until all reference frames are available for MC operations.
351 * @param h the H264 context
353 static void await_references(H264Context *h)
355 MpegEncContext *const s = &h->s;
356 const int mb_xy = h->mb_xy;
357 const int mb_type = s->current_picture.f.mb_type[mb_xy];
359 int nrefs[2] = { 0 };
362 memset(refs, -1, sizeof(refs));
364 if (IS_16X16(mb_type)) {
365 get_lowest_part_y(h, refs, 0, 16, 0,
366 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
367 } else if (IS_16X8(mb_type)) {
368 get_lowest_part_y(h, refs, 0, 8, 0,
369 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
370 get_lowest_part_y(h, refs, 8, 8, 8,
371 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
372 } else if (IS_8X16(mb_type)) {
373 get_lowest_part_y(h, refs, 0, 16, 0,
374 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
375 get_lowest_part_y(h, refs, 4, 16, 0,
376 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
380 assert(IS_8X8(mb_type));
382 for (i = 0; i < 4; i++) {
383 const int sub_mb_type = h->sub_mb_type[i];
385 int y_offset = (i & 2) << 2;
387 if (IS_SUB_8X8(sub_mb_type)) {
388 get_lowest_part_y(h, refs, n, 8, y_offset,
389 IS_DIR(sub_mb_type, 0, 0),
390 IS_DIR(sub_mb_type, 0, 1),
392 } else if (IS_SUB_8X4(sub_mb_type)) {
393 get_lowest_part_y(h, refs, n, 4, y_offset,
394 IS_DIR(sub_mb_type, 0, 0),
395 IS_DIR(sub_mb_type, 0, 1),
397 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
398 IS_DIR(sub_mb_type, 0, 0),
399 IS_DIR(sub_mb_type, 0, 1),
401 } else if (IS_SUB_4X8(sub_mb_type)) {
402 get_lowest_part_y(h, refs, n, 8, y_offset,
403 IS_DIR(sub_mb_type, 0, 0),
404 IS_DIR(sub_mb_type, 0, 1),
406 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
407 IS_DIR(sub_mb_type, 0, 0),
408 IS_DIR(sub_mb_type, 0, 1),
412 assert(IS_SUB_4X4(sub_mb_type));
413 for (j = 0; j < 4; j++) {
414 int sub_y_offset = y_offset + 2 * (j & 2);
415 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
416 IS_DIR(sub_mb_type, 0, 0),
417 IS_DIR(sub_mb_type, 0, 1),
424 for (list = h->list_count - 1; list >= 0; list--)
425 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
426 int row = refs[list][ref];
428 Picture *ref_pic = &h->ref_list[list][ref];
429 int ref_field = ref_pic->f.reference - 1;
430 int ref_field_picture = ref_pic->field_picture;
431 int pic_height = 16 * s->mb_height >> ref_field_picture;
436 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
437 ff_thread_await_progress(&ref_pic->f,
438 FFMIN((row >> 1) - !(row & 1),
441 ff_thread_await_progress(&ref_pic->f,
442 FFMIN((row >> 1), pic_height - 1),
444 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
445 ff_thread_await_progress(&ref_pic->f,
446 FFMIN(row * 2 + ref_field,
449 } else if (FIELD_PICTURE) {
450 ff_thread_await_progress(&ref_pic->f,
451 FFMIN(row, pic_height - 1),
454 ff_thread_await_progress(&ref_pic->f,
455 FFMIN(row, pic_height - 1),
462 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
463 int n, int square, int height,
465 uint8_t *dest_y, uint8_t *dest_cb,
467 int src_x_offset, int src_y_offset,
468 qpel_mc_func *qpix_op,
469 h264_chroma_mc_func chroma_op,
470 int pixel_shift, int chroma_idc)
472 MpegEncContext *const s = &h->s;
473 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
474 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
475 const int luma_xy = (mx & 3) + ((my & 3) << 2);
476 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
477 uint8_t *src_y = pic->f.data[0] + offset;
478 uint8_t *src_cb, *src_cr;
479 int extra_width = h->emu_edge_width;
480 int extra_height = h->emu_edge_height;
482 const int full_mx = mx >> 2;
483 const int full_my = my >> 2;
484 const int pic_width = 16 * s->mb_width;
485 const int pic_height = 16 * s->mb_height >> MB_FIELD;
493 if (full_mx < 0 - extra_width ||
494 full_my < 0 - extra_height ||
495 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
496 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
497 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
498 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
500 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
501 full_my - 2, pic_width, pic_height);
502 src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
506 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
508 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
510 if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
513 if (chroma_idc == 3 /* yuv444 */) {
514 src_cb = pic->f.data[1] + offset;
516 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
517 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
519 16 + 5, 16 + 5 /*FIXME*/,
520 full_mx - 2, full_my - 2,
521 pic_width, pic_height);
522 src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
524 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
526 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
528 src_cr = pic->f.data[2] + offset;
530 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
531 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
533 16 + 5, 16 + 5 /*FIXME*/,
534 full_mx - 2, full_my - 2,
535 pic_width, pic_height);
536 src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
538 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
540 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
544 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
545 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
546 // chroma offset when predicting from a field of opposite parity
547 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
548 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
551 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
552 (my >> ysh) * h->mb_uvlinesize;
553 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
554 (my >> ysh) * h->mb_uvlinesize;
557 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
558 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
559 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
560 src_cb = s->edge_emu_buffer;
562 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
563 height >> (chroma_idc == 1 /* yuv420 */),
564 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
567 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
568 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
569 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
570 src_cr = s->edge_emu_buffer;
572 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
573 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
576 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
577 int height, int delta,
578 uint8_t *dest_y, uint8_t *dest_cb,
580 int x_offset, int y_offset,
581 qpel_mc_func *qpix_put,
582 h264_chroma_mc_func chroma_put,
583 qpel_mc_func *qpix_avg,
584 h264_chroma_mc_func chroma_avg,
585 int list0, int list1,
586 int pixel_shift, int chroma_idc)
588 MpegEncContext *const s = &h->s;
589 qpel_mc_func *qpix_op = qpix_put;
590 h264_chroma_mc_func chroma_op = chroma_put;
592 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
593 if (chroma_idc == 3 /* yuv444 */) {
594 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
595 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
596 } else if (chroma_idc == 2 /* yuv422 */) {
597 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
598 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
599 } else { /* yuv420 */
600 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
601 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
603 x_offset += 8 * s->mb_x;
604 y_offset += 8 * (s->mb_y >> MB_FIELD);
607 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
608 mc_dir_part(h, ref, n, square, height, delta, 0,
609 dest_y, dest_cb, dest_cr, x_offset, y_offset,
610 qpix_op, chroma_op, pixel_shift, chroma_idc);
613 chroma_op = chroma_avg;
617 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
618 mc_dir_part(h, ref, n, square, height, delta, 1,
619 dest_y, dest_cb, dest_cr, x_offset, y_offset,
620 qpix_op, chroma_op, pixel_shift, chroma_idc);
624 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
625 int height, int delta,
626 uint8_t *dest_y, uint8_t *dest_cb,
628 int x_offset, int y_offset,
629 qpel_mc_func *qpix_put,
630 h264_chroma_mc_func chroma_put,
631 h264_weight_func luma_weight_op,
632 h264_weight_func chroma_weight_op,
633 h264_biweight_func luma_weight_avg,
634 h264_biweight_func chroma_weight_avg,
635 int list0, int list1,
636 int pixel_shift, int chroma_idc)
638 MpegEncContext *const s = &h->s;
641 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
642 if (chroma_idc == 3 /* yuv444 */) {
643 chroma_height = height;
644 chroma_weight_avg = luma_weight_avg;
645 chroma_weight_op = luma_weight_op;
646 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
647 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
648 } else if (chroma_idc == 2 /* yuv422 */) {
649 chroma_height = height;
650 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
651 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
652 } else { /* yuv420 */
653 chroma_height = height >> 1;
654 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
655 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
657 x_offset += 8 * s->mb_x;
658 y_offset += 8 * (s->mb_y >> MB_FIELD);
660 if (list0 && list1) {
661 /* don't optimize for luma-only case, since B-frames usually
662 * use implicit weights => chroma too. */
663 uint8_t *tmp_cb = s->obmc_scratchpad;
664 uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
665 uint8_t *tmp_y = s->obmc_scratchpad + 16 * h->mb_uvlinesize;
666 int refn0 = h->ref_cache[0][scan8[n]];
667 int refn1 = h->ref_cache[1][scan8[n]];
669 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
670 dest_y, dest_cb, dest_cr,
671 x_offset, y_offset, qpix_put, chroma_put,
672 pixel_shift, chroma_idc);
673 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
674 tmp_y, tmp_cb, tmp_cr,
675 x_offset, y_offset, qpix_put, chroma_put,
676 pixel_shift, chroma_idc);
678 if (h->use_weight == 2) {
679 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
680 int weight1 = 64 - weight0;
681 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
682 height, 5, weight0, weight1, 0);
683 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
684 chroma_height, 5, weight0, weight1, 0);
685 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
686 chroma_height, 5, weight0, weight1, 0);
688 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
689 h->luma_log2_weight_denom,
690 h->luma_weight[refn0][0][0],
691 h->luma_weight[refn1][1][0],
692 h->luma_weight[refn0][0][1] +
693 h->luma_weight[refn1][1][1]);
694 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
695 h->chroma_log2_weight_denom,
696 h->chroma_weight[refn0][0][0][0],
697 h->chroma_weight[refn1][1][0][0],
698 h->chroma_weight[refn0][0][0][1] +
699 h->chroma_weight[refn1][1][0][1]);
700 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
701 h->chroma_log2_weight_denom,
702 h->chroma_weight[refn0][0][1][0],
703 h->chroma_weight[refn1][1][1][0],
704 h->chroma_weight[refn0][0][1][1] +
705 h->chroma_weight[refn1][1][1][1]);
708 int list = list1 ? 1 : 0;
709 int refn = h->ref_cache[list][scan8[n]];
710 Picture *ref = &h->ref_list[list][refn];
711 mc_dir_part(h, ref, n, square, height, delta, list,
712 dest_y, dest_cb, dest_cr, x_offset, y_offset,
713 qpix_put, chroma_put, pixel_shift, chroma_idc);
715 luma_weight_op(dest_y, h->mb_linesize, height,
716 h->luma_log2_weight_denom,
717 h->luma_weight[refn][list][0],
718 h->luma_weight[refn][list][1]);
719 if (h->use_weight_chroma) {
720 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
721 h->chroma_log2_weight_denom,
722 h->chroma_weight[refn][list][0][0],
723 h->chroma_weight[refn][list][0][1]);
724 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
725 h->chroma_log2_weight_denom,
726 h->chroma_weight[refn][list][1][0],
727 h->chroma_weight[refn][list][1][1]);
732 static av_always_inline void prefetch_motion(H264Context *h, int list,
733 int pixel_shift, int chroma_idc)
735 /* fetch pixels for estimated mv 4 macroblocks ahead
736 * optimized for 64byte cache lines */
737 MpegEncContext *const s = &h->s;
738 const int refn = h->ref_cache[list][scan8[0]];
740 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
741 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
742 uint8_t **src = h->ref_list[list][refn].f.data;
743 int off = (mx << pixel_shift) +
744 (my + (s->mb_x & 3) * 4) * h->mb_linesize +
746 s->dsp.prefetch(src[0] + off, s->linesize, 4);
747 if (chroma_idc == 3 /* yuv444 */) {
748 s->dsp.prefetch(src[1] + off, s->linesize, 4);
749 s->dsp.prefetch(src[2] + off, s->linesize, 4);
751 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
752 s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
757 static void free_tables(H264Context *h, int free_rbsp)
762 av_freep(&h->intra4x4_pred_mode);
763 av_freep(&h->chroma_pred_mode_table);
764 av_freep(&h->cbp_table);
765 av_freep(&h->mvd_table[0]);
766 av_freep(&h->mvd_table[1]);
767 av_freep(&h->direct_table);
768 av_freep(&h->non_zero_count);
769 av_freep(&h->slice_table_base);
770 h->slice_table = NULL;
771 av_freep(&h->list_counts);
773 av_freep(&h->mb2b_xy);
774 av_freep(&h->mb2br_xy);
776 for (i = 0; i < MAX_THREADS; i++) {
777 hx = h->thread_context[i];
780 av_freep(&hx->top_borders[1]);
781 av_freep(&hx->top_borders[0]);
782 av_freep(&hx->s.obmc_scratchpad);
784 av_freep(&hx->rbsp_buffer[1]);
785 av_freep(&hx->rbsp_buffer[0]);
786 hx->rbsp_buffer_size[0] = 0;
787 hx->rbsp_buffer_size[1] = 0;
790 av_freep(&h->thread_context[i]);
794 static void init_dequant8_coeff_table(H264Context *h)
797 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
799 for (i = 0; i < 6; i++) {
800 h->dequant8_coeff[i] = h->dequant8_buffer[i];
801 for (j = 0; j < i; j++)
802 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
803 64 * sizeof(uint8_t))) {
804 h->dequant8_coeff[i] = h->dequant8_buffer[j];
810 for (q = 0; q < max_qp + 1; q++) {
813 for (x = 0; x < 64; x++)
814 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
815 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
816 h->pps.scaling_matrix8[i][x]) << shift;
821 static void init_dequant4_coeff_table(H264Context *h)
824 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
825 for (i = 0; i < 6; i++) {
826 h->dequant4_coeff[i] = h->dequant4_buffer[i];
827 for (j = 0; j < i; j++)
828 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
829 16 * sizeof(uint8_t))) {
830 h->dequant4_coeff[i] = h->dequant4_buffer[j];
836 for (q = 0; q < max_qp + 1; q++) {
837 int shift = div6[q] + 2;
839 for (x = 0; x < 16; x++)
840 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
841 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
842 h->pps.scaling_matrix4[i][x]) << shift;
847 static void init_dequant_tables(H264Context *h)
850 init_dequant4_coeff_table(h);
851 if (h->pps.transform_8x8_mode)
852 init_dequant8_coeff_table(h);
853 if (h->sps.transform_bypass) {
854 for (i = 0; i < 6; i++)
855 for (x = 0; x < 16; x++)
856 h->dequant4_coeff[i][0][x] = 1 << 6;
857 if (h->pps.transform_8x8_mode)
858 for (i = 0; i < 6; i++)
859 for (x = 0; x < 64; x++)
860 h->dequant8_coeff[i][0][x] = 1 << 6;
864 int ff_h264_alloc_tables(H264Context *h)
866 MpegEncContext *const s = &h->s;
867 const int big_mb_num = s->mb_stride * (s->mb_height + 1);
868 const int row_mb_num = 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
871 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
872 row_mb_num * 8 * sizeof(uint8_t), fail)
873 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
874 big_mb_num * 48 * sizeof(uint8_t), fail)
875 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
876 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
877 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
878 big_mb_num * sizeof(uint16_t), fail)
879 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
880 big_mb_num * sizeof(uint8_t), fail)
881 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
882 16 * row_mb_num * sizeof(uint8_t), fail);
883 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
884 16 * row_mb_num * sizeof(uint8_t), fail);
885 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
886 4 * big_mb_num * sizeof(uint8_t), fail);
887 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
888 big_mb_num * sizeof(uint8_t), fail)
890 memset(h->slice_table_base, -1,
891 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
892 h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
894 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
895 big_mb_num * sizeof(uint32_t), fail);
896 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
897 big_mb_num * sizeof(uint32_t), fail);
898 for (y = 0; y < s->mb_height; y++)
899 for (x = 0; x < s->mb_width; x++) {
900 const int mb_xy = x + y * s->mb_stride;
901 const int b_xy = 4 * x + 4 * y * h->b_stride;
903 h->mb2b_xy[mb_xy] = b_xy;
904 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
907 s->obmc_scratchpad = NULL;
909 if (!h->dequant4_coeff[0])
910 init_dequant_tables(h);
920 * Mimic alloc_tables(), but for every context thread.
922 static void clone_tables(H264Context *dst, H264Context *src, int i)
924 MpegEncContext *const s = &src->s;
925 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
926 dst->non_zero_count = src->non_zero_count;
927 dst->slice_table = src->slice_table;
928 dst->cbp_table = src->cbp_table;
929 dst->mb2b_xy = src->mb2b_xy;
930 dst->mb2br_xy = src->mb2br_xy;
931 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
932 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
933 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
934 dst->direct_table = src->direct_table;
935 dst->list_counts = src->list_counts;
936 dst->s.obmc_scratchpad = NULL;
937 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
938 src->sps.chroma_format_idc);
943 * Allocate buffers which are not shared amongst multiple threads.
945 static int context_init(H264Context *h)
947 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
948 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
949 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
950 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
952 h->ref_cache[0][scan8[5] + 1] =
953 h->ref_cache[0][scan8[7] + 1] =
954 h->ref_cache[0][scan8[13] + 1] =
955 h->ref_cache[1][scan8[5] + 1] =
956 h->ref_cache[1][scan8[7] + 1] =
957 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
962 return -1; // free_tables will clean up for us
965 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
967 static av_cold void common_init(H264Context *h)
969 MpegEncContext *const s = &h->s;
971 s->width = s->avctx->width;
972 s->height = s->avctx->height;
973 s->codec_id = s->avctx->codec->id;
975 s->avctx->bits_per_raw_sample = 8;
976 h->cur_chroma_format_idc = 1;
978 ff_h264dsp_init(&h->h264dsp,
979 s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
980 ff_h264_pred_init(&h->hpc, s->codec_id,
981 s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
983 h->dequant_coeff_pps = -1;
984 s->unrestricted_mv = 1;
986 s->dsp.dct_bits = 16;
987 /* needed so that IDCT permutation is known early */
988 ff_dsputil_init(&s->dsp, s->avctx);
990 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
991 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
994 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
996 AVCodecContext *avctx = h->s.avctx;
998 if (!buf || size <= 0)
1002 int i, cnt, nalsize;
1003 const unsigned char *p = buf;
1008 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1011 /* sps and pps in the avcC always have length coded with 2 bytes,
1012 * so put a fake nal_length_size = 2 while parsing them */
1013 h->nal_length_size = 2;
1014 // Decode sps from avcC
1015 cnt = *(p + 5) & 0x1f; // Number of sps
1017 for (i = 0; i < cnt; i++) {
1018 nalsize = AV_RB16(p) + 2;
1019 if(nalsize > size - (p-buf))
1021 if (decode_nal_units(h, p, nalsize) < 0) {
1022 av_log(avctx, AV_LOG_ERROR,
1023 "Decoding sps %d from avcC failed\n", i);
1028 // Decode pps from avcC
1029 cnt = *(p++); // Number of pps
1030 for (i = 0; i < cnt; i++) {
1031 nalsize = AV_RB16(p) + 2;
1032 if(nalsize > size - (p-buf))
1034 if (decode_nal_units(h, p, nalsize) < 0) {
1035 av_log(avctx, AV_LOG_ERROR,
1036 "Decoding pps %d from avcC failed\n", i);
1041 // Now store right nal length size, that will be used to parse all other nals
1042 h->nal_length_size = (buf[4] & 0x03) + 1;
1045 if (decode_nal_units(h, buf, size) < 0)
1051 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1053 H264Context *h = avctx->priv_data;
1054 MpegEncContext *const s = &h->s;
1057 ff_MPV_decode_defaults(s);
1062 s->out_format = FMT_H264;
1063 s->workaround_bugs = avctx->workaround_bugs;
1066 // s->decode_mb = ff_h263_decode_mb;
1067 s->quarter_sample = 1;
1068 if (!avctx->has_b_frames)
1071 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1073 ff_h264_decode_init_vlc();
1076 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1078 h->thread_context[0] = h;
1079 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1080 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1081 h->last_pocs[i] = INT_MIN;
1082 h->prev_poc_msb = 1 << 16;
1083 h->prev_frame_num = -1;
1085 ff_h264_reset_sei(h);
1086 if (avctx->codec_id == CODEC_ID_H264) {
1087 if (avctx->ticks_per_frame == 1)
1088 s->avctx->time_base.den *= 2;
1089 avctx->ticks_per_frame = 2;
1092 if (avctx->extradata_size > 0 && avctx->extradata &&
1093 ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
1094 ff_h264_free_context(h);
1098 if (h->sps.bitstream_restriction_flag &&
1099 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1100 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1107 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1109 static void copy_picture_range(Picture **to, Picture **from, int count,
1110 MpegEncContext *new_base,
1111 MpegEncContext *old_base)
1115 for (i = 0; i < count; i++) {
1116 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1117 IN_RANGE(from[i], old_base->picture,
1118 sizeof(Picture) * old_base->picture_count) ||
1120 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1124 static void copy_parameter_set(void **to, void **from, int count, int size)
1128 for (i = 0; i < count; i++) {
1129 if (to[i] && !from[i])
1131 else if (from[i] && !to[i])
1132 to[i] = av_malloc(size);
1135 memcpy(to[i], from[i], size);
1139 static int decode_init_thread_copy(AVCodecContext *avctx)
1141 H264Context *h = avctx->priv_data;
1143 if (!avctx->internal->is_copy)
1145 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1146 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1151 #define copy_fields(to, from, start_field, end_field) \
1152 memcpy(&to->start_field, &from->start_field, \
1153 (char *)&to->end_field - (char *)&to->start_field)
1155 static int decode_update_thread_context(AVCodecContext *dst,
1156 const AVCodecContext *src)
1158 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1159 MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1160 int inited = s->context_initialized, err;
1166 err = ff_mpeg_update_thread_context(dst, src);
1170 // FIXME handle width/height changing
1172 for (i = 0; i < MAX_SPS_COUNT; i++)
1173 av_freep(h->sps_buffers + i);
1175 for (i = 0; i < MAX_PPS_COUNT; i++)
1176 av_freep(h->pps_buffers + i);
1178 // copy all fields after MpegEnc
1179 memcpy(&h->s + 1, &h1->s + 1,
1180 sizeof(H264Context) - sizeof(MpegEncContext));
1181 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1182 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1184 if (s1->context_initialized) {
1185 if (ff_h264_alloc_tables(h) < 0) {
1186 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1187 return AVERROR(ENOMEM);
1191 /* frame_start may not be called for the next thread (if it's decoding
1192 * a bottom field) so this has to be allocated here */
1193 h->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1196 for (i = 0; i < 2; i++) {
1197 h->rbsp_buffer[i] = NULL;
1198 h->rbsp_buffer_size[i] = 0;
1201 h->thread_context[0] = h;
1203 s->dsp.clear_blocks(h->mb);
1204 s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1207 // extradata/NAL handling
1208 h->is_avc = h1->is_avc;
1211 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1212 MAX_SPS_COUNT, sizeof(SPS));
1214 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1215 MAX_PPS_COUNT, sizeof(PPS));
1218 // Dequantization matrices
1219 // FIXME these are big - can they be only copied when PPS changes?
1220 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1222 for (i = 0; i < 6; i++)
1223 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1224 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1226 for (i = 0; i < 6; i++)
1227 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1228 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1230 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1233 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1236 copy_fields(h, h1, ref_count, list_count);
1237 copy_fields(h, h1, ref_list, intra_gb);
1238 copy_fields(h, h1, short_ref, cabac_init_idc);
1240 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1241 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1242 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1243 MAX_DELAYED_PIC_COUNT + 2, s, s1);
1245 h->last_slice_type = h1->last_slice_type;
1248 if (!s->current_picture_ptr)
1252 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1253 h->prev_poc_msb = h->poc_msb;
1254 h->prev_poc_lsb = h->poc_lsb;
1256 h->prev_frame_num_offset = h->frame_num_offset;
1257 h->prev_frame_num = h->frame_num;
1258 h->outputed_poc = h->next_outputed_poc;
1263 int ff_h264_frame_start(H264Context *h)
1265 MpegEncContext *const s = &h->s;
1267 const int pixel_shift = h->pixel_shift;
1269 if (ff_MPV_frame_start(s, s->avctx) < 0)
1271 ff_er_frame_start(s);
1273 * ff_MPV_frame_start uses pict_type to derive key_frame.
1274 * This is incorrect for H.264; IDR markings must be used.
1275 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1276 * See decode_nal_units().
1278 s->current_picture_ptr->f.key_frame = 0;
1279 s->current_picture_ptr->sync = 0;
1280 s->current_picture_ptr->mmco_reset = 0;
1282 assert(s->linesize && s->uvlinesize);
1284 for (i = 0; i < 16; i++) {
1285 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1286 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1288 for (i = 0; i < 16; i++) {
1289 h->block_offset[16 + i] =
1290 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1291 h->block_offset[48 + 16 + i] =
1292 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1295 /* can't be in alloc_tables because linesize isn't known there.
1296 * FIXME: redo bipred weight to not require extra buffer? */
1297 for (i = 0; i < s->slice_context_count; i++)
1298 if (h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1299 h->thread_context[i]->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1301 /* Some macroblocks can be accessed before they're available in case
1302 * of lost slices, MBAFF or threading. */
1303 memset(h->slice_table, -1,
1304 (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1306 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1307 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1309 /* We mark the current picture as non-reference after allocating it, so
1310 * that if we break out due to an error it can be released automatically
1311 * in the next ff_MPV_frame_start().
1312 * SVQ3 as well as most other codecs have only last/next/current and thus
1313 * get released even with set reference, besides SVQ3 and others do not
1314 * mark frames as reference later "naturally". */
1315 if (s->codec_id != CODEC_ID_SVQ3)
1316 s->current_picture_ptr->f.reference = 0;
1318 s->current_picture_ptr->field_poc[0] =
1319 s->current_picture_ptr->field_poc[1] = INT_MAX;
1321 h->next_output_pic = NULL;
1323 assert(s->current_picture_ptr->long_ref == 0);
1329 * Run setup operations that must be run after slice header decoding.
1330 * This includes finding the next displayed frame.
1332 * @param h h264 master context
1333 * @param setup_finished enough NALs have been read that we can call
1334 * ff_thread_finish_setup()
1336 static void decode_postinit(H264Context *h, int setup_finished)
1338 MpegEncContext *const s = &h->s;
1339 Picture *out = s->current_picture_ptr;
1340 Picture *cur = s->current_picture_ptr;
1341 int i, pics, out_of_order, out_idx;
1343 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1344 s->current_picture_ptr->f.pict_type = s->pict_type;
1346 if (h->next_output_pic)
1349 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1350 /* FIXME: if we have two PAFF fields in one packet, we can't start
1351 * the next thread here. If we have one field per packet, we can.
1352 * The check in decode_nal_units() is not good enough to find this
1353 * yet, so we assume the worst for now. */
1354 // if (setup_finished)
1355 // ff_thread_finish_setup(s->avctx);
1359 cur->f.interlaced_frame = 0;
1360 cur->f.repeat_pict = 0;
1362 /* Signal interlacing information externally. */
1363 /* Prioritize picture timing SEI information over used
1364 * decoding process if it exists. */
1366 if (h->sps.pic_struct_present_flag) {
1367 switch (h->sei_pic_struct) {
1368 case SEI_PIC_STRUCT_FRAME:
1370 case SEI_PIC_STRUCT_TOP_FIELD:
1371 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1372 cur->f.interlaced_frame = 1;
1374 case SEI_PIC_STRUCT_TOP_BOTTOM:
1375 case SEI_PIC_STRUCT_BOTTOM_TOP:
1376 if (FIELD_OR_MBAFF_PICTURE)
1377 cur->f.interlaced_frame = 1;
1379 // try to flag soft telecine progressive
1380 cur->f.interlaced_frame = h->prev_interlaced_frame;
1382 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1383 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1384 /* Signal the possibility of telecined film externally
1385 * (pic_struct 5,6). From these hints, let the applications
1386 * decide if they apply deinterlacing. */
1387 cur->f.repeat_pict = 1;
1389 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1390 // Force progressive here, doubling interlaced frame is a bad idea.
1391 cur->f.repeat_pict = 2;
1393 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1394 cur->f.repeat_pict = 4;
1398 if ((h->sei_ct_type & 3) &&
1399 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1400 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1402 /* Derive interlacing flag from used decoding process. */
1403 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1405 h->prev_interlaced_frame = cur->f.interlaced_frame;
1407 if (cur->field_poc[0] != cur->field_poc[1]) {
1408 /* Derive top_field_first from field pocs. */
1409 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1411 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1412 /* Use picture timing SEI information. Even if it is a
1413 * information of a past frame, better than nothing. */
1414 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1415 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1416 cur->f.top_field_first = 1;
1418 cur->f.top_field_first = 0;
1420 /* Most likely progressive */
1421 cur->f.top_field_first = 0;
1425 cur->mmco_reset = h->mmco_reset;
1427 // FIXME do something with unavailable reference frames
1429 /* Sort B-frames into display order */
1431 if (h->sps.bitstream_restriction_flag &&
1432 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1433 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1437 if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1438 !h->sps.bitstream_restriction_flag) {
1439 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1443 for (i = 0; 1; i++) {
1444 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1446 h->last_pocs[i-1] = cur->poc;
1449 h->last_pocs[i-1]= h->last_pocs[i];
1452 out_of_order = MAX_DELAYED_PIC_COUNT - i;
1453 if( cur->f.pict_type == AV_PICTURE_TYPE_B
1454 || (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))
1455 out_of_order = FFMAX(out_of_order, 1);
1456 if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1457 av_log(s->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
1458 s->avctx->has_b_frames = out_of_order;
1463 while (h->delayed_pic[pics])
1466 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1468 h->delayed_pic[pics++] = cur;
1469 if (cur->f.reference == 0)
1470 cur->f.reference = DELAYED_PIC_REF;
1472 out = h->delayed_pic[0];
1474 for (i = 1; h->delayed_pic[i] &&
1475 !h->delayed_pic[i]->f.key_frame &&
1476 !h->delayed_pic[i]->mmco_reset;
1478 if (h->delayed_pic[i]->poc < out->poc) {
1479 out = h->delayed_pic[i];
1482 if (s->avctx->has_b_frames == 0 &&
1483 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1484 h->next_outputed_poc = INT_MIN;
1485 out_of_order = out->poc < h->next_outputed_poc;
1487 if (out_of_order || pics > s->avctx->has_b_frames) {
1488 out->f.reference &= ~DELAYED_PIC_REF;
1489 // for frame threading, the owner must be the second field's thread or
1490 // else the first thread can release the picture and reuse it unsafely
1492 for (i = out_idx; h->delayed_pic[i]; i++)
1493 h->delayed_pic[i] = h->delayed_pic[i + 1];
1495 if (!out_of_order && pics > s->avctx->has_b_frames) {
1496 h->next_output_pic = out;
1497 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1498 h->next_outputed_poc = INT_MIN;
1500 h->next_outputed_poc = out->poc;
1502 av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1505 if (h->next_output_pic && h->next_output_pic->sync) {
1510 ff_thread_finish_setup(s->avctx);
1513 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1514 uint8_t *src_cb, uint8_t *src_cr,
1515 int linesize, int uvlinesize,
1518 MpegEncContext *const s = &h->s;
1519 uint8_t *top_border;
1521 const int pixel_shift = h->pixel_shift;
1522 int chroma444 = CHROMA444;
1523 int chroma422 = CHROMA422;
1526 src_cb -= uvlinesize;
1527 src_cr -= uvlinesize;
1529 if (!simple && FRAME_MBAFF) {
1532 top_border = h->top_borders[0][s->mb_x];
1533 AV_COPY128(top_border, src_y + 15 * linesize);
1535 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1536 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1539 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1540 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1541 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1542 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1544 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1545 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1547 } else if (chroma422) {
1549 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1550 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1552 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1553 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1557 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1558 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1560 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1561 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1566 } else if (MB_MBAFF) {
1572 top_border = h->top_borders[top_idx][s->mb_x];
1573 /* There are two lines saved, the line above the top macroblock
1574 * of a pair, and the line above the bottom macroblock. */
1575 AV_COPY128(top_border, src_y + 16 * linesize);
1577 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1579 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1582 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1583 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1584 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1585 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1587 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1588 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1590 } else if (chroma422) {
1592 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1593 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1595 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1596 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1600 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1601 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1603 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1604 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1610 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1611 uint8_t *src_cb, uint8_t *src_cr,
1612 int linesize, int uvlinesize,
1613 int xchg, int chroma444,
1614 int simple, int pixel_shift)
1616 MpegEncContext *const s = &h->s;
1617 int deblock_topleft;
1620 uint8_t *top_border_m1;
1621 uint8_t *top_border;
1623 if (!simple && FRAME_MBAFF) {
1628 top_idx = MB_MBAFF ? 0 : 1;
1632 if (h->deblocking_filter == 2) {
1633 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1634 deblock_top = h->top_type;
1636 deblock_topleft = (s->mb_x > 0);
1637 deblock_top = (s->mb_y > !!MB_FIELD);
1640 src_y -= linesize + 1 + pixel_shift;
1641 src_cb -= uvlinesize + 1 + pixel_shift;
1642 src_cr -= uvlinesize + 1 + pixel_shift;
1644 top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1645 top_border = h->top_borders[top_idx][s->mb_x];
1647 #define XCHG(a, b, xchg) \
1648 if (pixel_shift) { \
1650 AV_SWAP64(b + 0, a + 0); \
1651 AV_SWAP64(b + 8, a + 8); \
1661 if (deblock_topleft) {
1662 XCHG(top_border_m1 + (8 << pixel_shift),
1663 src_y - (7 << pixel_shift), 1);
1665 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1666 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1667 if (s->mb_x + 1 < s->mb_width) {
1668 XCHG(h->top_borders[top_idx][s->mb_x + 1],
1669 src_y + (17 << pixel_shift), 1);
1672 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1674 if (deblock_topleft) {
1675 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1676 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1678 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1679 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1680 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1681 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1682 if (s->mb_x + 1 < s->mb_width) {
1683 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1684 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1688 if (deblock_topleft) {
1689 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1690 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1692 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1693 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1699 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
1702 if (high_bit_depth) {
1703 return AV_RN32A(((int32_t *)mb) + index);
1705 return AV_RN16A(mb + index);
1708 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
1709 int index, int value)
1711 if (high_bit_depth) {
1712 AV_WN32A(((int32_t *)mb) + index, value);
1714 AV_WN16A(mb + index, value);
1717 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1718 int mb_type, int is_h264,
1720 int transform_bypass,
1724 uint8_t *dest_y, int p)
1726 MpegEncContext *const s = &h->s;
1727 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1728 void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1730 int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1731 block_offset += 16 * p;
1732 if (IS_INTRA4x4(mb_type)) {
1733 if (simple || !s->encoding) {
1734 if (IS_8x8DCT(mb_type)) {
1735 if (transform_bypass) {
1737 idct_add = s->dsp.add_pixels8;
1739 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1740 idct_add = h->h264dsp.h264_idct8_add;
1742 for (i = 0; i < 16; i += 4) {
1743 uint8_t *const ptr = dest_y + block_offset[i];
1744 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1745 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1746 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1748 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1749 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1750 (h->topright_samples_available << i) & 0x4000, linesize);
1752 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1753 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1755 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1760 if (transform_bypass) {
1762 idct_add = s->dsp.add_pixels4;
1764 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1765 idct_add = h->h264dsp.h264_idct_add;
1767 for (i = 0; i < 16; i++) {
1768 uint8_t *const ptr = dest_y + block_offset[i];
1769 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1771 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1772 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1777 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1778 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1779 assert(s->mb_y || linesize <= block_offset[i]);
1780 if (!topright_avail) {
1782 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1783 topright = (uint8_t *)&tr_high;
1785 tr = ptr[3 - linesize] * 0x01010101u;
1786 topright = (uint8_t *)&tr;
1789 topright = ptr + (4 << pixel_shift) - linesize;
1793 h->hpc.pred4x4[dir](ptr, topright, linesize);
1794 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1797 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1798 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1800 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1801 } else if (CONFIG_SVQ3_DECODER)
1802 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1809 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1811 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1812 if (!transform_bypass)
1813 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1815 h->dequant4_coeff[p][qscale][0]);
1817 static const uint8_t dc_mapping[16] = {
1818 0 * 16, 1 * 16, 4 * 16, 5 * 16,
1819 2 * 16, 3 * 16, 6 * 16, 7 * 16,
1820 8 * 16, 9 * 16, 12 * 16, 13 * 16,
1821 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1822 for (i = 0; i < 16; i++)
1823 dctcoef_set(h->mb + (p * 256 << pixel_shift),
1824 pixel_shift, dc_mapping[i],
1825 dctcoef_get(h->mb_luma_dc[p],
1829 } else if (CONFIG_SVQ3_DECODER)
1830 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
1831 h->mb_luma_dc[p], qscale);
1835 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
1836 int is_h264, int simple,
1837 int transform_bypass,
1841 uint8_t *dest_y, int p)
1843 MpegEncContext *const s = &h->s;
1844 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1846 block_offset += 16 * p;
1847 if (!IS_INTRA4x4(mb_type)) {
1849 if (IS_INTRA16x16(mb_type)) {
1850 if (transform_bypass) {
1851 if (h->sps.profile_idc == 244 &&
1852 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
1853 h->intra16x16_pred_mode == HOR_PRED8x8)) {
1854 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
1855 h->mb + (p * 256 << pixel_shift),
1858 for (i = 0; i < 16; i++)
1859 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
1860 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1861 s->dsp.add_pixels4(dest_y + block_offset[i],
1862 h->mb + (i * 16 + p * 256 << pixel_shift),
1866 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
1867 h->mb + (p * 256 << pixel_shift),
1869 h->non_zero_count_cache + p * 5 * 8);
1871 } else if (h->cbp & 15) {
1872 if (transform_bypass) {
1873 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1874 idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
1875 : s->dsp.add_pixels4;
1876 for (i = 0; i < 16; i += di)
1877 if (h->non_zero_count_cache[scan8[i + p * 16]])
1878 idct_add(dest_y + block_offset[i],
1879 h->mb + (i * 16 + p * 256 << pixel_shift),
1882 if (IS_8x8DCT(mb_type))
1883 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
1884 h->mb + (p * 256 << pixel_shift),
1886 h->non_zero_count_cache + p * 5 * 8);
1888 h->h264dsp.h264_idct_add16(dest_y, block_offset,
1889 h->mb + (p * 256 << pixel_shift),
1891 h->non_zero_count_cache + p * 5 * 8);
1894 } else if (CONFIG_SVQ3_DECODER) {
1895 for (i = 0; i < 16; i++)
1896 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
1897 // FIXME benchmark weird rule, & below
1898 uint8_t *const ptr = dest_y + block_offset[i];
1899 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
1900 s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1908 #include "h264_mb_template.c"
1912 #include "h264_mb_template.c"
1916 #include "h264_mb_template.c"
1918 void ff_h264_hl_decode_mb(H264Context *h)
1920 MpegEncContext *const s = &h->s;
1921 const int mb_xy = h->mb_xy;
1922 const int mb_type = s->current_picture.f.mb_type[mb_xy];
1923 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1926 if (is_complex || h->pixel_shift)
1927 hl_decode_mb_444_complex(h);
1929 hl_decode_mb_444_simple_8(h);
1930 } else if (is_complex) {
1931 hl_decode_mb_complex(h);
1932 } else if (h->pixel_shift) {
1933 hl_decode_mb_simple_16(h);
1935 hl_decode_mb_simple_8(h);
1938 static int pred_weight_table(H264Context *h)
1940 MpegEncContext *const s = &h->s;
1942 int luma_def, chroma_def;
1945 h->use_weight_chroma = 0;
1946 h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
1947 if (h->sps.chroma_format_idc)
1948 h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
1949 luma_def = 1 << h->luma_log2_weight_denom;
1950 chroma_def = 1 << h->chroma_log2_weight_denom;
1952 for (list = 0; list < 2; list++) {
1953 h->luma_weight_flag[list] = 0;
1954 h->chroma_weight_flag[list] = 0;
1955 for (i = 0; i < h->ref_count[list]; i++) {
1956 int luma_weight_flag, chroma_weight_flag;
1958 luma_weight_flag = get_bits1(&s->gb);
1959 if (luma_weight_flag) {
1960 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
1961 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
1962 if (h->luma_weight[i][list][0] != luma_def ||
1963 h->luma_weight[i][list][1] != 0) {
1965 h->luma_weight_flag[list] = 1;
1968 h->luma_weight[i][list][0] = luma_def;
1969 h->luma_weight[i][list][1] = 0;
1972 if (h->sps.chroma_format_idc) {
1973 chroma_weight_flag = get_bits1(&s->gb);
1974 if (chroma_weight_flag) {
1976 for (j = 0; j < 2; j++) {
1977 h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
1978 h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
1979 if (h->chroma_weight[i][list][j][0] != chroma_def ||
1980 h->chroma_weight[i][list][j][1] != 0) {
1981 h->use_weight_chroma = 1;
1982 h->chroma_weight_flag[list] = 1;
1987 for (j = 0; j < 2; j++) {
1988 h->chroma_weight[i][list][j][0] = chroma_def;
1989 h->chroma_weight[i][list][j][1] = 0;
1994 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1997 h->use_weight = h->use_weight || h->use_weight_chroma;
2002 * Initialize implicit_weight table.
2003 * @param field 0/1 initialize the weight for interlaced MBAFF
2004 * -1 initializes the rest
2006 static void implicit_weight_table(H264Context *h, int field)
2008 MpegEncContext *const s = &h->s;
2009 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2011 for (i = 0; i < 2; i++) {
2012 h->luma_weight_flag[i] = 0;
2013 h->chroma_weight_flag[i] = 0;
2017 if (s->picture_structure == PICT_FRAME) {
2018 cur_poc = s->current_picture_ptr->poc;
2020 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2022 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2023 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2025 h->use_weight_chroma = 0;
2029 ref_count0 = h->ref_count[0];
2030 ref_count1 = h->ref_count[1];
2032 cur_poc = s->current_picture_ptr->field_poc[field];
2034 ref_count0 = 16 + 2 * h->ref_count[0];
2035 ref_count1 = 16 + 2 * h->ref_count[1];
2039 h->use_weight_chroma = 2;
2040 h->luma_log2_weight_denom = 5;
2041 h->chroma_log2_weight_denom = 5;
2043 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2044 int poc0 = h->ref_list[0][ref0].poc;
2045 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2047 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2048 int poc1 = h->ref_list[1][ref1].poc;
2049 int td = av_clip(poc1 - poc0, -128, 127);
2051 int tb = av_clip(cur_poc - poc0, -128, 127);
2052 int tx = (16384 + (FFABS(td) >> 1)) / td;
2053 int dist_scale_factor = (tb * tx + 32) >> 8;
2054 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2055 w = 64 - dist_scale_factor;
2059 h->implicit_weight[ref0][ref1][0] =
2060 h->implicit_weight[ref0][ref1][1] = w;
2062 h->implicit_weight[ref0][ref1][field] = w;
2069 * instantaneous decoder refresh.
2071 static void idr(H264Context *h)
2074 ff_h264_remove_all_refs(h);
2075 h->prev_frame_num = 0;
2076 h->prev_frame_num_offset = 0;
2077 h->prev_poc_msb = 1<<16;
2078 h->prev_poc_lsb = 0;
2079 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2080 h->last_pocs[i] = INT_MIN;
2083 /* forget old pics after a seek */
2084 static void flush_dpb(AVCodecContext *avctx)
2086 H264Context *h = avctx->priv_data;
2088 for (i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
2089 if (h->delayed_pic[i])
2090 h->delayed_pic[i]->f.reference = 0;
2091 h->delayed_pic[i] = NULL;
2093 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2094 h->prev_interlaced_frame = 1;
2096 h->prev_frame_num = -1;
2097 if (h->s.current_picture_ptr)
2098 h->s.current_picture_ptr->f.reference = 0;
2099 h->s.first_field = 0;
2100 ff_h264_reset_sei(h);
2101 ff_mpeg_flush(avctx);
2102 h->recovery_frame= -1;
2106 static int init_poc(H264Context *h)
2108 MpegEncContext *const s = &h->s;
2109 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2111 Picture *cur = s->current_picture_ptr;
2113 h->frame_num_offset = h->prev_frame_num_offset;
2114 if (h->frame_num < h->prev_frame_num)
2115 h->frame_num_offset += max_frame_num;
2117 if (h->sps.poc_type == 0) {
2118 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2120 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2121 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2122 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2123 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2125 h->poc_msb = h->prev_poc_msb;
2126 // printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2128 field_poc[1] = h->poc_msb + h->poc_lsb;
2129 if (s->picture_structure == PICT_FRAME)
2130 field_poc[1] += h->delta_poc_bottom;
2131 } else if (h->sps.poc_type == 1) {
2132 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2135 if (h->sps.poc_cycle_length != 0)
2136 abs_frame_num = h->frame_num_offset + h->frame_num;
2140 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2143 expected_delta_per_poc_cycle = 0;
2144 for (i = 0; i < h->sps.poc_cycle_length; i++)
2145 // FIXME integrate during sps parse
2146 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2148 if (abs_frame_num > 0) {
2149 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2150 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2152 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2153 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2154 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2158 if (h->nal_ref_idc == 0)
2159 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2161 field_poc[0] = expectedpoc + h->delta_poc[0];
2162 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2164 if (s->picture_structure == PICT_FRAME)
2165 field_poc[1] += h->delta_poc[1];
2167 int poc = 2 * (h->frame_num_offset + h->frame_num);
2169 if (!h->nal_ref_idc)
2176 if (s->picture_structure != PICT_BOTTOM_FIELD)
2177 s->current_picture_ptr->field_poc[0] = field_poc[0];
2178 if (s->picture_structure != PICT_TOP_FIELD)
2179 s->current_picture_ptr->field_poc[1] = field_poc[1];
2180 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2186 * initialize scan tables
2188 static void init_scan_tables(H264Context *h)
2191 for (i = 0; i < 16; i++) {
2192 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2193 h->zigzag_scan[i] = T(zigzag_scan[i]);
2194 h->field_scan[i] = T(field_scan[i]);
2197 for (i = 0; i < 64; i++) {
2198 #define T(x) (x >> 3) | ((x & 7) << 3)
2199 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2200 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2201 h->field_scan8x8[i] = T(field_scan8x8[i]);
2202 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2205 if (h->sps.transform_bypass) { // FIXME same ugly
2206 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2207 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2208 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2209 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2210 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2211 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2213 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2214 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2215 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2216 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2217 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2218 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2222 static int field_end(H264Context *h, int in_setup)
2224 MpegEncContext *const s = &h->s;
2225 AVCodecContext *const avctx = s->avctx;
2229 if (!in_setup && !s->dropable)
2230 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2231 s->picture_structure == PICT_BOTTOM_FIELD);
2233 if (CONFIG_H264_VDPAU_DECODER &&
2234 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2235 ff_vdpau_h264_set_reference_frames(s);
2237 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2239 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2240 h->prev_poc_msb = h->poc_msb;
2241 h->prev_poc_lsb = h->poc_lsb;
2243 h->prev_frame_num_offset = h->frame_num_offset;
2244 h->prev_frame_num = h->frame_num;
2245 h->outputed_poc = h->next_outputed_poc;
2248 if (avctx->hwaccel) {
2249 if (avctx->hwaccel->end_frame(avctx) < 0)
2250 av_log(avctx, AV_LOG_ERROR,
2251 "hardware accelerator failed to decode picture\n");
2254 if (CONFIG_H264_VDPAU_DECODER &&
2255 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2256 ff_vdpau_h264_picture_complete(s);
2259 * FIXME: Error handling code does not seem to support interlaced
2260 * when slices span multiple rows
2261 * The ff_er_add_slice calls don't work right for bottom
2262 * fields; they cause massive erroneous error concealing
2263 * Error marking covers both fields (top and bottom).
2264 * This causes a mismatched s->error_count
2265 * and a bad error table. Further, the error count goes to
2266 * INT_MAX when called for bottom field, because mb_y is
2267 * past end by one (callers fault) and resync_mb_y != 0
2268 * causes problems for the first MB line, too.
2273 ff_MPV_frame_end(s);
2275 h->current_slice = 0;
2281 * Replicate H264 "master" context to thread contexts.
2283 static void clone_slice(H264Context *dst, H264Context *src)
2285 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2286 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2287 dst->s.current_picture = src->s.current_picture;
2288 dst->s.linesize = src->s.linesize;
2289 dst->s.uvlinesize = src->s.uvlinesize;
2290 dst->s.first_field = src->s.first_field;
2292 dst->prev_poc_msb = src->prev_poc_msb;
2293 dst->prev_poc_lsb = src->prev_poc_lsb;
2294 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2295 dst->prev_frame_num = src->prev_frame_num;
2296 dst->short_ref_count = src->short_ref_count;
2298 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2299 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2300 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2301 memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
2303 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2304 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2308 * Compute profile from profile_idc and constraint_set?_flags.
2312 * @return profile as defined by FF_PROFILE_H264_*
2314 int ff_h264_get_profile(SPS *sps)
2316 int profile = sps->profile_idc;
2318 switch (sps->profile_idc) {
2319 case FF_PROFILE_H264_BASELINE:
2320 // constraint_set1_flag set to 1
2321 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2323 case FF_PROFILE_H264_HIGH_10:
2324 case FF_PROFILE_H264_HIGH_422:
2325 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2326 // constraint_set3_flag set to 1
2327 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2335 * Decode a slice header.
2336 * This will also call ff_MPV_common_init() and frame_start() as needed.
2338 * @param h h264context
2339 * @param h0 h264 master context (differs from 'h' when doing sliced based
2340 * parallel decoding)
2342 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2344 static int decode_slice_header(H264Context *h, H264Context *h0)
2346 MpegEncContext *const s = &h->s;
2347 MpegEncContext *const s0 = &h0->s;
2348 unsigned int first_mb_in_slice;
2349 unsigned int pps_id;
2350 int num_ref_idx_active_override_flag;
2351 unsigned int slice_type, tmp, i, j;
2352 int default_ref_list_done = 0;
2353 int last_pic_structure, last_pic_dropable;
2356 /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2357 if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
2358 !h->nal_ref_idc && !h->pixel_shift) {
2359 s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
2360 s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
2362 s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
2363 s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
2366 first_mb_in_slice = get_ue_golomb_long(&s->gb);
2368 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2369 if (h0->current_slice && FIELD_PICTURE) {
2373 h0->current_slice = 0;
2374 if (!s0->first_field) {
2375 if (s->current_picture_ptr && !s->dropable &&
2376 s->current_picture_ptr->owner2 == s) {
2377 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2378 s->picture_structure == PICT_BOTTOM_FIELD);
2380 s->current_picture_ptr = NULL;
2384 slice_type = get_ue_golomb_31(&s->gb);
2385 if (slice_type > 9) {
2386 av_log(h->s.avctx, AV_LOG_ERROR,
2387 "slice type too large (%d) at %d %d\n",
2388 h->slice_type, s->mb_x, s->mb_y);
2391 if (slice_type > 4) {
2393 h->slice_type_fixed = 1;
2395 h->slice_type_fixed = 0;
2397 slice_type = golomb_to_pict_type[slice_type];
2398 if (slice_type == AV_PICTURE_TYPE_I ||
2399 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2400 default_ref_list_done = 1;
2402 h->slice_type = slice_type;
2403 h->slice_type_nos = slice_type & 3;
2405 // to make a few old functions happy, it's wrong though
2406 s->pict_type = h->slice_type;
2408 pps_id = get_ue_golomb(&s->gb);
2409 if (pps_id >= MAX_PPS_COUNT) {
2410 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
2413 if (!h0->pps_buffers[pps_id]) {
2414 av_log(h->s.avctx, AV_LOG_ERROR,
2415 "non-existing PPS %u referenced\n",
2419 h->pps = *h0->pps_buffers[pps_id];
2421 if (!h0->sps_buffers[h->pps.sps_id]) {
2422 av_log(h->s.avctx, AV_LOG_ERROR,
2423 "non-existing SPS %u referenced\n",
2427 h->sps = *h0->sps_buffers[h->pps.sps_id];
2429 s->avctx->profile = ff_h264_get_profile(&h->sps);
2430 s->avctx->level = h->sps.level_idc;
2431 s->avctx->refs = h->sps.ref_frame_count;
2433 must_reinit = (s->context_initialized &&
2434 ( 16*h->sps.mb_width != s->avctx->coded_width
2435 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != s->avctx->coded_height
2436 || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
2437 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
2438 || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio)));
2440 if(must_reinit && (h != h0 || (s->avctx->active_thread_type & FF_THREAD_FRAME))) {
2441 av_log_missing_feature(s->avctx,
2442 "Width/height/bit depth/chroma idc changing with threads is", 0);
2443 return AVERROR_PATCHWELCOME; // width / height changed during parallelized decoding
2446 s->mb_width = h->sps.mb_width;
2447 s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2449 h->b_stride = s->mb_width * 4;
2451 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2453 s->width = 16 * s->mb_width;
2454 s->height = 16 * s->mb_height;
2458 flush_dpb(s->avctx);
2459 ff_MPV_common_end(s);
2461 h->current_slice = 0;
2463 if (!s->context_initialized) {
2465 av_log(h->s.avctx, AV_LOG_ERROR,
2466 "Cannot (re-)initialize context during parallel decoding.\n");
2469 if( FFALIGN(s->avctx->width , 16 ) == s->width
2470 && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height
2471 && !h->sps.crop_right && !h->sps.crop_bottom
2472 && (s->avctx->width != s->width || s->avctx->height && s->height)
2474 av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
2475 s->avctx->coded_width = s->width;
2476 s->avctx->coded_height = s->height;
2478 avcodec_set_dimensions(s->avctx, s->width, s->height);
2479 s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2480 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);
2482 s->avctx->sample_aspect_ratio = h->sps.sar;
2483 av_assert0(s->avctx->sample_aspect_ratio.den);
2485 if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2486 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2487 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10 &&
2488 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2489 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2490 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2491 h->pixel_shift = h->sps.bit_depth_luma > 8;
2493 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2494 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, 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);
2498 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
2499 h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2504 if (h->sps.video_signal_type_present_flag) {
2505 s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
2507 if (h->sps.colour_description_present_flag) {
2508 s->avctx->color_primaries = h->sps.color_primaries;
2509 s->avctx->color_trc = h->sps.color_trc;
2510 s->avctx->colorspace = h->sps.colorspace;
2514 if (h->sps.timing_info_present_flag) {
2515 int64_t den = h->sps.time_scale;
2516 if (h->x264_build < 44U)
2518 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2519 h->sps.num_units_in_tick, den, 1 << 30);
2522 switch (h->sps.bit_depth_luma) {
2525 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2526 s->avctx->pix_fmt = PIX_FMT_GBRP9;
2528 s->avctx->pix_fmt = PIX_FMT_YUV444P9;
2529 } else if (CHROMA422)
2530 s->avctx->pix_fmt = PIX_FMT_YUV422P9;
2532 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
2536 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2537 s->avctx->pix_fmt = PIX_FMT_GBRP10;
2539 s->avctx->pix_fmt = PIX_FMT_YUV444P10;
2540 } else if (CHROMA422)
2541 s->avctx->pix_fmt = PIX_FMT_YUV422P10;
2543 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
2547 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P
2549 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2550 s->avctx->pix_fmt = PIX_FMT_GBR24P;
2551 av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2552 } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
2553 av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2555 } else if (CHROMA422) {
2556 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P
2559 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2560 s->avctx->codec->pix_fmts ?
2561 s->avctx->codec->pix_fmts :
2562 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2563 hwaccel_pixfmt_list_h264_jpeg_420 :
2564 ff_hwaccel_pixfmt_list_420);
2568 av_log(s->avctx, AV_LOG_ERROR,
2569 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2570 return AVERROR_INVALIDDATA;
2573 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
2576 if (ff_MPV_common_init(s) < 0) {
2577 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
2581 h->prev_interlaced_frame = 1;
2583 init_scan_tables(h);
2584 if (ff_h264_alloc_tables(h) < 0) {
2585 av_log(h->s.avctx, AV_LOG_ERROR,
2586 "Could not allocate memory for h264\n");
2587 return AVERROR(ENOMEM);
2590 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
2591 if (context_init(h) < 0) {
2592 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2596 for (i = 1; i < s->slice_context_count; i++) {
2598 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2599 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2600 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2601 c->h264dsp = h->h264dsp;
2604 c->pixel_shift = h->pixel_shift;
2605 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
2606 init_scan_tables(c);
2607 clone_tables(c, h, i);
2610 for (i = 0; i < s->slice_context_count; i++)
2611 if (context_init(h->thread_context[i]) < 0) {
2612 av_log(h->s.avctx, AV_LOG_ERROR,
2613 "context_init() failed.\n");
2619 if (h == h0 && h->dequant_coeff_pps != pps_id) {
2620 h->dequant_coeff_pps = pps_id;
2621 init_dequant_tables(h);
2624 h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
2627 h->mb_aff_frame = 0;
2628 last_pic_structure = s0->picture_structure;
2629 last_pic_dropable = s->dropable;
2630 s->dropable = h->nal_ref_idc == 0;
2631 if (h->sps.frame_mbs_only_flag) {
2632 s->picture_structure = PICT_FRAME;
2634 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
2635 av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
2638 if (get_bits1(&s->gb)) { // field_pic_flag
2639 s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
2641 s->picture_structure = PICT_FRAME;
2642 h->mb_aff_frame = h->sps.mb_aff;
2645 h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
2647 if (h0->current_slice != 0) {
2648 if (last_pic_structure != s->picture_structure ||
2649 last_pic_dropable != s->dropable) {
2650 av_log(h->s.avctx, AV_LOG_ERROR,
2651 "Changing field mode (%d -> %d) between slices is not allowed\n",
2652 last_pic_structure, s->picture_structure);
2653 s->picture_structure = last_pic_structure;
2654 s->dropable = last_pic_dropable;
2655 return AVERROR_INVALIDDATA;
2658 /* Shorten frame num gaps so we don't have to allocate reference
2659 * frames just to throw them away */
2660 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
2661 int unwrap_prev_frame_num = h->prev_frame_num;
2662 int max_frame_num = 1 << h->sps.log2_max_frame_num;
2664 if (unwrap_prev_frame_num > h->frame_num)
2665 unwrap_prev_frame_num -= max_frame_num;
2667 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2668 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2669 if (unwrap_prev_frame_num < 0)
2670 unwrap_prev_frame_num += max_frame_num;
2672 h->prev_frame_num = unwrap_prev_frame_num;
2676 /* See if we have a decoded first field looking for a pair...
2677 * Here, we're using that to see if we should mark previously
2678 * decode frames as "finished".
2679 * We have to do that before the "dummy" in-between frame allocation,
2680 * since that can modify s->current_picture_ptr. */
2681 if (s0->first_field) {
2682 assert(s0->current_picture_ptr);
2683 assert(s0->current_picture_ptr->f.data[0]);
2684 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2686 /* Mark old field/frame as completed */
2687 if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
2688 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2689 last_pic_structure == PICT_BOTTOM_FIELD);
2692 /* figure out if we have a complementary field pair */
2693 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2694 /* Previous field is unmatched. Don't display it, but let it
2695 * remain for reference if marked as such. */
2696 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
2697 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2698 last_pic_structure == PICT_TOP_FIELD);
2701 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2702 /* This and previous field were reference, but had
2703 * different frame_nums. Consider this field first in
2704 * pair. Throw away previous field except for reference
2706 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
2707 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2708 last_pic_structure == PICT_TOP_FIELD);
2711 /* Second field in complementary pair */
2712 if (!((last_pic_structure == PICT_TOP_FIELD &&
2713 s->picture_structure == PICT_BOTTOM_FIELD) ||
2714 (last_pic_structure == PICT_BOTTOM_FIELD &&
2715 s->picture_structure == PICT_TOP_FIELD))) {
2716 av_log(s->avctx, AV_LOG_ERROR,
2717 "Invalid field mode combination %d/%d\n",
2718 last_pic_structure, s->picture_structure);
2719 s->picture_structure = last_pic_structure;
2720 s->dropable = last_pic_dropable;
2721 return AVERROR_INVALIDDATA;
2722 } else if (last_pic_dropable != s->dropable) {
2723 av_log(s->avctx, AV_LOG_ERROR,
2724 "Cannot combine reference and non-reference fields in the same frame\n");
2725 av_log_ask_for_sample(s->avctx, NULL);
2726 s->picture_structure = last_pic_structure;
2727 s->dropable = last_pic_dropable;
2728 return AVERROR_INVALIDDATA;
2731 /* Take ownership of this buffer. Note that if another thread owned
2732 * the first field of this buffer, we're not operating on that pointer,
2733 * so the original thread is still responsible for reporting progress
2734 * on that first field (or if that was us, we just did that above).
2735 * By taking ownership, we assign responsibility to ourselves to
2736 * report progress on the second field. */
2737 s0->current_picture_ptr->owner2 = s0;
2742 while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
2743 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
2744 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2745 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
2746 h->frame_num, h->prev_frame_num);
2747 if (ff_h264_frame_start(h) < 0)
2749 h->prev_frame_num++;
2750 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
2751 s->current_picture_ptr->frame_num = h->prev_frame_num;
2752 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
2753 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
2754 ff_generate_sliding_window_mmcos(h);
2755 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2756 (s->avctx->err_recognition & AV_EF_EXPLODE))
2757 return AVERROR_INVALIDDATA;
2758 /* Error concealment: if a ref is missing, copy the previous ref in its place.
2759 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2760 * about there being no actual duplicates.
2761 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
2762 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2764 if (h->short_ref_count) {
2766 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2767 (const uint8_t **)prev->f.data, prev->f.linesize,
2768 s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
2769 h->short_ref[0]->poc = prev->poc + 2;
2771 h->short_ref[0]->frame_num = h->prev_frame_num;
2775 /* See if we have a decoded first field looking for a pair...
2776 * We're using that to see whether to continue decoding in that
2777 * frame, or to allocate a new one. */
2778 if (s0->first_field) {
2779 assert(s0->current_picture_ptr);
2780 assert(s0->current_picture_ptr->f.data[0]);
2781 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2783 /* figure out if we have a complementary field pair */
2784 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2785 /* Previous field is unmatched. Don't display it, but let it
2786 * remain for reference if marked as such. */
2787 s0->current_picture_ptr = NULL;
2788 s0->first_field = FIELD_PICTURE;
2790 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2791 ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
2792 s0->picture_structure==PICT_BOTTOM_FIELD);
2793 /* This and the previous field had different frame_nums.
2794 * Consider this field first in pair. Throw away previous
2795 * one except for reference purposes. */
2796 s0->first_field = 1;
2797 s0->current_picture_ptr = NULL;
2799 /* Second field in complementary pair */
2800 s0->first_field = 0;
2804 /* Frame or first field in a potentially complementary pair */
2805 assert(!s0->current_picture_ptr);
2806 s0->first_field = FIELD_PICTURE;
2809 if (!FIELD_PICTURE || s0->first_field) {
2810 if (ff_h264_frame_start(h) < 0) {
2811 s0->first_field = 0;
2815 ff_release_unused_pictures(s, 0);
2821 s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
2823 assert(s->mb_num == s->mb_width * s->mb_height);
2824 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2825 first_mb_in_slice >= s->mb_num) {
2826 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2829 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2830 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2831 if (s->picture_structure == PICT_BOTTOM_FIELD)
2832 s->resync_mb_y = s->mb_y = s->mb_y + 1;
2833 assert(s->mb_y < s->mb_height);
2835 if (s->picture_structure == PICT_FRAME) {
2836 h->curr_pic_num = h->frame_num;
2837 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
2839 h->curr_pic_num = 2 * h->frame_num + 1;
2840 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
2843 if (h->nal_unit_type == NAL_IDR_SLICE)
2844 get_ue_golomb(&s->gb); /* idr_pic_id */
2846 if (h->sps.poc_type == 0) {
2847 h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2849 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2850 h->delta_poc_bottom = get_se_golomb(&s->gb);
2853 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
2854 h->delta_poc[0] = get_se_golomb(&s->gb);
2856 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2857 h->delta_poc[1] = get_se_golomb(&s->gb);
2862 if (h->pps.redundant_pic_cnt_present)
2863 h->redundant_pic_count = get_ue_golomb(&s->gb);
2865 // set defaults, might be overridden a few lines later
2866 h->ref_count[0] = h->pps.ref_count[0];
2867 h->ref_count[1] = h->pps.ref_count[1];
2869 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2871 max[0] = max[1] = s->picture_structure == PICT_FRAME ? 15 : 31;
2873 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2874 h->direct_spatial_mv_pred = get_bits1(&s->gb);
2875 num_ref_idx_active_override_flag = get_bits1(&s->gb);
2877 if (num_ref_idx_active_override_flag) {
2878 h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
2879 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2880 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
2882 // full range is spec-ok in this case, even for frames
2886 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
2887 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]);
2888 h->ref_count[0] = h->ref_count[1] = 1;
2889 return AVERROR_INVALIDDATA;
2892 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2897 h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
2899 if (!default_ref_list_done)
2900 ff_h264_fill_default_ref_list(h);
2902 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
2903 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
2904 h->ref_count[1] = h->ref_count[0] = 0;
2908 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2909 s->last_picture_ptr = &h->ref_list[0][0];
2910 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2912 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
2913 s->next_picture_ptr = &h->ref_list[1][0];
2914 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2917 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
2918 (h->pps.weighted_bipred_idc == 1 &&
2919 h->slice_type_nos == AV_PICTURE_TYPE_B))
2920 pred_weight_table(h);
2921 else if (h->pps.weighted_bipred_idc == 2 &&
2922 h->slice_type_nos == AV_PICTURE_TYPE_B) {
2923 implicit_weight_table(h, -1);
2926 for (i = 0; i < 2; i++) {
2927 h->luma_weight_flag[i] = 0;
2928 h->chroma_weight_flag[i] = 0;
2932 if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
2933 (s->avctx->err_recognition & AV_EF_EXPLODE))
2934 return AVERROR_INVALIDDATA;
2937 ff_h264_fill_mbaff_ref_list(h);
2939 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
2940 implicit_weight_table(h, 0);
2941 implicit_weight_table(h, 1);
2945 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
2946 ff_h264_direct_dist_scale_factor(h);
2947 ff_h264_direct_ref_list_init(h);
2949 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
2950 tmp = get_ue_golomb_31(&s->gb);
2952 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2955 h->cabac_init_idc = tmp;
2958 h->last_qscale_diff = 0;
2959 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2960 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
2961 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2965 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2966 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2967 // FIXME qscale / qp ... stuff
2968 if (h->slice_type == AV_PICTURE_TYPE_SP)
2969 get_bits1(&s->gb); /* sp_for_switch_flag */
2970 if (h->slice_type == AV_PICTURE_TYPE_SP ||
2971 h->slice_type == AV_PICTURE_TYPE_SI)
2972 get_se_golomb(&s->gb); /* slice_qs_delta */
2974 h->deblocking_filter = 1;
2975 h->slice_alpha_c0_offset = 52;
2976 h->slice_beta_offset = 52;
2977 if (h->pps.deblocking_filter_parameters_present) {
2978 tmp = get_ue_golomb_31(&s->gb);
2980 av_log(s->avctx, AV_LOG_ERROR,
2981 "deblocking_filter_idc %u out of range\n", tmp);
2984 h->deblocking_filter = tmp;
2985 if (h->deblocking_filter < 2)
2986 h->deblocking_filter ^= 1; // 1<->0
2988 if (h->deblocking_filter) {
2989 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2990 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
2991 if (h->slice_alpha_c0_offset > 104U ||
2992 h->slice_beta_offset > 104U) {
2993 av_log(s->avctx, AV_LOG_ERROR,
2994 "deblocking filter parameters %d %d out of range\n",
2995 h->slice_alpha_c0_offset, h->slice_beta_offset);
3001 if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3002 (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3003 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3004 (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3005 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3006 (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3007 h->nal_ref_idc == 0))
3008 h->deblocking_filter = 0;
3010 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3011 if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3012 /* Cheat slightly for speed:
3013 * Do not bother to deblock across slices. */
3014 h->deblocking_filter = 2;
3016 h0->max_contexts = 1;
3017 if (!h0->single_decode_warning) {
3018 av_log(s->avctx, AV_LOG_INFO,
3019 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3020 h0->single_decode_warning = 1;
3023 av_log(h->s.avctx, AV_LOG_ERROR,
3024 "Deblocking switched inside frame.\n");
3029 h->qp_thresh = 15 + 52 -
3030 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3032 h->pps.chroma_qp_index_offset[0],
3033 h->pps.chroma_qp_index_offset[1]) +
3034 6 * (h->sps.bit_depth_luma - 8);
3036 h0->last_slice_type = slice_type;
3037 h->slice_num = ++h0->current_slice;
3040 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
3041 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
3042 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
3043 && h->slice_num >= MAX_SLICES) {
3044 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3045 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);
3048 for (j = 0; j < 2; j++) {
3050 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3051 for (i = 0; i < 16; i++) {
3053 if (h->ref_list[j][i].f.data[0]) {
3055 uint8_t *base = h->ref_list[j][i].f.base[0];
3056 for (k = 0; k < h->short_ref_count; k++)
3057 if (h->short_ref[k]->f.base[0] == base) {
3061 for (k = 0; k < h->long_ref_count; k++)
3062 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3063 id_list[i] = h->short_ref_count + k;
3071 for (i = 0; i < 16; i++)
3072 ref2frm[i + 2] = 4 * id_list[i] +
3073 (h->ref_list[j][i].f.reference & 3);
3075 ref2frm[18 + 1] = -1;
3076 for (i = 16; i < 48; i++)
3077 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3078 (h->ref_list[j][i].f.reference & 3);
3081 // FIXME: fix draw_edges + PAFF + frame threads
3082 h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
3083 (!h->sps.frame_mbs_only_flag &&
3084 s->avctx->active_thread_type))
3086 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3088 if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3089 av_log(h->s.avctx, AV_LOG_DEBUG,
3090 "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",
3092 (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3094 av_get_picture_type_char(h->slice_type),
3095 h->slice_type_fixed ? " fix" : "",
3096 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3097 pps_id, h->frame_num,
3098 s->current_picture_ptr->field_poc[0],
3099 s->current_picture_ptr->field_poc[1],
3100 h->ref_count[0], h->ref_count[1],
3102 h->deblocking_filter,
3103 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3105 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3106 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3112 int ff_h264_get_slice_type(const H264Context *h)
3114 switch (h->slice_type) {
3115 case AV_PICTURE_TYPE_P:
3117 case AV_PICTURE_TYPE_B:
3119 case AV_PICTURE_TYPE_I:
3121 case AV_PICTURE_TYPE_SP:
3123 case AV_PICTURE_TYPE_SI:
3130 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3131 MpegEncContext *const s,
3132 int mb_type, int top_xy,
3133 int left_xy[LEFT_MBS],
3135 int left_type[LEFT_MBS],
3136 int mb_xy, int list)
3138 int b_stride = h->b_stride;
3139 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3140 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3141 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3142 if (USES_LIST(top_type, list)) {
3143 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3144 const int b8_xy = 4 * top_xy + 2;
3145 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3146 AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
3147 ref_cache[0 - 1 * 8] =
3148 ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3149 ref_cache[2 - 1 * 8] =
3150 ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3152 AV_ZERO128(mv_dst - 1 * 8);
3153 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3156 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3157 if (USES_LIST(left_type[LTOP], list)) {
3158 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3159 const int b8_xy = 4 * left_xy[LTOP] + 1;
3160 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3161 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
3162 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
3163 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
3164 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
3166 ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
3167 ref_cache[-1 + 16] =
3168 ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
3170 AV_ZERO32(mv_dst - 1 + 0);
3171 AV_ZERO32(mv_dst - 1 + 8);
3172 AV_ZERO32(mv_dst - 1 + 16);
3173 AV_ZERO32(mv_dst - 1 + 24);
3176 ref_cache[-1 + 16] =
3177 ref_cache[-1 + 24] = LIST_NOT_USED;
3182 if (!USES_LIST(mb_type, list)) {
3183 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3184 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3185 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3186 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3187 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3192 int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
3193 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3194 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3195 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3196 AV_WN32A(&ref_cache[0 * 8], ref01);
3197 AV_WN32A(&ref_cache[1 * 8], ref01);
3198 AV_WN32A(&ref_cache[2 * 8], ref23);
3199 AV_WN32A(&ref_cache[3 * 8], ref23);
3203 int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
3204 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3205 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3206 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3207 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3213 * @return non zero if the loop filter can be skipped
3215 static int fill_filter_caches(H264Context *h, int mb_type)
3217 MpegEncContext *const s = &h->s;
3218 const int mb_xy = h->mb_xy;
3219 int top_xy, left_xy[LEFT_MBS];
3220 int top_type, left_type[LEFT_MBS];
3224 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3226 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3227 * stuff, I can't imagine that these complex rules are worth it. */
3229 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3231 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3232 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3234 if (left_mb_field_flag != curr_mb_field_flag)
3235 left_xy[LTOP] -= s->mb_stride;
3237 if (curr_mb_field_flag)
3238 top_xy += s->mb_stride &
3239 (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3240 if (left_mb_field_flag != curr_mb_field_flag)
3241 left_xy[LBOT] += s->mb_stride;
3245 h->top_mb_xy = top_xy;
3246 h->left_mb_xy[LTOP] = left_xy[LTOP];
3247 h->left_mb_xy[LBOT] = left_xy[LBOT];
3249 /* For sufficiently low qp, filtering wouldn't do anything.
3250 * This is a conservative estimate: could also check beta_offset
3251 * and more accurate chroma_qp. */
3252 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3253 int qp = s->current_picture.f.qscale_table[mb_xy];
3254 if (qp <= qp_thresh &&
3255 (left_xy[LTOP] < 0 ||
3256 ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3258 ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3261 if ((left_xy[LTOP] < 0 ||
3262 ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3263 (top_xy < s->mb_stride ||
3264 ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3269 top_type = s->current_picture.f.mb_type[top_xy];
3270 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3271 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3272 if (h->deblocking_filter == 2) {
3273 if (h->slice_table[top_xy] != h->slice_num)
3275 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3276 left_type[LTOP] = left_type[LBOT] = 0;
3278 if (h->slice_table[top_xy] == 0xFFFF)
3280 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3281 left_type[LTOP] = left_type[LBOT] = 0;
3283 h->top_type = top_type;
3284 h->left_type[LTOP] = left_type[LTOP];
3285 h->left_type[LBOT] = left_type[LBOT];
3287 if (IS_INTRA(mb_type))
3290 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3291 top_type, left_type, mb_xy, 0);
3292 if (h->list_count == 2)
3293 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3294 top_type, left_type, mb_xy, 1);
3296 nnz = h->non_zero_count[mb_xy];
3297 nnz_cache = h->non_zero_count_cache;
3298 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3299 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3300 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3301 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3302 h->cbp = h->cbp_table[mb_xy];
3305 nnz = h->non_zero_count[top_xy];
3306 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3309 if (left_type[LTOP]) {
3310 nnz = h->non_zero_count[left_xy[LTOP]];
3311 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3312 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3313 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3314 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3317 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3318 * from what the loop filter needs */
3319 if (!CABAC && h->pps.transform_8x8_mode) {
3320 if (IS_8x8DCT(top_type)) {
3321 nnz_cache[4 + 8 * 0] =
3322 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3323 nnz_cache[6 + 8 * 0] =
3324 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3326 if (IS_8x8DCT(left_type[LTOP])) {
3327 nnz_cache[3 + 8 * 1] =
3328 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3330 if (IS_8x8DCT(left_type[LBOT])) {
3331 nnz_cache[3 + 8 * 3] =
3332 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3335 if (IS_8x8DCT(mb_type)) {
3336 nnz_cache[scan8[0]] =
3337 nnz_cache[scan8[1]] =
3338 nnz_cache[scan8[2]] =
3339 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3341 nnz_cache[scan8[0 + 4]] =
3342 nnz_cache[scan8[1 + 4]] =
3343 nnz_cache[scan8[2 + 4]] =
3344 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3346 nnz_cache[scan8[0 + 8]] =
3347 nnz_cache[scan8[1 + 8]] =
3348 nnz_cache[scan8[2 + 8]] =
3349 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3351 nnz_cache[scan8[0 + 12]] =
3352 nnz_cache[scan8[1 + 12]] =
3353 nnz_cache[scan8[2 + 12]] =
3354 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3361 static void loop_filter(H264Context *h, int start_x, int end_x)
3363 MpegEncContext *const s = &h->s;
3364 uint8_t *dest_y, *dest_cb, *dest_cr;
3365 int linesize, uvlinesize, mb_x, mb_y;
3366 const int end_mb_y = s->mb_y + FRAME_MBAFF;
3367 const int old_slice_type = h->slice_type;
3368 const int pixel_shift = h->pixel_shift;
3369 const int block_h = 16 >> s->chroma_y_shift;
3371 if (h->deblocking_filter) {
3372 for (mb_x = start_x; mb_x < end_x; mb_x++)
3373 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
3375 mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
3376 h->slice_num = h->slice_table[mb_xy];
3377 mb_type = s->current_picture.f.mb_type[mb_xy];
3378 h->list_count = h->list_counts[mb_xy];
3382 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3386 dest_y = s->current_picture.f.data[0] +
3387 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
3388 dest_cb = s->current_picture.f.data[1] +
3389 (mb_x << pixel_shift) * (8 << CHROMA444) +
3390 mb_y * s->uvlinesize * block_h;
3391 dest_cr = s->current_picture.f.data[2] +
3392 (mb_x << pixel_shift) * (8 << CHROMA444) +
3393 mb_y * s->uvlinesize * block_h;
3394 // FIXME simplify above
3397 linesize = h->mb_linesize = s->linesize * 2;
3398 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3399 if (mb_y & 1) { // FIXME move out of this function?
3400 dest_y -= s->linesize * 15;
3401 dest_cb -= s->uvlinesize * (block_h - 1);
3402 dest_cr -= s->uvlinesize * (block_h - 1);
3405 linesize = h->mb_linesize = s->linesize;
3406 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3408 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
3410 if (fill_filter_caches(h, mb_type))
3412 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3413 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3416 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
3417 linesize, uvlinesize);
3419 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
3420 dest_cr, linesize, uvlinesize);
3424 h->slice_type = old_slice_type;
3426 s->mb_y = end_mb_y - FRAME_MBAFF;
3427 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3428 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3431 static void predict_field_decoding_flag(H264Context *h)
3433 MpegEncContext *const s = &h->s;
3434 const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
3435 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
3436 s->current_picture.f.mb_type[mb_xy - 1] :
3437 (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
3438 s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
3439 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3443 * Draw edges and report progress for the last MB row.
3445 static void decode_finish_row(H264Context *h)
3447 MpegEncContext *const s = &h->s;
3448 int top = 16 * (s->mb_y >> FIELD_PICTURE);
3449 int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
3450 int height = 16 << FRAME_MBAFF;
3451 int deblock_border = (16 + 4) << FRAME_MBAFF;
3453 if (h->deblocking_filter) {
3454 if ((top + height) >= pic_height)
3455 height += deblock_border;
3456 top -= deblock_border;
3459 if (top >= pic_height || (top + height) < h->emu_edge_height)
3462 height = FFMIN(height, pic_height - top);
3463 if (top < h->emu_edge_height) {
3464 height = top + height;
3468 ff_draw_horiz_band(s, top, height);
3473 ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
3474 s->picture_structure == PICT_BOTTOM_FIELD);
3477 static int decode_slice(struct AVCodecContext *avctx, void *arg)
3479 H264Context *h = *(void **)arg;
3480 MpegEncContext *const s = &h->s;
3481 const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
3483 int lf_x_start = s->mb_x;
3485 s->mb_skip_run = -1;
3487 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
3488 s->codec_id != CODEC_ID_H264 ||
3489 (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
3493 align_get_bits(&s->gb);
3496 ff_init_cabac_states(&h->cabac);
3497 ff_init_cabac_decoder(&h->cabac,
3498 s->gb.buffer + get_bits_count(&s->gb) / 8,
3499 (get_bits_left(&s->gb) + 7) / 8);
3501 ff_h264_init_cabac_states(h);
3505 int ret = ff_h264_decode_mb_cabac(h);
3507 // STOP_TIMER("decode_mb_cabac")
3510 ff_h264_hl_decode_mb(h);
3512 // FIXME optimal? or let mb_decode decode 16x32 ?
3513 if (ret >= 0 && FRAME_MBAFF) {
3516 ret = ff_h264_decode_mb_cabac(h);
3519 ff_h264_hl_decode_mb(h);
3522 eos = get_cabac_terminate(&h->cabac);
3524 if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
3525 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3526 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3527 s->mb_y, ER_MB_END & part_mask);
3528 if (s->mb_x >= lf_x_start)
3529 loop_filter(h, lf_x_start, s->mb_x + 1);
3532 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
3533 av_log(h->s.avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
3534 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
3535 av_log(h->s.avctx, AV_LOG_ERROR,
3536 "error while decoding MB %d %d, bytestream (%td)\n",
3538 h->cabac.bytestream_end - h->cabac.bytestream);
3539 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3540 s->mb_y, ER_MB_ERROR & part_mask);
3544 if (++s->mb_x >= s->mb_width) {
3545 loop_filter(h, lf_x_start, s->mb_x);
3546 s->mb_x = lf_x_start = 0;
3547 decode_finish_row(h);
3549 if (FIELD_OR_MBAFF_PICTURE) {
3551 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3552 predict_field_decoding_flag(h);
3556 if (eos || s->mb_y >= s->mb_height) {
3557 tprintf(s->avctx, "slice end %d %d\n",
3558 get_bits_count(&s->gb), s->gb.size_in_bits);
3559 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3560 s->mb_y, ER_MB_END & part_mask);
3561 if (s->mb_x > lf_x_start)
3562 loop_filter(h, lf_x_start, s->mb_x);
3568 int ret = ff_h264_decode_mb_cavlc(h);
3571 ff_h264_hl_decode_mb(h);
3573 // FIXME optimal? or let mb_decode decode 16x32 ?
3574 if (ret >= 0 && FRAME_MBAFF) {
3576 ret = ff_h264_decode_mb_cavlc(h);
3579 ff_h264_hl_decode_mb(h);
3584 av_log(h->s.avctx, AV_LOG_ERROR,
3585 "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3586 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3587 s->mb_y, ER_MB_ERROR & part_mask);
3591 if (++s->mb_x >= s->mb_width) {
3592 loop_filter(h, lf_x_start, s->mb_x);
3593 s->mb_x = lf_x_start = 0;
3594 decode_finish_row(h);
3596 if (FIELD_OR_MBAFF_PICTURE) {
3598 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3599 predict_field_decoding_flag(h);
3601 if (s->mb_y >= s->mb_height) {
3602 tprintf(s->avctx, "slice end %d %d\n",
3603 get_bits_count(&s->gb), s->gb.size_in_bits);
3605 if ( get_bits_left(&s->gb) == 0
3606 || get_bits_left(&s->gb) > 0 && !(s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
3607 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3608 s->mb_x - 1, s->mb_y,
3609 ER_MB_END & part_mask);
3613 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3615 ER_MB_END & part_mask);
3622 if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
3623 tprintf(s->avctx, "slice end %d %d\n",
3624 get_bits_count(&s->gb), s->gb.size_in_bits);
3625 if (get_bits_left(&s->gb) == 0) {
3626 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3627 s->mb_x - 1, s->mb_y,
3628 ER_MB_END & part_mask);
3629 if (s->mb_x > lf_x_start)
3630 loop_filter(h, lf_x_start, s->mb_x);
3634 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3635 s->mb_y, ER_MB_ERROR & part_mask);
3645 * Call decode_slice() for each context.
3647 * @param h h264 master context
3648 * @param context_count number of contexts to execute
3650 static int execute_decode_slices(H264Context *h, int context_count)
3652 MpegEncContext *const s = &h->s;
3653 AVCodecContext *const avctx = s->avctx;
3657 if (s->avctx->hwaccel ||
3658 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3660 if (context_count == 1) {
3661 return decode_slice(avctx, &h);
3663 for (i = 1; i < context_count; i++) {
3664 hx = h->thread_context[i];
3665 hx->s.err_recognition = avctx->err_recognition;
3666 hx->s.error_count = 0;
3667 hx->x264_build = h->x264_build;
3670 avctx->execute(avctx, decode_slice, h->thread_context,
3671 NULL, context_count, sizeof(void *));
3673 /* pull back stuff from slices to master context */
3674 hx = h->thread_context[context_count - 1];
3675 s->mb_x = hx->s.mb_x;
3676 s->mb_y = hx->s.mb_y;
3677 s->dropable = hx->s.dropable;
3678 s->picture_structure = hx->s.picture_structure;
3679 for (i = 1; i < context_count; i++)
3680 h->s.error_count += h->thread_context[i]->s.error_count;
3686 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
3688 MpegEncContext *const s = &h->s;
3689 AVCodecContext *const avctx = s->avctx;
3690 H264Context *hx; ///< thread context
3694 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
3695 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
3698 h->nal_unit_type= 0;
3700 if(!s->slice_context_count)
3701 s->slice_context_count= 1;
3702 h->max_contexts = s->slice_context_count;
3703 if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3704 h->current_slice = 0;
3705 if (!s->first_field)
3706 s->current_picture_ptr = NULL;
3707 ff_h264_reset_sei(h);
3710 for (; pass <= 1; pass++) {
3713 next_avc = h->is_avc ? 0 : buf_size;
3723 if (buf_index >= next_avc) {
3724 if (buf_index >= buf_size - h->nal_length_size)
3727 for (i = 0; i < h->nal_length_size; i++)
3728 nalsize = (nalsize << 8) | buf[buf_index++];
3729 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
3730 av_log(h->s.avctx, AV_LOG_ERROR,
3731 "AVC: nal size %d\n", nalsize);
3734 next_avc = buf_index + nalsize;
3736 // start code prefix search
3737 for (; buf_index + 3 < next_avc; buf_index++)
3738 // This should always succeed in the first iteration.
3739 if (buf[buf_index] == 0 &&
3740 buf[buf_index + 1] == 0 &&
3741 buf[buf_index + 2] == 1)
3744 if (buf_index + 3 >= buf_size)
3748 if (buf_index >= next_avc)
3752 hx = h->thread_context[context_count];
3754 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
3755 &consumed, next_avc - buf_index);
3756 if (ptr == NULL || dst_length < 0) {
3760 i = buf_index + consumed;
3761 if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
3762 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
3763 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
3764 s->workaround_bugs |= FF_BUG_TRUNCATED;
3766 if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
3767 while(dst_length > 0 && ptr[dst_length - 1] == 0)
3769 bit_length = !dst_length ? 0
3771 decode_rbsp_trailing(h, ptr + dst_length - 1));
3773 if (s->avctx->debug & FF_DEBUG_STARTCODE)
3774 av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
3776 if (h->is_avc && (nalsize != consumed) && nalsize)
3777 av_log(h->s.avctx, AV_LOG_DEBUG,
3778 "AVC: Consumed only %d bytes instead of %d\n",
3781 buf_index += consumed;
3785 /* packets can sometimes contain multiple PPS/SPS,
3786 * e.g. two PAFF field pictures in one packet, or a demuxer
3787 * which splits NALs strangely if so, when frame threading we
3788 * can't start the next thread until we've read all of them */
3789 switch (hx->nal_unit_type) {
3792 nals_needed = nal_index;
3796 init_get_bits(&hx->s.gb, ptr, bit_length);
3797 if (!get_ue_golomb(&hx->s.gb))
3798 nals_needed = nal_index;
3803 // FIXME do not discard SEI id
3804 if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
3809 switch (hx->nal_unit_type) {
3811 if (h->nal_unit_type != NAL_IDR_SLICE) {
3812 av_log(h->s.avctx, AV_LOG_ERROR,
3813 "Invalid mix of idr and non-idr slices\n");
3817 idr(h); // FIXME ensure we don't lose some frames if there is reordering
3819 init_get_bits(&hx->s.gb, ptr, bit_length);
3821 hx->inter_gb_ptr = &hx->s.gb;
3822 hx->s.data_partitioning = 0;
3824 if ((err = decode_slice_header(hx, h)))
3827 if ( h->sei_recovery_frame_cnt >= 0
3828 && ( h->recovery_frame<0
3829 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
3830 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
3831 (1 << h->sps.log2_max_frame_num);
3834 s->current_picture_ptr->f.key_frame |=
3835 (hx->nal_unit_type == NAL_IDR_SLICE);
3837 if (h->recovery_frame == h->frame_num) {
3838 s->current_picture_ptr->sync |= 1;
3839 h->recovery_frame = -1;
3842 h->sync |= !!s->current_picture_ptr->f.key_frame;
3843 h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
3844 s->current_picture_ptr->sync |= h->sync;
3846 if (h->current_slice == 1) {
3847 if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
3848 decode_postinit(h, nal_index >= nals_needed);
3850 if (s->avctx->hwaccel &&
3851 s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3853 if (CONFIG_H264_VDPAU_DECODER &&
3854 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3855 ff_vdpau_h264_picture_start(s);
3858 if (hx->redundant_pic_count == 0 &&
3859 (avctx->skip_frame < AVDISCARD_NONREF ||
3861 (avctx->skip_frame < AVDISCARD_BIDIR ||
3862 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
3863 (avctx->skip_frame < AVDISCARD_NONKEY ||
3864 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
3865 avctx->skip_frame < AVDISCARD_ALL) {
3866 if (avctx->hwaccel) {
3867 if (avctx->hwaccel->decode_slice(avctx,
3868 &buf[buf_index - consumed],
3871 } else if (CONFIG_H264_VDPAU_DECODER &&
3872 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
3873 static const uint8_t start_code[] = {
3875 ff_vdpau_add_data_chunk(s, start_code,
3876 sizeof(start_code));
3877 ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
3884 init_get_bits(&hx->s.gb, ptr, bit_length);
3886 hx->inter_gb_ptr = NULL;
3888 if ((err = decode_slice_header(hx, h)) < 0)
3891 hx->s.data_partitioning = 1;
3894 init_get_bits(&hx->intra_gb, ptr, bit_length);
3895 hx->intra_gb_ptr = &hx->intra_gb;
3898 init_get_bits(&hx->inter_gb, ptr, bit_length);
3899 hx->inter_gb_ptr = &hx->inter_gb;
3901 av_log(h->s.avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
3902 return AVERROR_PATCHWELCOME;
3904 if (hx->redundant_pic_count == 0 &&
3906 hx->s.data_partitioning &&
3907 s->context_initialized &&
3908 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
3909 (avctx->skip_frame < AVDISCARD_BIDIR ||
3910 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
3911 (avctx->skip_frame < AVDISCARD_NONKEY ||
3912 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
3913 avctx->skip_frame < AVDISCARD_ALL)
3917 init_get_bits(&s->gb, ptr, bit_length);
3918 ff_h264_decode_sei(h);
3921 init_get_bits(&s->gb, ptr, bit_length);
3922 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
3923 av_log(h->s.avctx, AV_LOG_DEBUG,
3924 "SPS decoding failure, trying again with the complete NAL\n");
3926 av_assert0(next_avc - buf_index + consumed == nalsize);
3927 init_get_bits(&s->gb, &buf[buf_index + 1 - consumed],
3928 8*(next_avc - buf_index + consumed - 1));
3929 ff_h264_decode_seq_parameter_set(h);
3932 if (s->flags & CODEC_FLAG_LOW_DELAY ||
3933 (h->sps.bitstream_restriction_flag &&
3934 !h->sps.num_reorder_frames))
3936 if (avctx->has_b_frames < 2)
3937 avctx->has_b_frames = !s->low_delay;
3940 init_get_bits(&s->gb, ptr, bit_length);
3941 ff_h264_decode_picture_parameter_set(h, bit_length);
3944 case NAL_END_SEQUENCE:
3945 case NAL_END_STREAM:
3946 case NAL_FILLER_DATA:
3948 case NAL_AUXILIARY_SLICE:
3951 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
3952 hx->nal_unit_type, bit_length);
3955 if (context_count == h->max_contexts) {
3956 execute_decode_slices(h, context_count);
3961 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3962 else if (err == 1) {
3963 /* Slice could not be decoded in parallel mode, copy down
3964 * NAL unit stuff to context 0 and restart. Note that
3965 * rbsp_buffer is not transferred, but since we no longer
3966 * run in parallel mode this should not be an issue. */
3967 h->nal_unit_type = hx->nal_unit_type;
3968 h->nal_ref_idc = hx->nal_ref_idc;
3975 execute_decode_slices(h, context_count);
3979 if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
3981 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
3982 s->picture_structure == PICT_BOTTOM_FIELD);
3989 * Return the number of bytes consumed for building the current frame.
3991 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
3994 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
3995 if (pos + 10 > buf_size)
3996 pos = buf_size; // oops ;)
4001 static int decode_frame(AVCodecContext *avctx, void *data,
4002 int *data_size, AVPacket *avpkt)
4004 const uint8_t *buf = avpkt->data;
4005 int buf_size = avpkt->size;
4006 H264Context *h = avctx->priv_data;
4007 MpegEncContext *s = &h->s;
4008 AVFrame *pict = data;
4013 s->flags = avctx->flags;
4014 s->flags2 = avctx->flags2;
4016 /* end of stream, output what is still in the buffers */
4017 if (buf_size == 0) {
4020 s->current_picture_ptr = NULL;
4022 // FIXME factorize this with the output code below
4023 out = h->delayed_pic[0];
4026 h->delayed_pic[i] &&
4027 !h->delayed_pic[i]->f.key_frame &&
4028 !h->delayed_pic[i]->mmco_reset;
4030 if (h->delayed_pic[i]->poc < out->poc) {
4031 out = h->delayed_pic[i];
4035 for (i = out_idx; h->delayed_pic[i]; i++)
4036 h->delayed_pic[i] = h->delayed_pic[i + 1];
4039 *data_size = sizeof(AVFrame);
4045 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
4046 int cnt= buf[5]&0x1f;
4047 const uint8_t *p= buf+6;
4049 int nalsize= AV_RB16(p) + 2;
4050 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
4058 int nalsize= AV_RB16(p) + 2;
4059 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
4064 return ff_h264_decode_extradata(h, buf, buf_size);
4068 buf_index = decode_nal_units(h, buf, buf_size);
4072 if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4073 av_assert0(buf_index <= buf_size);
4077 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
4078 if (avctx->skip_frame >= AVDISCARD_NONREF ||
4079 buf_size >= 4 && !memcmp("Q264", buf, 4))
4081 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4085 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
4086 (s->mb_y >= s->mb_height && s->mb_height)) {
4087 if (s->flags2 & CODEC_FLAG2_CHUNKS)
4088 decode_postinit(h, 1);
4092 /* Wait for second field. */
4094 if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
4095 *data_size = sizeof(AVFrame);
4096 *pict = h->next_output_pic->f;
4100 assert(pict->data[0] || !*data_size);
4101 ff_print_debug_info(s, pict);
4102 // printf("out %d\n", (int)pict->data[0]);
4104 return get_consumed_bytes(s, buf_index, buf_size);
4107 av_cold void ff_h264_free_context(H264Context *h)
4111 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4113 for (i = 0; i < MAX_SPS_COUNT; i++)
4114 av_freep(h->sps_buffers + i);
4116 for (i = 0; i < MAX_PPS_COUNT; i++)
4117 av_freep(h->pps_buffers + i);
4120 static av_cold int h264_decode_end(AVCodecContext *avctx)
4122 H264Context *h = avctx->priv_data;
4123 MpegEncContext *s = &h->s;
4125 ff_h264_remove_all_refs(h);
4126 ff_h264_free_context(h);
4128 ff_MPV_common_end(s);
4130 // memset(h, 0, sizeof(H264Context));
4135 static const AVProfile profiles[] = {
4136 { FF_PROFILE_H264_BASELINE, "Baseline" },
4137 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4138 { FF_PROFILE_H264_MAIN, "Main" },
4139 { FF_PROFILE_H264_EXTENDED, "Extended" },
4140 { FF_PROFILE_H264_HIGH, "High" },
4141 { FF_PROFILE_H264_HIGH_10, "High 10" },
4142 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4143 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4144 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4145 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4146 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4147 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4148 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4149 { FF_PROFILE_UNKNOWN },
4152 static const AVOption h264_options[] = {
4153 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
4154 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 4, 0},
4158 static const AVClass h264_class = {
4160 av_default_item_name,
4162 LIBAVUTIL_VERSION_INT,
4165 static const AVClass h264_vdpau_class = {
4166 "H264 VDPAU Decoder",
4167 av_default_item_name,
4169 LIBAVUTIL_VERSION_INT,
4172 AVCodec ff_h264_decoder = {
4174 .type = AVMEDIA_TYPE_VIDEO,
4175 .id = CODEC_ID_H264,
4176 .priv_data_size = sizeof(H264Context),
4177 .init = ff_h264_decode_init,
4178 .close = h264_decode_end,
4179 .decode = decode_frame,
4180 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4181 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4182 CODEC_CAP_FRAME_THREADS,
4184 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4185 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4186 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4187 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4188 .priv_class = &h264_class,
4191 #if CONFIG_H264_VDPAU_DECODER
4192 AVCodec ff_h264_vdpau_decoder = {
4193 .name = "h264_vdpau",
4194 .type = AVMEDIA_TYPE_VIDEO,
4195 .id = CODEC_ID_H264,
4196 .priv_data_size = sizeof(H264Context),
4197 .init = ff_h264_decode_init,
4198 .close = h264_decode_end,
4199 .decode = decode_frame,
4200 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4202 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4203 .pix_fmts = (const enum PixelFormat[]) { PIX_FMT_VDPAU_H264,
4205 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4206 .priv_class = &h264_vdpau_class,