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,
57 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
61 static const uint8_t div6[QP_MAX_NUM + 1] = {
62 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
63 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
64 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
65 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
69 static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
77 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
79 H264Context *h = avctx->priv_data;
80 return h ? h->sps.num_reorder_frames : 0;
84 * Check if the top & left blocks are available if needed and
85 * change the dc mode so it only uses the available blocks.
87 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
89 MpegEncContext *const s = &h->s;
90 static const int8_t top[12] = {
91 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
93 static const int8_t left[12] = {
94 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
98 if (!(h->top_samples_available & 0x8000)) {
99 for (i = 0; i < 4; i++) {
100 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
102 av_log(h->s.avctx, AV_LOG_ERROR,
103 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
104 status, s->mb_x, s->mb_y);
107 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
112 if ((h->left_samples_available & 0x8888) != 0x8888) {
113 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
114 for (i = 0; i < 4; i++)
115 if (!(h->left_samples_available & mask[i])) {
116 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
118 av_log(h->s.avctx, AV_LOG_ERROR,
119 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
120 status, s->mb_x, s->mb_y);
123 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
129 } // FIXME cleanup like ff_h264_check_intra_pred_mode
132 * Check if the top & left blocks are available if needed and
133 * change the dc mode so it only uses the available blocks.
135 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
137 MpegEncContext *const s = &h->s;
138 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
139 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
142 av_log(h->s.avctx, AV_LOG_ERROR,
143 "out of range intra chroma pred mode at %d %d\n",
148 if (!(h->top_samples_available & 0x8000)) {
151 av_log(h->s.avctx, AV_LOG_ERROR,
152 "top block unavailable for requested intra mode at %d %d\n",
158 if ((h->left_samples_available & 0x8080) != 0x8080) {
160 if (is_chroma && (h->left_samples_available & 0x8080)) {
161 // mad cow disease mode, aka MBAFF + constrained_intra_pred
162 mode = ALZHEIMER_DC_L0T_PRED8x8 +
163 (!(h->left_samples_available & 0x8000)) +
164 2 * (mode == DC_128_PRED8x8);
167 av_log(h->s.avctx, AV_LOG_ERROR,
168 "left block unavailable for requested intra mode at %d %d\n",
177 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
178 int *dst_length, int *consumed, int length)
184 // src[0]&0x80; // forbidden bit
185 h->nal_ref_idc = src[0] >> 5;
186 h->nal_unit_type = src[0] & 0x1F;
191 #if HAVE_FAST_UNALIGNED
194 for (i = 0; i + 1 < length; i += 9) {
195 if (!((~AV_RN64A(src + i) &
196 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
197 0x8000800080008080ULL))
200 for (i = 0; i + 1 < length; i += 5) {
201 if (!((~AV_RN32A(src + i) &
202 (AV_RN32A(src + i) - 0x01000101U)) &
206 if (i > 0 && !src[i])
212 for (i = 0; i + 1 < length; i += 2) {
215 if (i > 0 && src[i - 1] == 0)
218 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {
219 if (src[i + 2] != 3) {
220 /* startcode, so we must be past the end */
228 // use second escape buffer for inter data
229 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
231 si = h->rbsp_buffer_size[bufidx];
232 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
233 dst = h->rbsp_buffer[bufidx];
238 if(i>=length-1){ //no escaped 0
240 *consumed= length+1; //+1 for the header
241 if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
244 memcpy(dst, src, length);
249 // printf("decoding esc\n");
252 while (si + 2 < length) {
253 // remove escapes (very rare 1:2^22)
254 if (src[si + 2] > 3) {
255 dst[di++] = src[si++];
256 dst[di++] = src[si++];
257 } else if (src[si] == 0 && src[si + 1] == 0) {
258 if (src[si + 2] == 3) { // escape
263 } else // next start code
267 dst[di++] = src[si++];
270 dst[di++] = src[si++];
273 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
276 *consumed = si + 1; // +1 for the header
277 /* FIXME store exact number of bits in the getbitcontext
278 * (it is needed for decoding) */
283 * Identify the exact end of the bitstream
284 * @return the length of the trailing, or 0 if damaged
286 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
291 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
293 for (r = 1; r < 9; r++) {
301 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
302 int height, int y_offset, int list)
304 int raw_my = h->mv_cache[list][scan8[n]][1];
305 int filter_height = (raw_my & 3) ? 2 : 0;
306 int full_my = (raw_my >> 2) + y_offset;
307 int top = full_my - filter_height;
308 int bottom = full_my + filter_height + height;
310 return FFMAX(abs(top), bottom);
313 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
314 int height, int y_offset, int list0,
315 int list1, int *nrefs)
317 MpegEncContext *const s = &h->s;
320 y_offset += 16 * (s->mb_y >> MB_FIELD);
323 int ref_n = h->ref_cache[0][scan8[n]];
324 Picture *ref = &h->ref_list[0][ref_n];
326 // Error resilience puts the current picture in the ref list.
327 // Don't try to wait on these as it will cause a deadlock.
328 // Fields can wait on each other, though.
329 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
330 (ref->f.reference & 3) != s->picture_structure) {
331 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
332 if (refs[0][ref_n] < 0)
334 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
339 int ref_n = h->ref_cache[1][scan8[n]];
340 Picture *ref = &h->ref_list[1][ref_n];
342 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
343 (ref->f.reference & 3) != s->picture_structure) {
344 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
345 if (refs[1][ref_n] < 0)
347 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
353 * Wait until all reference frames are available for MC operations.
355 * @param h the H264 context
357 static void await_references(H264Context *h)
359 MpegEncContext *const s = &h->s;
360 const int mb_xy = h->mb_xy;
361 const int mb_type = s->current_picture.f.mb_type[mb_xy];
363 int nrefs[2] = { 0 };
366 memset(refs, -1, sizeof(refs));
368 if (IS_16X16(mb_type)) {
369 get_lowest_part_y(h, refs, 0, 16, 0,
370 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
371 } else if (IS_16X8(mb_type)) {
372 get_lowest_part_y(h, refs, 0, 8, 0,
373 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
374 get_lowest_part_y(h, refs, 8, 8, 8,
375 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
376 } else if (IS_8X16(mb_type)) {
377 get_lowest_part_y(h, refs, 0, 16, 0,
378 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
379 get_lowest_part_y(h, refs, 4, 16, 0,
380 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
384 assert(IS_8X8(mb_type));
386 for (i = 0; i < 4; i++) {
387 const int sub_mb_type = h->sub_mb_type[i];
389 int y_offset = (i & 2) << 2;
391 if (IS_SUB_8X8(sub_mb_type)) {
392 get_lowest_part_y(h, refs, n, 8, y_offset,
393 IS_DIR(sub_mb_type, 0, 0),
394 IS_DIR(sub_mb_type, 0, 1),
396 } else if (IS_SUB_8X4(sub_mb_type)) {
397 get_lowest_part_y(h, refs, n, 4, y_offset,
398 IS_DIR(sub_mb_type, 0, 0),
399 IS_DIR(sub_mb_type, 0, 1),
401 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
402 IS_DIR(sub_mb_type, 0, 0),
403 IS_DIR(sub_mb_type, 0, 1),
405 } else if (IS_SUB_4X8(sub_mb_type)) {
406 get_lowest_part_y(h, refs, n, 8, y_offset,
407 IS_DIR(sub_mb_type, 0, 0),
408 IS_DIR(sub_mb_type, 0, 1),
410 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
411 IS_DIR(sub_mb_type, 0, 0),
412 IS_DIR(sub_mb_type, 0, 1),
416 assert(IS_SUB_4X4(sub_mb_type));
417 for (j = 0; j < 4; j++) {
418 int sub_y_offset = y_offset + 2 * (j & 2);
419 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
420 IS_DIR(sub_mb_type, 0, 0),
421 IS_DIR(sub_mb_type, 0, 1),
428 for (list = h->list_count - 1; list >= 0; list--)
429 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
430 int row = refs[list][ref];
432 Picture *ref_pic = &h->ref_list[list][ref];
433 int ref_field = ref_pic->f.reference - 1;
434 int ref_field_picture = ref_pic->field_picture;
435 int pic_height = 16 * s->mb_height >> ref_field_picture;
440 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
441 ff_thread_await_progress(&ref_pic->f,
442 FFMIN((row >> 1) - !(row & 1),
445 ff_thread_await_progress(&ref_pic->f,
446 FFMIN((row >> 1), pic_height - 1),
448 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
449 ff_thread_await_progress(&ref_pic->f,
450 FFMIN(row * 2 + ref_field,
453 } else if (FIELD_PICTURE) {
454 ff_thread_await_progress(&ref_pic->f,
455 FFMIN(row, pic_height - 1),
458 ff_thread_await_progress(&ref_pic->f,
459 FFMIN(row, pic_height - 1),
466 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
467 int n, int square, int height,
469 uint8_t *dest_y, uint8_t *dest_cb,
471 int src_x_offset, int src_y_offset,
472 qpel_mc_func *qpix_op,
473 h264_chroma_mc_func chroma_op,
474 int pixel_shift, int chroma_idc)
476 MpegEncContext *const s = &h->s;
477 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
478 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
479 const int luma_xy = (mx & 3) + ((my & 3) << 2);
480 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
481 uint8_t *src_y = pic->f.data[0] + offset;
482 uint8_t *src_cb, *src_cr;
483 int extra_width = h->emu_edge_width;
484 int extra_height = h->emu_edge_height;
486 const int full_mx = mx >> 2;
487 const int full_my = my >> 2;
488 const int pic_width = 16 * s->mb_width;
489 const int pic_height = 16 * s->mb_height >> MB_FIELD;
497 if (full_mx < 0 - extra_width ||
498 full_my < 0 - extra_height ||
499 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
500 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
501 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
502 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
504 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
505 full_my - 2, pic_width, pic_height);
506 src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
510 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
512 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
514 if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
517 if (chroma_idc == 3 /* yuv444 */) {
518 src_cb = pic->f.data[1] + offset;
520 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
521 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
523 16 + 5, 16 + 5 /*FIXME*/,
524 full_mx - 2, full_my - 2,
525 pic_width, pic_height);
526 src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
528 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
530 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
532 src_cr = pic->f.data[2] + offset;
534 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
535 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
537 16 + 5, 16 + 5 /*FIXME*/,
538 full_mx - 2, full_my - 2,
539 pic_width, pic_height);
540 src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
542 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
544 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
548 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
549 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
550 // chroma offset when predicting from a field of opposite parity
551 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
552 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
555 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
556 (my >> ysh) * h->mb_uvlinesize;
557 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
558 (my >> ysh) * h->mb_uvlinesize;
561 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
562 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
563 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
564 src_cb = s->edge_emu_buffer;
566 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
567 height >> (chroma_idc == 1 /* yuv420 */),
568 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
571 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
572 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
573 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
574 src_cr = s->edge_emu_buffer;
576 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
577 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
580 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
581 int height, int delta,
582 uint8_t *dest_y, uint8_t *dest_cb,
584 int x_offset, int y_offset,
585 qpel_mc_func *qpix_put,
586 h264_chroma_mc_func chroma_put,
587 qpel_mc_func *qpix_avg,
588 h264_chroma_mc_func chroma_avg,
589 int list0, int list1,
590 int pixel_shift, int chroma_idc)
592 MpegEncContext *const s = &h->s;
593 qpel_mc_func *qpix_op = qpix_put;
594 h264_chroma_mc_func chroma_op = chroma_put;
596 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
597 if (chroma_idc == 3 /* yuv444 */) {
598 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
599 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
600 } else if (chroma_idc == 2 /* yuv422 */) {
601 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
602 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
603 } else { /* yuv420 */
604 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
605 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
607 x_offset += 8 * s->mb_x;
608 y_offset += 8 * (s->mb_y >> MB_FIELD);
611 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
612 mc_dir_part(h, ref, n, square, height, delta, 0,
613 dest_y, dest_cb, dest_cr, x_offset, y_offset,
614 qpix_op, chroma_op, pixel_shift, chroma_idc);
617 chroma_op = chroma_avg;
621 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
622 mc_dir_part(h, ref, n, square, height, delta, 1,
623 dest_y, dest_cb, dest_cr, x_offset, y_offset,
624 qpix_op, chroma_op, pixel_shift, chroma_idc);
628 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
629 int height, int delta,
630 uint8_t *dest_y, uint8_t *dest_cb,
632 int x_offset, int y_offset,
633 qpel_mc_func *qpix_put,
634 h264_chroma_mc_func chroma_put,
635 h264_weight_func luma_weight_op,
636 h264_weight_func chroma_weight_op,
637 h264_biweight_func luma_weight_avg,
638 h264_biweight_func chroma_weight_avg,
639 int list0, int list1,
640 int pixel_shift, int chroma_idc)
642 MpegEncContext *const s = &h->s;
645 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
646 if (chroma_idc == 3 /* yuv444 */) {
647 chroma_height = height;
648 chroma_weight_avg = luma_weight_avg;
649 chroma_weight_op = luma_weight_op;
650 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
651 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
652 } else if (chroma_idc == 2 /* yuv422 */) {
653 chroma_height = height;
654 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
655 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
656 } else { /* yuv420 */
657 chroma_height = height >> 1;
658 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
659 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
661 x_offset += 8 * s->mb_x;
662 y_offset += 8 * (s->mb_y >> MB_FIELD);
664 if (list0 && list1) {
665 /* don't optimize for luma-only case, since B-frames usually
666 * use implicit weights => chroma too. */
667 uint8_t *tmp_cb = s->obmc_scratchpad;
668 uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
669 uint8_t *tmp_y = s->obmc_scratchpad + 16 * h->mb_uvlinesize;
670 int refn0 = h->ref_cache[0][scan8[n]];
671 int refn1 = h->ref_cache[1][scan8[n]];
673 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
674 dest_y, dest_cb, dest_cr,
675 x_offset, y_offset, qpix_put, chroma_put,
676 pixel_shift, chroma_idc);
677 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
678 tmp_y, tmp_cb, tmp_cr,
679 x_offset, y_offset, qpix_put, chroma_put,
680 pixel_shift, chroma_idc);
682 if (h->use_weight == 2) {
683 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
684 int weight1 = 64 - weight0;
685 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
686 height, 5, weight0, weight1, 0);
687 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
688 chroma_height, 5, weight0, weight1, 0);
689 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
690 chroma_height, 5, weight0, weight1, 0);
692 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
693 h->luma_log2_weight_denom,
694 h->luma_weight[refn0][0][0],
695 h->luma_weight[refn1][1][0],
696 h->luma_weight[refn0][0][1] +
697 h->luma_weight[refn1][1][1]);
698 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
699 h->chroma_log2_weight_denom,
700 h->chroma_weight[refn0][0][0][0],
701 h->chroma_weight[refn1][1][0][0],
702 h->chroma_weight[refn0][0][0][1] +
703 h->chroma_weight[refn1][1][0][1]);
704 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
705 h->chroma_log2_weight_denom,
706 h->chroma_weight[refn0][0][1][0],
707 h->chroma_weight[refn1][1][1][0],
708 h->chroma_weight[refn0][0][1][1] +
709 h->chroma_weight[refn1][1][1][1]);
712 int list = list1 ? 1 : 0;
713 int refn = h->ref_cache[list][scan8[n]];
714 Picture *ref = &h->ref_list[list][refn];
715 mc_dir_part(h, ref, n, square, height, delta, list,
716 dest_y, dest_cb, dest_cr, x_offset, y_offset,
717 qpix_put, chroma_put, pixel_shift, chroma_idc);
719 luma_weight_op(dest_y, h->mb_linesize, height,
720 h->luma_log2_weight_denom,
721 h->luma_weight[refn][list][0],
722 h->luma_weight[refn][list][1]);
723 if (h->use_weight_chroma) {
724 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
725 h->chroma_log2_weight_denom,
726 h->chroma_weight[refn][list][0][0],
727 h->chroma_weight[refn][list][0][1]);
728 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
729 h->chroma_log2_weight_denom,
730 h->chroma_weight[refn][list][1][0],
731 h->chroma_weight[refn][list][1][1]);
736 static av_always_inline void prefetch_motion(H264Context *h, int list,
737 int pixel_shift, int chroma_idc)
739 /* fetch pixels for estimated mv 4 macroblocks ahead
740 * optimized for 64byte cache lines */
741 MpegEncContext *const s = &h->s;
742 const int refn = h->ref_cache[list][scan8[0]];
744 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
745 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
746 uint8_t **src = h->ref_list[list][refn].f.data;
747 int off = (mx << pixel_shift) +
748 (my + (s->mb_x & 3) * 4) * h->mb_linesize +
750 s->dsp.prefetch(src[0] + off, s->linesize, 4);
751 if (chroma_idc == 3 /* yuv444 */) {
752 s->dsp.prefetch(src[1] + off, s->linesize, 4);
753 s->dsp.prefetch(src[2] + off, s->linesize, 4);
755 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
756 s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
761 static void free_tables(H264Context *h, int free_rbsp)
766 av_freep(&h->intra4x4_pred_mode);
767 av_freep(&h->chroma_pred_mode_table);
768 av_freep(&h->cbp_table);
769 av_freep(&h->mvd_table[0]);
770 av_freep(&h->mvd_table[1]);
771 av_freep(&h->direct_table);
772 av_freep(&h->non_zero_count);
773 av_freep(&h->slice_table_base);
774 h->slice_table = NULL;
775 av_freep(&h->list_counts);
777 av_freep(&h->mb2b_xy);
778 av_freep(&h->mb2br_xy);
780 for (i = 0; i < MAX_THREADS; i++) {
781 hx = h->thread_context[i];
784 av_freep(&hx->top_borders[1]);
785 av_freep(&hx->top_borders[0]);
786 av_freep(&hx->s.obmc_scratchpad);
788 av_freep(&hx->rbsp_buffer[1]);
789 av_freep(&hx->rbsp_buffer[0]);
790 hx->rbsp_buffer_size[0] = 0;
791 hx->rbsp_buffer_size[1] = 0;
794 av_freep(&h->thread_context[i]);
798 static void init_dequant8_coeff_table(H264Context *h)
801 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
803 for (i = 0; i < 6; i++) {
804 h->dequant8_coeff[i] = h->dequant8_buffer[i];
805 for (j = 0; j < i; j++)
806 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
807 64 * sizeof(uint8_t))) {
808 h->dequant8_coeff[i] = h->dequant8_buffer[j];
814 for (q = 0; q < max_qp + 1; q++) {
817 for (x = 0; x < 64; x++)
818 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
819 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
820 h->pps.scaling_matrix8[i][x]) << shift;
825 static void init_dequant4_coeff_table(H264Context *h)
828 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
829 for (i = 0; i < 6; i++) {
830 h->dequant4_coeff[i] = h->dequant4_buffer[i];
831 for (j = 0; j < i; j++)
832 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
833 16 * sizeof(uint8_t))) {
834 h->dequant4_coeff[i] = h->dequant4_buffer[j];
840 for (q = 0; q < max_qp + 1; q++) {
841 int shift = div6[q] + 2;
843 for (x = 0; x < 16; x++)
844 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
845 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
846 h->pps.scaling_matrix4[i][x]) << shift;
851 static void init_dequant_tables(H264Context *h)
854 init_dequant4_coeff_table(h);
855 if (h->pps.transform_8x8_mode)
856 init_dequant8_coeff_table(h);
857 if (h->sps.transform_bypass) {
858 for (i = 0; i < 6; i++)
859 for (x = 0; x < 16; x++)
860 h->dequant4_coeff[i][0][x] = 1 << 6;
861 if (h->pps.transform_8x8_mode)
862 for (i = 0; i < 6; i++)
863 for (x = 0; x < 64; x++)
864 h->dequant8_coeff[i][0][x] = 1 << 6;
868 int ff_h264_alloc_tables(H264Context *h)
870 MpegEncContext *const s = &h->s;
871 const int big_mb_num = s->mb_stride * (s->mb_height + 1);
872 const int row_mb_num = 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
875 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
876 row_mb_num * 8 * sizeof(uint8_t), fail)
877 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
878 big_mb_num * 48 * sizeof(uint8_t), fail)
879 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
880 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
881 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
882 big_mb_num * sizeof(uint16_t), fail)
883 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
884 big_mb_num * sizeof(uint8_t), fail)
885 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
886 16 * row_mb_num * sizeof(uint8_t), fail);
887 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
888 16 * row_mb_num * sizeof(uint8_t), fail);
889 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
890 4 * big_mb_num * sizeof(uint8_t), fail);
891 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
892 big_mb_num * sizeof(uint8_t), fail)
894 memset(h->slice_table_base, -1,
895 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
896 h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
898 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
899 big_mb_num * sizeof(uint32_t), fail);
900 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
901 big_mb_num * sizeof(uint32_t), fail);
902 for (y = 0; y < s->mb_height; y++)
903 for (x = 0; x < s->mb_width; x++) {
904 const int mb_xy = x + y * s->mb_stride;
905 const int b_xy = 4 * x + 4 * y * h->b_stride;
907 h->mb2b_xy[mb_xy] = b_xy;
908 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
911 s->obmc_scratchpad = NULL;
913 if (!h->dequant4_coeff[0])
914 init_dequant_tables(h);
924 * Mimic alloc_tables(), but for every context thread.
926 static void clone_tables(H264Context *dst, H264Context *src, int i)
928 MpegEncContext *const s = &src->s;
929 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
930 dst->non_zero_count = src->non_zero_count;
931 dst->slice_table = src->slice_table;
932 dst->cbp_table = src->cbp_table;
933 dst->mb2b_xy = src->mb2b_xy;
934 dst->mb2br_xy = src->mb2br_xy;
935 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
936 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
937 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
938 dst->direct_table = src->direct_table;
939 dst->list_counts = src->list_counts;
940 dst->s.obmc_scratchpad = NULL;
941 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
942 src->sps.chroma_format_idc);
947 * Allocate buffers which are not shared amongst multiple threads.
949 static int context_init(H264Context *h)
951 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
952 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
953 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
954 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
956 h->ref_cache[0][scan8[5] + 1] =
957 h->ref_cache[0][scan8[7] + 1] =
958 h->ref_cache[0][scan8[13] + 1] =
959 h->ref_cache[1][scan8[5] + 1] =
960 h->ref_cache[1][scan8[7] + 1] =
961 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
966 return -1; // free_tables will clean up for us
969 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
971 static av_cold void common_init(H264Context *h)
973 MpegEncContext *const s = &h->s;
975 s->width = s->avctx->width;
976 s->height = s->avctx->height;
977 s->codec_id = s->avctx->codec->id;
979 s->avctx->bits_per_raw_sample = 8;
980 h->cur_chroma_format_idc = 1;
982 ff_h264dsp_init(&h->h264dsp,
983 s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
984 ff_h264_pred_init(&h->hpc, s->codec_id,
985 s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
987 h->dequant_coeff_pps = -1;
988 s->unrestricted_mv = 1;
990 s->dsp.dct_bits = 16;
991 /* needed so that IDCT permutation is known early */
992 ff_dsputil_init(&s->dsp, s->avctx);
994 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
995 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
998 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1000 AVCodecContext *avctx = h->s.avctx;
1002 if (!buf || size <= 0)
1006 int i, cnt, nalsize;
1007 const unsigned char *p = buf;
1012 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1015 /* sps and pps in the avcC always have length coded with 2 bytes,
1016 * so put a fake nal_length_size = 2 while parsing them */
1017 h->nal_length_size = 2;
1018 // Decode sps from avcC
1019 cnt = *(p + 5) & 0x1f; // Number of sps
1021 for (i = 0; i < cnt; i++) {
1022 nalsize = AV_RB16(p) + 2;
1023 if(nalsize > size - (p-buf))
1025 if (decode_nal_units(h, p, nalsize) < 0) {
1026 av_log(avctx, AV_LOG_ERROR,
1027 "Decoding sps %d from avcC failed\n", i);
1032 // Decode pps from avcC
1033 cnt = *(p++); // Number of pps
1034 for (i = 0; i < cnt; i++) {
1035 nalsize = AV_RB16(p) + 2;
1036 if(nalsize > size - (p-buf))
1038 if (decode_nal_units(h, p, nalsize) < 0) {
1039 av_log(avctx, AV_LOG_ERROR,
1040 "Decoding pps %d from avcC failed\n", i);
1045 // Now store right nal length size, that will be used to parse all other nals
1046 h->nal_length_size = (buf[4] & 0x03) + 1;
1049 if (decode_nal_units(h, buf, size) < 0)
1055 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1057 H264Context *h = avctx->priv_data;
1058 MpegEncContext *const s = &h->s;
1061 ff_MPV_decode_defaults(s);
1066 s->out_format = FMT_H264;
1067 s->workaround_bugs = avctx->workaround_bugs;
1070 // s->decode_mb = ff_h263_decode_mb;
1071 s->quarter_sample = 1;
1072 if (!avctx->has_b_frames)
1075 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1077 ff_h264_decode_init_vlc();
1080 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1082 h->thread_context[0] = h;
1083 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1084 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1085 h->last_pocs[i] = INT_MIN;
1086 h->prev_poc_msb = 1 << 16;
1087 h->prev_frame_num = -1;
1089 ff_h264_reset_sei(h);
1090 if (avctx->codec_id == CODEC_ID_H264) {
1091 if (avctx->ticks_per_frame == 1)
1092 s->avctx->time_base.den *= 2;
1093 avctx->ticks_per_frame = 2;
1096 if (avctx->extradata_size > 0 && avctx->extradata &&
1097 ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
1098 ff_h264_free_context(h);
1102 if (h->sps.bitstream_restriction_flag &&
1103 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1104 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1111 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1113 static void copy_picture_range(Picture **to, Picture **from, int count,
1114 MpegEncContext *new_base,
1115 MpegEncContext *old_base)
1119 for (i = 0; i < count; i++) {
1120 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1121 IN_RANGE(from[i], old_base->picture,
1122 sizeof(Picture) * old_base->picture_count) ||
1124 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1128 static void copy_parameter_set(void **to, void **from, int count, int size)
1132 for (i = 0; i < count; i++) {
1133 if (to[i] && !from[i])
1135 else if (from[i] && !to[i])
1136 to[i] = av_malloc(size);
1139 memcpy(to[i], from[i], size);
1143 static int decode_init_thread_copy(AVCodecContext *avctx)
1145 H264Context *h = avctx->priv_data;
1147 if (!avctx->internal->is_copy)
1149 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1150 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1155 #define copy_fields(to, from, start_field, end_field) \
1156 memcpy(&to->start_field, &from->start_field, \
1157 (char *)&to->end_field - (char *)&to->start_field)
1159 static int decode_update_thread_context(AVCodecContext *dst,
1160 const AVCodecContext *src)
1162 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1163 MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1164 int inited = s->context_initialized, err;
1170 err = ff_mpeg_update_thread_context(dst, src);
1174 // FIXME handle width/height changing
1176 for (i = 0; i < MAX_SPS_COUNT; i++)
1177 av_freep(h->sps_buffers + i);
1179 for (i = 0; i < MAX_PPS_COUNT; i++)
1180 av_freep(h->pps_buffers + i);
1182 // copy all fields after MpegEnc
1183 memcpy(&h->s + 1, &h1->s + 1,
1184 sizeof(H264Context) - sizeof(MpegEncContext));
1185 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1186 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1188 if (s1->context_initialized) {
1189 if (ff_h264_alloc_tables(h) < 0) {
1190 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1191 return AVERROR(ENOMEM);
1195 /* frame_start may not be called for the next thread (if it's decoding
1196 * a bottom field) so this has to be allocated here */
1197 h->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1200 for (i = 0; i < 2; i++) {
1201 h->rbsp_buffer[i] = NULL;
1202 h->rbsp_buffer_size[i] = 0;
1205 h->thread_context[0] = h;
1207 s->dsp.clear_blocks(h->mb);
1208 s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1211 // extradata/NAL handling
1212 h->is_avc = h1->is_avc;
1215 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1216 MAX_SPS_COUNT, sizeof(SPS));
1218 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1219 MAX_PPS_COUNT, sizeof(PPS));
1222 // Dequantization matrices
1223 // FIXME these are big - can they be only copied when PPS changes?
1224 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1226 for (i = 0; i < 6; i++)
1227 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1228 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1230 for (i = 0; i < 6; i++)
1231 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1232 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1234 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1237 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1240 copy_fields(h, h1, ref_count, list_count);
1241 copy_fields(h, h1, ref_list, intra_gb);
1242 copy_fields(h, h1, short_ref, cabac_init_idc);
1244 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1245 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1246 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1247 MAX_DELAYED_PIC_COUNT + 2, s, s1);
1249 h->last_slice_type = h1->last_slice_type;
1252 if (!s->current_picture_ptr)
1256 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1257 h->prev_poc_msb = h->poc_msb;
1258 h->prev_poc_lsb = h->poc_lsb;
1260 h->prev_frame_num_offset = h->frame_num_offset;
1261 h->prev_frame_num = h->frame_num;
1262 h->outputed_poc = h->next_outputed_poc;
1267 int ff_h264_frame_start(H264Context *h)
1269 MpegEncContext *const s = &h->s;
1271 const int pixel_shift = h->pixel_shift;
1273 if (ff_MPV_frame_start(s, s->avctx) < 0)
1275 ff_er_frame_start(s);
1277 * ff_MPV_frame_start uses pict_type to derive key_frame.
1278 * This is incorrect for H.264; IDR markings must be used.
1279 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1280 * See decode_nal_units().
1282 s->current_picture_ptr->f.key_frame = 0;
1283 s->current_picture_ptr->sync = 0;
1284 s->current_picture_ptr->mmco_reset = 0;
1286 assert(s->linesize && s->uvlinesize);
1288 for (i = 0; i < 16; i++) {
1289 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1290 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1292 for (i = 0; i < 16; i++) {
1293 h->block_offset[16 + i] =
1294 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1295 h->block_offset[48 + 16 + i] =
1296 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1299 /* can't be in alloc_tables because linesize isn't known there.
1300 * FIXME: redo bipred weight to not require extra buffer? */
1301 for (i = 0; i < s->slice_context_count; i++)
1302 if (h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1303 h->thread_context[i]->s.obmc_scratchpad = av_malloc(16 * 6 * s->linesize);
1305 /* Some macroblocks can be accessed before they're available in case
1306 * of lost slices, MBAFF or threading. */
1307 memset(h->slice_table, -1,
1308 (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1310 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1311 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1313 /* We mark the current picture as non-reference after allocating it, so
1314 * that if we break out due to an error it can be released automatically
1315 * in the next ff_MPV_frame_start().
1316 * SVQ3 as well as most other codecs have only last/next/current and thus
1317 * get released even with set reference, besides SVQ3 and others do not
1318 * mark frames as reference later "naturally". */
1319 if (s->codec_id != CODEC_ID_SVQ3)
1320 s->current_picture_ptr->f.reference = 0;
1322 s->current_picture_ptr->field_poc[0] =
1323 s->current_picture_ptr->field_poc[1] = INT_MAX;
1325 h->next_output_pic = NULL;
1327 assert(s->current_picture_ptr->long_ref == 0);
1333 * Run setup operations that must be run after slice header decoding.
1334 * This includes finding the next displayed frame.
1336 * @param h h264 master context
1337 * @param setup_finished enough NALs have been read that we can call
1338 * ff_thread_finish_setup()
1340 static void decode_postinit(H264Context *h, int setup_finished)
1342 MpegEncContext *const s = &h->s;
1343 Picture *out = s->current_picture_ptr;
1344 Picture *cur = s->current_picture_ptr;
1345 int i, pics, out_of_order, out_idx;
1347 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1348 s->current_picture_ptr->f.pict_type = s->pict_type;
1350 if (h->next_output_pic)
1353 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1354 /* FIXME: if we have two PAFF fields in one packet, we can't start
1355 * the next thread here. If we have one field per packet, we can.
1356 * The check in decode_nal_units() is not good enough to find this
1357 * yet, so we assume the worst for now. */
1358 // if (setup_finished)
1359 // ff_thread_finish_setup(s->avctx);
1363 cur->f.interlaced_frame = 0;
1364 cur->f.repeat_pict = 0;
1366 /* Signal interlacing information externally. */
1367 /* Prioritize picture timing SEI information over used
1368 * decoding process if it exists. */
1370 if (h->sps.pic_struct_present_flag) {
1371 switch (h->sei_pic_struct) {
1372 case SEI_PIC_STRUCT_FRAME:
1374 case SEI_PIC_STRUCT_TOP_FIELD:
1375 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1376 cur->f.interlaced_frame = 1;
1378 case SEI_PIC_STRUCT_TOP_BOTTOM:
1379 case SEI_PIC_STRUCT_BOTTOM_TOP:
1380 if (FIELD_OR_MBAFF_PICTURE)
1381 cur->f.interlaced_frame = 1;
1383 // try to flag soft telecine progressive
1384 cur->f.interlaced_frame = h->prev_interlaced_frame;
1386 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1387 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1388 /* Signal the possibility of telecined film externally
1389 * (pic_struct 5,6). From these hints, let the applications
1390 * decide if they apply deinterlacing. */
1391 cur->f.repeat_pict = 1;
1393 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1394 // Force progressive here, doubling interlaced frame is a bad idea.
1395 cur->f.repeat_pict = 2;
1397 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1398 cur->f.repeat_pict = 4;
1402 if ((h->sei_ct_type & 3) &&
1403 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1404 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1406 /* Derive interlacing flag from used decoding process. */
1407 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1409 h->prev_interlaced_frame = cur->f.interlaced_frame;
1411 if (cur->field_poc[0] != cur->field_poc[1]) {
1412 /* Derive top_field_first from field pocs. */
1413 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1415 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1416 /* Use picture timing SEI information. Even if it is a
1417 * information of a past frame, better than nothing. */
1418 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1419 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1420 cur->f.top_field_first = 1;
1422 cur->f.top_field_first = 0;
1424 /* Most likely progressive */
1425 cur->f.top_field_first = 0;
1429 cur->mmco_reset = h->mmco_reset;
1431 // FIXME do something with unavailable reference frames
1433 /* Sort B-frames into display order */
1435 if (h->sps.bitstream_restriction_flag &&
1436 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1437 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1441 if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1442 !h->sps.bitstream_restriction_flag) {
1443 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1447 for (i = 0; 1; i++) {
1448 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1450 h->last_pocs[i-1] = cur->poc;
1453 h->last_pocs[i-1]= h->last_pocs[i];
1456 out_of_order = MAX_DELAYED_PIC_COUNT - i;
1457 if( cur->f.pict_type == AV_PICTURE_TYPE_B
1458 || (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))
1459 out_of_order = FFMAX(out_of_order, 1);
1460 if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1461 av_log(s->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
1462 s->avctx->has_b_frames = out_of_order;
1467 while (h->delayed_pic[pics])
1470 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1472 h->delayed_pic[pics++] = cur;
1473 if (cur->f.reference == 0)
1474 cur->f.reference = DELAYED_PIC_REF;
1476 out = h->delayed_pic[0];
1478 for (i = 1; h->delayed_pic[i] &&
1479 !h->delayed_pic[i]->f.key_frame &&
1480 !h->delayed_pic[i]->mmco_reset;
1482 if (h->delayed_pic[i]->poc < out->poc) {
1483 out = h->delayed_pic[i];
1486 if (s->avctx->has_b_frames == 0 &&
1487 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1488 h->next_outputed_poc = INT_MIN;
1489 out_of_order = out->poc < h->next_outputed_poc;
1491 if (out_of_order || pics > s->avctx->has_b_frames) {
1492 out->f.reference &= ~DELAYED_PIC_REF;
1493 // for frame threading, the owner must be the second field's thread or
1494 // else the first thread can release the picture and reuse it unsafely
1496 for (i = out_idx; h->delayed_pic[i]; i++)
1497 h->delayed_pic[i] = h->delayed_pic[i + 1];
1499 if (!out_of_order && pics > s->avctx->has_b_frames) {
1500 h->next_output_pic = out;
1501 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1502 h->next_outputed_poc = INT_MIN;
1504 h->next_outputed_poc = out->poc;
1506 av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1509 if (h->next_output_pic && h->next_output_pic->sync) {
1514 ff_thread_finish_setup(s->avctx);
1517 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1518 uint8_t *src_cb, uint8_t *src_cr,
1519 int linesize, int uvlinesize,
1522 MpegEncContext *const s = &h->s;
1523 uint8_t *top_border;
1525 const int pixel_shift = h->pixel_shift;
1526 int chroma444 = CHROMA444;
1527 int chroma422 = CHROMA422;
1530 src_cb -= uvlinesize;
1531 src_cr -= uvlinesize;
1533 if (!simple && FRAME_MBAFF) {
1536 top_border = h->top_borders[0][s->mb_x];
1537 AV_COPY128(top_border, src_y + 15 * linesize);
1539 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1540 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1543 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1544 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1545 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1546 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1548 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1549 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1551 } else if (chroma422) {
1553 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1554 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1556 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1557 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1561 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1562 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1564 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1565 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1570 } else if (MB_MBAFF) {
1576 top_border = h->top_borders[top_idx][s->mb_x];
1577 /* There are two lines saved, the line above the top macroblock
1578 * of a pair, and the line above the bottom macroblock. */
1579 AV_COPY128(top_border, src_y + 16 * linesize);
1581 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1583 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1586 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1587 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1588 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1589 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1591 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1592 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1594 } else if (chroma422) {
1596 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1597 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1599 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1600 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1604 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1605 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1607 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1608 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1614 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1615 uint8_t *src_cb, uint8_t *src_cr,
1616 int linesize, int uvlinesize,
1617 int xchg, int chroma444,
1618 int simple, int pixel_shift)
1620 MpegEncContext *const s = &h->s;
1621 int deblock_topleft;
1624 uint8_t *top_border_m1;
1625 uint8_t *top_border;
1627 if (!simple && FRAME_MBAFF) {
1632 top_idx = MB_MBAFF ? 0 : 1;
1636 if (h->deblocking_filter == 2) {
1637 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1638 deblock_top = h->top_type;
1640 deblock_topleft = (s->mb_x > 0);
1641 deblock_top = (s->mb_y > !!MB_FIELD);
1644 src_y -= linesize + 1 + pixel_shift;
1645 src_cb -= uvlinesize + 1 + pixel_shift;
1646 src_cr -= uvlinesize + 1 + pixel_shift;
1648 top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1649 top_border = h->top_borders[top_idx][s->mb_x];
1651 #define XCHG(a, b, xchg) \
1652 if (pixel_shift) { \
1654 AV_SWAP64(b + 0, a + 0); \
1655 AV_SWAP64(b + 8, a + 8); \
1665 if (deblock_topleft) {
1666 XCHG(top_border_m1 + (8 << pixel_shift),
1667 src_y - (7 << pixel_shift), 1);
1669 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1670 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1671 if (s->mb_x + 1 < s->mb_width) {
1672 XCHG(h->top_borders[top_idx][s->mb_x + 1],
1673 src_y + (17 << pixel_shift), 1);
1676 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1678 if (deblock_topleft) {
1679 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1680 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1682 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1683 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1684 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1685 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1686 if (s->mb_x + 1 < s->mb_width) {
1687 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1688 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1692 if (deblock_topleft) {
1693 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1694 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1696 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1697 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1703 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
1706 if (high_bit_depth) {
1707 return AV_RN32A(((int32_t *)mb) + index);
1709 return AV_RN16A(mb + index);
1712 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
1713 int index, int value)
1715 if (high_bit_depth) {
1716 AV_WN32A(((int32_t *)mb) + index, value);
1718 AV_WN16A(mb + index, value);
1721 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1722 int mb_type, int is_h264,
1724 int transform_bypass,
1728 uint8_t *dest_y, int p)
1730 MpegEncContext *const s = &h->s;
1731 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1732 void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1734 int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1735 block_offset += 16 * p;
1736 if (IS_INTRA4x4(mb_type)) {
1737 if (simple || !s->encoding) {
1738 if (IS_8x8DCT(mb_type)) {
1739 if (transform_bypass) {
1741 idct_add = s->dsp.add_pixels8;
1743 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1744 idct_add = h->h264dsp.h264_idct8_add;
1746 for (i = 0; i < 16; i += 4) {
1747 uint8_t *const ptr = dest_y + block_offset[i];
1748 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1749 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1750 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1752 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1753 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1754 (h->topright_samples_available << i) & 0x4000, linesize);
1756 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1757 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1759 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1764 if (transform_bypass) {
1766 idct_add = s->dsp.add_pixels4;
1768 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1769 idct_add = h->h264dsp.h264_idct_add;
1771 for (i = 0; i < 16; i++) {
1772 uint8_t *const ptr = dest_y + block_offset[i];
1773 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1775 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1776 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1781 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1782 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1783 assert(s->mb_y || linesize <= block_offset[i]);
1784 if (!topright_avail) {
1786 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1787 topright = (uint8_t *)&tr_high;
1789 tr = ptr[3 - linesize] * 0x01010101u;
1790 topright = (uint8_t *)&tr;
1793 topright = ptr + (4 << pixel_shift) - linesize;
1797 h->hpc.pred4x4[dir](ptr, topright, linesize);
1798 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1801 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1802 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1804 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1805 } else if (CONFIG_SVQ3_DECODER)
1806 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1813 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1815 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1816 if (!transform_bypass)
1817 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1819 h->dequant4_coeff[p][qscale][0]);
1821 static const uint8_t dc_mapping[16] = {
1822 0 * 16, 1 * 16, 4 * 16, 5 * 16,
1823 2 * 16, 3 * 16, 6 * 16, 7 * 16,
1824 8 * 16, 9 * 16, 12 * 16, 13 * 16,
1825 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1826 for (i = 0; i < 16; i++)
1827 dctcoef_set(h->mb + (p * 256 << pixel_shift),
1828 pixel_shift, dc_mapping[i],
1829 dctcoef_get(h->mb_luma_dc[p],
1833 } else if (CONFIG_SVQ3_DECODER)
1834 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
1835 h->mb_luma_dc[p], qscale);
1839 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
1840 int is_h264, int simple,
1841 int transform_bypass,
1845 uint8_t *dest_y, int p)
1847 MpegEncContext *const s = &h->s;
1848 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1850 block_offset += 16 * p;
1851 if (!IS_INTRA4x4(mb_type)) {
1853 if (IS_INTRA16x16(mb_type)) {
1854 if (transform_bypass) {
1855 if (h->sps.profile_idc == 244 &&
1856 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
1857 h->intra16x16_pred_mode == HOR_PRED8x8)) {
1858 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
1859 h->mb + (p * 256 << pixel_shift),
1862 for (i = 0; i < 16; i++)
1863 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
1864 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1865 s->dsp.add_pixels4(dest_y + block_offset[i],
1866 h->mb + (i * 16 + p * 256 << pixel_shift),
1870 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
1871 h->mb + (p * 256 << pixel_shift),
1873 h->non_zero_count_cache + p * 5 * 8);
1875 } else if (h->cbp & 15) {
1876 if (transform_bypass) {
1877 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1878 idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
1879 : s->dsp.add_pixels4;
1880 for (i = 0; i < 16; i += di)
1881 if (h->non_zero_count_cache[scan8[i + p * 16]])
1882 idct_add(dest_y + block_offset[i],
1883 h->mb + (i * 16 + p * 256 << pixel_shift),
1886 if (IS_8x8DCT(mb_type))
1887 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
1888 h->mb + (p * 256 << pixel_shift),
1890 h->non_zero_count_cache + p * 5 * 8);
1892 h->h264dsp.h264_idct_add16(dest_y, block_offset,
1893 h->mb + (p * 256 << pixel_shift),
1895 h->non_zero_count_cache + p * 5 * 8);
1898 } else if (CONFIG_SVQ3_DECODER) {
1899 for (i = 0; i < 16; i++)
1900 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
1901 // FIXME benchmark weird rule, & below
1902 uint8_t *const ptr = dest_y + block_offset[i];
1903 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
1904 s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1912 #include "h264_mb_template.c"
1916 #include "h264_mb_template.c"
1920 #include "h264_mb_template.c"
1922 void ff_h264_hl_decode_mb(H264Context *h)
1924 MpegEncContext *const s = &h->s;
1925 const int mb_xy = h->mb_xy;
1926 const int mb_type = s->current_picture.f.mb_type[mb_xy];
1927 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1930 if (is_complex || h->pixel_shift)
1931 hl_decode_mb_444_complex(h);
1933 hl_decode_mb_444_simple_8(h);
1934 } else if (is_complex) {
1935 hl_decode_mb_complex(h);
1936 } else if (h->pixel_shift) {
1937 hl_decode_mb_simple_16(h);
1939 hl_decode_mb_simple_8(h);
1942 static int pred_weight_table(H264Context *h)
1944 MpegEncContext *const s = &h->s;
1946 int luma_def, chroma_def;
1949 h->use_weight_chroma = 0;
1950 h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
1951 if (h->sps.chroma_format_idc)
1952 h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
1953 luma_def = 1 << h->luma_log2_weight_denom;
1954 chroma_def = 1 << h->chroma_log2_weight_denom;
1956 for (list = 0; list < 2; list++) {
1957 h->luma_weight_flag[list] = 0;
1958 h->chroma_weight_flag[list] = 0;
1959 for (i = 0; i < h->ref_count[list]; i++) {
1960 int luma_weight_flag, chroma_weight_flag;
1962 luma_weight_flag = get_bits1(&s->gb);
1963 if (luma_weight_flag) {
1964 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
1965 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
1966 if (h->luma_weight[i][list][0] != luma_def ||
1967 h->luma_weight[i][list][1] != 0) {
1969 h->luma_weight_flag[list] = 1;
1972 h->luma_weight[i][list][0] = luma_def;
1973 h->luma_weight[i][list][1] = 0;
1976 if (h->sps.chroma_format_idc) {
1977 chroma_weight_flag = get_bits1(&s->gb);
1978 if (chroma_weight_flag) {
1980 for (j = 0; j < 2; j++) {
1981 h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
1982 h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
1983 if (h->chroma_weight[i][list][j][0] != chroma_def ||
1984 h->chroma_weight[i][list][j][1] != 0) {
1985 h->use_weight_chroma = 1;
1986 h->chroma_weight_flag[list] = 1;
1991 for (j = 0; j < 2; j++) {
1992 h->chroma_weight[i][list][j][0] = chroma_def;
1993 h->chroma_weight[i][list][j][1] = 0;
1998 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2001 h->use_weight = h->use_weight || h->use_weight_chroma;
2006 * Initialize implicit_weight table.
2007 * @param field 0/1 initialize the weight for interlaced MBAFF
2008 * -1 initializes the rest
2010 static void implicit_weight_table(H264Context *h, int field)
2012 MpegEncContext *const s = &h->s;
2013 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2015 for (i = 0; i < 2; i++) {
2016 h->luma_weight_flag[i] = 0;
2017 h->chroma_weight_flag[i] = 0;
2021 if (s->picture_structure == PICT_FRAME) {
2022 cur_poc = s->current_picture_ptr->poc;
2024 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2026 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2027 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2029 h->use_weight_chroma = 0;
2033 ref_count0 = h->ref_count[0];
2034 ref_count1 = h->ref_count[1];
2036 cur_poc = s->current_picture_ptr->field_poc[field];
2038 ref_count0 = 16 + 2 * h->ref_count[0];
2039 ref_count1 = 16 + 2 * h->ref_count[1];
2043 h->use_weight_chroma = 2;
2044 h->luma_log2_weight_denom = 5;
2045 h->chroma_log2_weight_denom = 5;
2047 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2048 int poc0 = h->ref_list[0][ref0].poc;
2049 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2051 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2052 int poc1 = h->ref_list[1][ref1].poc;
2053 int td = av_clip(poc1 - poc0, -128, 127);
2055 int tb = av_clip(cur_poc - poc0, -128, 127);
2056 int tx = (16384 + (FFABS(td) >> 1)) / td;
2057 int dist_scale_factor = (tb * tx + 32) >> 8;
2058 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2059 w = 64 - dist_scale_factor;
2063 h->implicit_weight[ref0][ref1][0] =
2064 h->implicit_weight[ref0][ref1][1] = w;
2066 h->implicit_weight[ref0][ref1][field] = w;
2073 * instantaneous decoder refresh.
2075 static void idr(H264Context *h)
2078 ff_h264_remove_all_refs(h);
2079 h->prev_frame_num = 0;
2080 h->prev_frame_num_offset = 0;
2081 h->prev_poc_msb = 1<<16;
2082 h->prev_poc_lsb = 0;
2083 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2084 h->last_pocs[i] = INT_MIN;
2087 /* forget old pics after a seek */
2088 static void flush_dpb(AVCodecContext *avctx)
2090 H264Context *h = avctx->priv_data;
2092 for (i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
2093 if (h->delayed_pic[i])
2094 h->delayed_pic[i]->f.reference = 0;
2095 h->delayed_pic[i] = NULL;
2097 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2098 h->prev_interlaced_frame = 1;
2100 h->prev_frame_num = -1;
2101 if (h->s.current_picture_ptr)
2102 h->s.current_picture_ptr->f.reference = 0;
2103 h->s.first_field = 0;
2104 ff_h264_reset_sei(h);
2105 ff_mpeg_flush(avctx);
2106 h->recovery_frame= -1;
2110 static int init_poc(H264Context *h)
2112 MpegEncContext *const s = &h->s;
2113 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2115 Picture *cur = s->current_picture_ptr;
2117 h->frame_num_offset = h->prev_frame_num_offset;
2118 if (h->frame_num < h->prev_frame_num)
2119 h->frame_num_offset += max_frame_num;
2121 if (h->sps.poc_type == 0) {
2122 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2124 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2125 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2126 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2127 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2129 h->poc_msb = h->prev_poc_msb;
2130 // printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2132 field_poc[1] = h->poc_msb + h->poc_lsb;
2133 if (s->picture_structure == PICT_FRAME)
2134 field_poc[1] += h->delta_poc_bottom;
2135 } else if (h->sps.poc_type == 1) {
2136 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2139 if (h->sps.poc_cycle_length != 0)
2140 abs_frame_num = h->frame_num_offset + h->frame_num;
2144 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2147 expected_delta_per_poc_cycle = 0;
2148 for (i = 0; i < h->sps.poc_cycle_length; i++)
2149 // FIXME integrate during sps parse
2150 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2152 if (abs_frame_num > 0) {
2153 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2154 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2156 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2157 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2158 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2162 if (h->nal_ref_idc == 0)
2163 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2165 field_poc[0] = expectedpoc + h->delta_poc[0];
2166 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2168 if (s->picture_structure == PICT_FRAME)
2169 field_poc[1] += h->delta_poc[1];
2171 int poc = 2 * (h->frame_num_offset + h->frame_num);
2173 if (!h->nal_ref_idc)
2180 if (s->picture_structure != PICT_BOTTOM_FIELD)
2181 s->current_picture_ptr->field_poc[0] = field_poc[0];
2182 if (s->picture_structure != PICT_TOP_FIELD)
2183 s->current_picture_ptr->field_poc[1] = field_poc[1];
2184 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2190 * initialize scan tables
2192 static void init_scan_tables(H264Context *h)
2195 for (i = 0; i < 16; i++) {
2196 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2197 h->zigzag_scan[i] = T(zigzag_scan[i]);
2198 h->field_scan[i] = T(field_scan[i]);
2201 for (i = 0; i < 64; i++) {
2202 #define T(x) (x >> 3) | ((x & 7) << 3)
2203 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2204 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2205 h->field_scan8x8[i] = T(field_scan8x8[i]);
2206 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2209 if (h->sps.transform_bypass) { // FIXME same ugly
2210 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2211 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2212 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2213 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2214 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2215 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2217 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2218 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2219 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2220 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2221 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2222 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2226 static int field_end(H264Context *h, int in_setup)
2228 MpegEncContext *const s = &h->s;
2229 AVCodecContext *const avctx = s->avctx;
2233 if (!in_setup && !s->dropable)
2234 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2235 s->picture_structure == PICT_BOTTOM_FIELD);
2237 if (CONFIG_H264_VDPAU_DECODER &&
2238 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2239 ff_vdpau_h264_set_reference_frames(s);
2241 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2243 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2244 h->prev_poc_msb = h->poc_msb;
2245 h->prev_poc_lsb = h->poc_lsb;
2247 h->prev_frame_num_offset = h->frame_num_offset;
2248 h->prev_frame_num = h->frame_num;
2249 h->outputed_poc = h->next_outputed_poc;
2252 if (avctx->hwaccel) {
2253 if (avctx->hwaccel->end_frame(avctx) < 0)
2254 av_log(avctx, AV_LOG_ERROR,
2255 "hardware accelerator failed to decode picture\n");
2258 if (CONFIG_H264_VDPAU_DECODER &&
2259 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2260 ff_vdpau_h264_picture_complete(s);
2263 * FIXME: Error handling code does not seem to support interlaced
2264 * when slices span multiple rows
2265 * The ff_er_add_slice calls don't work right for bottom
2266 * fields; they cause massive erroneous error concealing
2267 * Error marking covers both fields (top and bottom).
2268 * This causes a mismatched s->error_count
2269 * and a bad error table. Further, the error count goes to
2270 * INT_MAX when called for bottom field, because mb_y is
2271 * past end by one (callers fault) and resync_mb_y != 0
2272 * causes problems for the first MB line, too.
2277 ff_MPV_frame_end(s);
2279 h->current_slice = 0;
2285 * Replicate H264 "master" context to thread contexts.
2287 static void clone_slice(H264Context *dst, H264Context *src)
2289 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2290 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2291 dst->s.current_picture = src->s.current_picture;
2292 dst->s.linesize = src->s.linesize;
2293 dst->s.uvlinesize = src->s.uvlinesize;
2294 dst->s.first_field = src->s.first_field;
2296 dst->prev_poc_msb = src->prev_poc_msb;
2297 dst->prev_poc_lsb = src->prev_poc_lsb;
2298 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2299 dst->prev_frame_num = src->prev_frame_num;
2300 dst->short_ref_count = src->short_ref_count;
2302 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2303 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2304 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2305 memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
2307 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2308 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2312 * Compute profile from profile_idc and constraint_set?_flags.
2316 * @return profile as defined by FF_PROFILE_H264_*
2318 int ff_h264_get_profile(SPS *sps)
2320 int profile = sps->profile_idc;
2322 switch (sps->profile_idc) {
2323 case FF_PROFILE_H264_BASELINE:
2324 // constraint_set1_flag set to 1
2325 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2327 case FF_PROFILE_H264_HIGH_10:
2328 case FF_PROFILE_H264_HIGH_422:
2329 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2330 // constraint_set3_flag set to 1
2331 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2339 * Decode a slice header.
2340 * This will also call ff_MPV_common_init() and frame_start() as needed.
2342 * @param h h264context
2343 * @param h0 h264 master context (differs from 'h' when doing sliced based
2344 * parallel decoding)
2346 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2348 static int decode_slice_header(H264Context *h, H264Context *h0)
2350 MpegEncContext *const s = &h->s;
2351 MpegEncContext *const s0 = &h0->s;
2352 unsigned int first_mb_in_slice;
2353 unsigned int pps_id;
2354 int num_ref_idx_active_override_flag;
2355 unsigned int slice_type, tmp, i, j;
2356 int default_ref_list_done = 0;
2357 int last_pic_structure, last_pic_dropable;
2360 /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2361 if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
2362 !h->nal_ref_idc && !h->pixel_shift) {
2363 s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
2364 s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
2366 s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
2367 s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
2370 first_mb_in_slice = get_ue_golomb_long(&s->gb);
2372 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2373 if (h0->current_slice && FIELD_PICTURE) {
2377 h0->current_slice = 0;
2378 if (!s0->first_field) {
2379 if (s->current_picture_ptr && !s->dropable &&
2380 s->current_picture_ptr->owner2 == s) {
2381 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2382 s->picture_structure == PICT_BOTTOM_FIELD);
2384 s->current_picture_ptr = NULL;
2388 slice_type = get_ue_golomb_31(&s->gb);
2389 if (slice_type > 9) {
2390 av_log(h->s.avctx, AV_LOG_ERROR,
2391 "slice type too large (%d) at %d %d\n",
2392 h->slice_type, s->mb_x, s->mb_y);
2395 if (slice_type > 4) {
2397 h->slice_type_fixed = 1;
2399 h->slice_type_fixed = 0;
2401 slice_type = golomb_to_pict_type[slice_type];
2402 if (slice_type == AV_PICTURE_TYPE_I ||
2403 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2404 default_ref_list_done = 1;
2406 h->slice_type = slice_type;
2407 h->slice_type_nos = slice_type & 3;
2409 // to make a few old functions happy, it's wrong though
2410 s->pict_type = h->slice_type;
2412 pps_id = get_ue_golomb(&s->gb);
2413 if (pps_id >= MAX_PPS_COUNT) {
2414 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
2417 if (!h0->pps_buffers[pps_id]) {
2418 av_log(h->s.avctx, AV_LOG_ERROR,
2419 "non-existing PPS %u referenced\n",
2423 h->pps = *h0->pps_buffers[pps_id];
2425 if (!h0->sps_buffers[h->pps.sps_id]) {
2426 av_log(h->s.avctx, AV_LOG_ERROR,
2427 "non-existing SPS %u referenced\n",
2431 h->sps = *h0->sps_buffers[h->pps.sps_id];
2433 s->avctx->profile = ff_h264_get_profile(&h->sps);
2434 s->avctx->level = h->sps.level_idc;
2435 s->avctx->refs = h->sps.ref_frame_count;
2437 must_reinit = (s->context_initialized &&
2438 ( 16*h->sps.mb_width != s->avctx->coded_width
2439 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != s->avctx->coded_height
2440 || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
2441 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
2442 || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio)));
2444 if(must_reinit && (h != h0 || (s->avctx->active_thread_type & FF_THREAD_FRAME))) {
2445 av_log_missing_feature(s->avctx,
2446 "Width/height/bit depth/chroma idc changing with threads is", 0);
2447 return AVERROR_PATCHWELCOME; // width / height changed during parallelized decoding
2450 s->mb_width = h->sps.mb_width;
2451 s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2453 h->b_stride = s->mb_width * 4;
2455 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2457 s->width = 16 * s->mb_width;
2458 s->height = 16 * s->mb_height;
2462 flush_dpb(s->avctx);
2463 ff_MPV_common_end(s);
2465 h->current_slice = 0;
2467 if (!s->context_initialized) {
2469 av_log(h->s.avctx, AV_LOG_ERROR,
2470 "Cannot (re-)initialize context during parallel decoding.\n");
2473 if( FFALIGN(s->avctx->width , 16 ) == s->width
2474 && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height
2475 && !h->sps.crop_right && !h->sps.crop_bottom
2476 && (s->avctx->width != s->width || s->avctx->height && s->height)
2478 av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
2479 s->avctx->coded_width = s->width;
2480 s->avctx->coded_height = s->height;
2482 avcodec_set_dimensions(s->avctx, s->width, s->height);
2483 s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2484 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);
2486 s->avctx->sample_aspect_ratio = h->sps.sar;
2487 av_assert0(s->avctx->sample_aspect_ratio.den);
2489 if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2490 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2491 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 && h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
2492 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2493 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2494 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2495 h->pixel_shift = h->sps.bit_depth_luma > 8;
2497 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2498 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2499 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2500 ff_dsputil_init(&s->dsp, s->avctx);
2502 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
2503 h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2508 if (h->sps.video_signal_type_present_flag) {
2509 s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
2511 if (h->sps.colour_description_present_flag) {
2512 s->avctx->color_primaries = h->sps.color_primaries;
2513 s->avctx->color_trc = h->sps.color_trc;
2514 s->avctx->colorspace = h->sps.colorspace;
2518 if (h->sps.timing_info_present_flag) {
2519 int64_t den = h->sps.time_scale;
2520 if (h->x264_build < 44U)
2522 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2523 h->sps.num_units_in_tick, den, 1 << 30);
2526 switch (h->sps.bit_depth_luma) {
2529 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2530 s->avctx->pix_fmt = PIX_FMT_GBRP9;
2532 s->avctx->pix_fmt = PIX_FMT_YUV444P9;
2533 } else if (CHROMA422)
2534 s->avctx->pix_fmt = PIX_FMT_YUV422P9;
2536 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
2540 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2541 s->avctx->pix_fmt = PIX_FMT_GBRP10;
2543 s->avctx->pix_fmt = PIX_FMT_YUV444P10;
2544 } else if (CHROMA422)
2545 s->avctx->pix_fmt = PIX_FMT_YUV422P10;
2547 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
2551 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2552 s->avctx->pix_fmt = PIX_FMT_GBRP12;
2554 s->avctx->pix_fmt = PIX_FMT_YUV444P12;
2555 } else if (CHROMA422)
2556 s->avctx->pix_fmt = PIX_FMT_YUV422P12;
2558 s->avctx->pix_fmt = PIX_FMT_YUV420P12;
2562 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2563 s->avctx->pix_fmt = PIX_FMT_GBRP14;
2565 s->avctx->pix_fmt = PIX_FMT_YUV444P14;
2566 } else if (CHROMA422)
2567 s->avctx->pix_fmt = PIX_FMT_YUV422P14;
2569 s->avctx->pix_fmt = PIX_FMT_YUV420P14;
2573 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P
2575 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2576 s->avctx->pix_fmt = PIX_FMT_GBR24P;
2577 av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2578 } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
2579 av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2581 } else if (CHROMA422) {
2582 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P
2585 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2586 s->avctx->codec->pix_fmts ?
2587 s->avctx->codec->pix_fmts :
2588 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2589 hwaccel_pixfmt_list_h264_jpeg_420 :
2590 ff_hwaccel_pixfmt_list_420);
2594 av_log(s->avctx, AV_LOG_ERROR,
2595 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2596 return AVERROR_INVALIDDATA;
2599 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
2602 if (ff_MPV_common_init(s) < 0) {
2603 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
2607 h->prev_interlaced_frame = 1;
2609 init_scan_tables(h);
2610 if (ff_h264_alloc_tables(h) < 0) {
2611 av_log(h->s.avctx, AV_LOG_ERROR,
2612 "Could not allocate memory for h264\n");
2613 return AVERROR(ENOMEM);
2616 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
2617 if (context_init(h) < 0) {
2618 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2622 for (i = 1; i < s->slice_context_count; i++) {
2624 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2625 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2626 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2627 c->h264dsp = h->h264dsp;
2630 c->pixel_shift = h->pixel_shift;
2631 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
2632 init_scan_tables(c);
2633 clone_tables(c, h, i);
2636 for (i = 0; i < s->slice_context_count; i++)
2637 if (context_init(h->thread_context[i]) < 0) {
2638 av_log(h->s.avctx, AV_LOG_ERROR,
2639 "context_init() failed.\n");
2645 if (h == h0 && h->dequant_coeff_pps != pps_id) {
2646 h->dequant_coeff_pps = pps_id;
2647 init_dequant_tables(h);
2650 h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
2653 h->mb_aff_frame = 0;
2654 last_pic_structure = s0->picture_structure;
2655 last_pic_dropable = s->dropable;
2656 s->dropable = h->nal_ref_idc == 0;
2657 if (h->sps.frame_mbs_only_flag) {
2658 s->picture_structure = PICT_FRAME;
2660 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
2661 av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
2664 if (get_bits1(&s->gb)) { // field_pic_flag
2665 s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
2667 s->picture_structure = PICT_FRAME;
2668 h->mb_aff_frame = h->sps.mb_aff;
2671 h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
2673 if (h0->current_slice != 0) {
2674 if (last_pic_structure != s->picture_structure ||
2675 last_pic_dropable != s->dropable) {
2676 av_log(h->s.avctx, AV_LOG_ERROR,
2677 "Changing field mode (%d -> %d) between slices is not allowed\n",
2678 last_pic_structure, s->picture_structure);
2679 s->picture_structure = last_pic_structure;
2680 s->dropable = last_pic_dropable;
2681 return AVERROR_INVALIDDATA;
2684 /* Shorten frame num gaps so we don't have to allocate reference
2685 * frames just to throw them away */
2686 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
2687 int unwrap_prev_frame_num = h->prev_frame_num;
2688 int max_frame_num = 1 << h->sps.log2_max_frame_num;
2690 if (unwrap_prev_frame_num > h->frame_num)
2691 unwrap_prev_frame_num -= max_frame_num;
2693 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2694 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2695 if (unwrap_prev_frame_num < 0)
2696 unwrap_prev_frame_num += max_frame_num;
2698 h->prev_frame_num = unwrap_prev_frame_num;
2702 /* See if we have a decoded first field looking for a pair...
2703 * Here, we're using that to see if we should mark previously
2704 * decode frames as "finished".
2705 * We have to do that before the "dummy" in-between frame allocation,
2706 * since that can modify s->current_picture_ptr. */
2707 if (s0->first_field) {
2708 assert(s0->current_picture_ptr);
2709 assert(s0->current_picture_ptr->f.data[0]);
2710 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2712 /* Mark old field/frame as completed */
2713 if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
2714 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2715 last_pic_structure == PICT_BOTTOM_FIELD);
2718 /* figure out if we have a complementary field pair */
2719 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2720 /* Previous field is unmatched. Don't display it, but let it
2721 * remain for reference if marked as such. */
2722 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
2723 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2724 last_pic_structure == PICT_TOP_FIELD);
2727 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2728 /* This and previous field were reference, but had
2729 * different frame_nums. Consider this field first in
2730 * pair. Throw away previous field except for reference
2732 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
2733 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2734 last_pic_structure == PICT_TOP_FIELD);
2737 /* Second field in complementary pair */
2738 if (!((last_pic_structure == PICT_TOP_FIELD &&
2739 s->picture_structure == PICT_BOTTOM_FIELD) ||
2740 (last_pic_structure == PICT_BOTTOM_FIELD &&
2741 s->picture_structure == PICT_TOP_FIELD))) {
2742 av_log(s->avctx, AV_LOG_ERROR,
2743 "Invalid field mode combination %d/%d\n",
2744 last_pic_structure, s->picture_structure);
2745 s->picture_structure = last_pic_structure;
2746 s->dropable = last_pic_dropable;
2747 return AVERROR_INVALIDDATA;
2748 } else if (last_pic_dropable != s->dropable) {
2749 av_log(s->avctx, AV_LOG_ERROR,
2750 "Cannot combine reference and non-reference fields in the same frame\n");
2751 av_log_ask_for_sample(s->avctx, NULL);
2752 s->picture_structure = last_pic_structure;
2753 s->dropable = last_pic_dropable;
2754 return AVERROR_INVALIDDATA;
2757 /* Take ownership of this buffer. Note that if another thread owned
2758 * the first field of this buffer, we're not operating on that pointer,
2759 * so the original thread is still responsible for reporting progress
2760 * on that first field (or if that was us, we just did that above).
2761 * By taking ownership, we assign responsibility to ourselves to
2762 * report progress on the second field. */
2763 s0->current_picture_ptr->owner2 = s0;
2768 while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
2769 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
2770 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2771 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
2772 h->frame_num, h->prev_frame_num);
2773 if (ff_h264_frame_start(h) < 0)
2775 h->prev_frame_num++;
2776 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
2777 s->current_picture_ptr->frame_num = h->prev_frame_num;
2778 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
2779 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
2780 ff_generate_sliding_window_mmcos(h);
2781 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2782 (s->avctx->err_recognition & AV_EF_EXPLODE))
2783 return AVERROR_INVALIDDATA;
2784 /* Error concealment: if a ref is missing, copy the previous ref in its place.
2785 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2786 * about there being no actual duplicates.
2787 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
2788 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2790 if (h->short_ref_count) {
2792 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2793 (const uint8_t **)prev->f.data, prev->f.linesize,
2794 s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
2795 h->short_ref[0]->poc = prev->poc + 2;
2797 h->short_ref[0]->frame_num = h->prev_frame_num;
2801 /* See if we have a decoded first field looking for a pair...
2802 * We're using that to see whether to continue decoding in that
2803 * frame, or to allocate a new one. */
2804 if (s0->first_field) {
2805 assert(s0->current_picture_ptr);
2806 assert(s0->current_picture_ptr->f.data[0]);
2807 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2809 /* figure out if we have a complementary field pair */
2810 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2811 /* Previous field is unmatched. Don't display it, but let it
2812 * remain for reference if marked as such. */
2813 s0->current_picture_ptr = NULL;
2814 s0->first_field = FIELD_PICTURE;
2816 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2817 ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
2818 s0->picture_structure==PICT_BOTTOM_FIELD);
2819 /* This and the previous field had different frame_nums.
2820 * Consider this field first in pair. Throw away previous
2821 * one except for reference purposes. */
2822 s0->first_field = 1;
2823 s0->current_picture_ptr = NULL;
2825 /* Second field in complementary pair */
2826 s0->first_field = 0;
2830 /* Frame or first field in a potentially complementary pair */
2831 assert(!s0->current_picture_ptr);
2832 s0->first_field = FIELD_PICTURE;
2835 if (!FIELD_PICTURE || s0->first_field) {
2836 if (ff_h264_frame_start(h) < 0) {
2837 s0->first_field = 0;
2841 ff_release_unused_pictures(s, 0);
2847 s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
2849 assert(s->mb_num == s->mb_width * s->mb_height);
2850 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2851 first_mb_in_slice >= s->mb_num) {
2852 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2855 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2856 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2857 if (s->picture_structure == PICT_BOTTOM_FIELD)
2858 s->resync_mb_y = s->mb_y = s->mb_y + 1;
2859 assert(s->mb_y < s->mb_height);
2861 if (s->picture_structure == PICT_FRAME) {
2862 h->curr_pic_num = h->frame_num;
2863 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
2865 h->curr_pic_num = 2 * h->frame_num + 1;
2866 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
2869 if (h->nal_unit_type == NAL_IDR_SLICE)
2870 get_ue_golomb(&s->gb); /* idr_pic_id */
2872 if (h->sps.poc_type == 0) {
2873 h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2875 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2876 h->delta_poc_bottom = get_se_golomb(&s->gb);
2879 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
2880 h->delta_poc[0] = get_se_golomb(&s->gb);
2882 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2883 h->delta_poc[1] = get_se_golomb(&s->gb);
2888 if (h->pps.redundant_pic_cnt_present)
2889 h->redundant_pic_count = get_ue_golomb(&s->gb);
2891 // set defaults, might be overridden a few lines later
2892 h->ref_count[0] = h->pps.ref_count[0];
2893 h->ref_count[1] = h->pps.ref_count[1];
2895 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2897 max[0] = max[1] = s->picture_structure == PICT_FRAME ? 15 : 31;
2899 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2900 h->direct_spatial_mv_pred = get_bits1(&s->gb);
2901 num_ref_idx_active_override_flag = get_bits1(&s->gb);
2903 if (num_ref_idx_active_override_flag) {
2904 h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
2905 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2906 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
2908 // full range is spec-ok in this case, even for frames
2912 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
2913 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]);
2914 h->ref_count[0] = h->ref_count[1] = 1;
2915 return AVERROR_INVALIDDATA;
2918 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2923 h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
2925 if (!default_ref_list_done)
2926 ff_h264_fill_default_ref_list(h);
2928 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
2929 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
2930 h->ref_count[1] = h->ref_count[0] = 0;
2934 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2935 s->last_picture_ptr = &h->ref_list[0][0];
2936 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2938 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
2939 s->next_picture_ptr = &h->ref_list[1][0];
2940 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2943 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
2944 (h->pps.weighted_bipred_idc == 1 &&
2945 h->slice_type_nos == AV_PICTURE_TYPE_B))
2946 pred_weight_table(h);
2947 else if (h->pps.weighted_bipred_idc == 2 &&
2948 h->slice_type_nos == AV_PICTURE_TYPE_B) {
2949 implicit_weight_table(h, -1);
2952 for (i = 0; i < 2; i++) {
2953 h->luma_weight_flag[i] = 0;
2954 h->chroma_weight_flag[i] = 0;
2958 if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
2959 (s->avctx->err_recognition & AV_EF_EXPLODE))
2960 return AVERROR_INVALIDDATA;
2963 ff_h264_fill_mbaff_ref_list(h);
2965 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
2966 implicit_weight_table(h, 0);
2967 implicit_weight_table(h, 1);
2971 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
2972 ff_h264_direct_dist_scale_factor(h);
2973 ff_h264_direct_ref_list_init(h);
2975 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
2976 tmp = get_ue_golomb_31(&s->gb);
2978 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2981 h->cabac_init_idc = tmp;
2984 h->last_qscale_diff = 0;
2985 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2986 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
2987 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2991 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2992 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2993 // FIXME qscale / qp ... stuff
2994 if (h->slice_type == AV_PICTURE_TYPE_SP)
2995 get_bits1(&s->gb); /* sp_for_switch_flag */
2996 if (h->slice_type == AV_PICTURE_TYPE_SP ||
2997 h->slice_type == AV_PICTURE_TYPE_SI)
2998 get_se_golomb(&s->gb); /* slice_qs_delta */
3000 h->deblocking_filter = 1;
3001 h->slice_alpha_c0_offset = 52;
3002 h->slice_beta_offset = 52;
3003 if (h->pps.deblocking_filter_parameters_present) {
3004 tmp = get_ue_golomb_31(&s->gb);
3006 av_log(s->avctx, AV_LOG_ERROR,
3007 "deblocking_filter_idc %u out of range\n", tmp);
3010 h->deblocking_filter = tmp;
3011 if (h->deblocking_filter < 2)
3012 h->deblocking_filter ^= 1; // 1<->0
3014 if (h->deblocking_filter) {
3015 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3016 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3017 if (h->slice_alpha_c0_offset > 104U ||
3018 h->slice_beta_offset > 104U) {
3019 av_log(s->avctx, AV_LOG_ERROR,
3020 "deblocking filter parameters %d %d out of range\n",
3021 h->slice_alpha_c0_offset, h->slice_beta_offset);
3027 if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3028 (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3029 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3030 (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3031 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3032 (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3033 h->nal_ref_idc == 0))
3034 h->deblocking_filter = 0;
3036 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3037 if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3038 /* Cheat slightly for speed:
3039 * Do not bother to deblock across slices. */
3040 h->deblocking_filter = 2;
3042 h0->max_contexts = 1;
3043 if (!h0->single_decode_warning) {
3044 av_log(s->avctx, AV_LOG_INFO,
3045 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3046 h0->single_decode_warning = 1;
3049 av_log(h->s.avctx, AV_LOG_ERROR,
3050 "Deblocking switched inside frame.\n");
3055 h->qp_thresh = 15 + 52 -
3056 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3058 h->pps.chroma_qp_index_offset[0],
3059 h->pps.chroma_qp_index_offset[1]) +
3060 6 * (h->sps.bit_depth_luma - 8);
3062 h0->last_slice_type = slice_type;
3063 h->slice_num = ++h0->current_slice;
3066 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
3067 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
3068 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
3069 && h->slice_num >= MAX_SLICES) {
3070 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3071 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);
3074 for (j = 0; j < 2; j++) {
3076 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3077 for (i = 0; i < 16; i++) {
3079 if (h->ref_list[j][i].f.data[0]) {
3081 uint8_t *base = h->ref_list[j][i].f.base[0];
3082 for (k = 0; k < h->short_ref_count; k++)
3083 if (h->short_ref[k]->f.base[0] == base) {
3087 for (k = 0; k < h->long_ref_count; k++)
3088 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3089 id_list[i] = h->short_ref_count + k;
3097 for (i = 0; i < 16; i++)
3098 ref2frm[i + 2] = 4 * id_list[i] +
3099 (h->ref_list[j][i].f.reference & 3);
3101 ref2frm[18 + 1] = -1;
3102 for (i = 16; i < 48; i++)
3103 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3104 (h->ref_list[j][i].f.reference & 3);
3107 // FIXME: fix draw_edges + PAFF + frame threads
3108 h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
3109 (!h->sps.frame_mbs_only_flag &&
3110 s->avctx->active_thread_type))
3112 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3114 if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3115 av_log(h->s.avctx, AV_LOG_DEBUG,
3116 "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",
3118 (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3120 av_get_picture_type_char(h->slice_type),
3121 h->slice_type_fixed ? " fix" : "",
3122 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3123 pps_id, h->frame_num,
3124 s->current_picture_ptr->field_poc[0],
3125 s->current_picture_ptr->field_poc[1],
3126 h->ref_count[0], h->ref_count[1],
3128 h->deblocking_filter,
3129 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3131 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3132 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3138 int ff_h264_get_slice_type(const H264Context *h)
3140 switch (h->slice_type) {
3141 case AV_PICTURE_TYPE_P:
3143 case AV_PICTURE_TYPE_B:
3145 case AV_PICTURE_TYPE_I:
3147 case AV_PICTURE_TYPE_SP:
3149 case AV_PICTURE_TYPE_SI:
3156 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3157 MpegEncContext *const s,
3158 int mb_type, int top_xy,
3159 int left_xy[LEFT_MBS],
3161 int left_type[LEFT_MBS],
3162 int mb_xy, int list)
3164 int b_stride = h->b_stride;
3165 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3166 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3167 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3168 if (USES_LIST(top_type, list)) {
3169 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3170 const int b8_xy = 4 * top_xy + 2;
3171 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3172 AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
3173 ref_cache[0 - 1 * 8] =
3174 ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3175 ref_cache[2 - 1 * 8] =
3176 ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3178 AV_ZERO128(mv_dst - 1 * 8);
3179 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3182 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3183 if (USES_LIST(left_type[LTOP], list)) {
3184 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3185 const int b8_xy = 4 * left_xy[LTOP] + 1;
3186 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3187 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
3188 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
3189 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
3190 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
3192 ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
3193 ref_cache[-1 + 16] =
3194 ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
3196 AV_ZERO32(mv_dst - 1 + 0);
3197 AV_ZERO32(mv_dst - 1 + 8);
3198 AV_ZERO32(mv_dst - 1 + 16);
3199 AV_ZERO32(mv_dst - 1 + 24);
3202 ref_cache[-1 + 16] =
3203 ref_cache[-1 + 24] = LIST_NOT_USED;
3208 if (!USES_LIST(mb_type, list)) {
3209 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3210 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3211 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3212 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3213 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3218 int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
3219 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3220 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3221 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3222 AV_WN32A(&ref_cache[0 * 8], ref01);
3223 AV_WN32A(&ref_cache[1 * 8], ref01);
3224 AV_WN32A(&ref_cache[2 * 8], ref23);
3225 AV_WN32A(&ref_cache[3 * 8], ref23);
3229 int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
3230 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3231 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3232 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3233 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3239 * @return non zero if the loop filter can be skipped
3241 static int fill_filter_caches(H264Context *h, int mb_type)
3243 MpegEncContext *const s = &h->s;
3244 const int mb_xy = h->mb_xy;
3245 int top_xy, left_xy[LEFT_MBS];
3246 int top_type, left_type[LEFT_MBS];
3250 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3252 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3253 * stuff, I can't imagine that these complex rules are worth it. */
3255 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3257 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3258 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3260 if (left_mb_field_flag != curr_mb_field_flag)
3261 left_xy[LTOP] -= s->mb_stride;
3263 if (curr_mb_field_flag)
3264 top_xy += s->mb_stride &
3265 (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3266 if (left_mb_field_flag != curr_mb_field_flag)
3267 left_xy[LBOT] += s->mb_stride;
3271 h->top_mb_xy = top_xy;
3272 h->left_mb_xy[LTOP] = left_xy[LTOP];
3273 h->left_mb_xy[LBOT] = left_xy[LBOT];
3275 /* For sufficiently low qp, filtering wouldn't do anything.
3276 * This is a conservative estimate: could also check beta_offset
3277 * and more accurate chroma_qp. */
3278 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3279 int qp = s->current_picture.f.qscale_table[mb_xy];
3280 if (qp <= qp_thresh &&
3281 (left_xy[LTOP] < 0 ||
3282 ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3284 ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3287 if ((left_xy[LTOP] < 0 ||
3288 ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3289 (top_xy < s->mb_stride ||
3290 ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3295 top_type = s->current_picture.f.mb_type[top_xy];
3296 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3297 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3298 if (h->deblocking_filter == 2) {
3299 if (h->slice_table[top_xy] != h->slice_num)
3301 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3302 left_type[LTOP] = left_type[LBOT] = 0;
3304 if (h->slice_table[top_xy] == 0xFFFF)
3306 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3307 left_type[LTOP] = left_type[LBOT] = 0;
3309 h->top_type = top_type;
3310 h->left_type[LTOP] = left_type[LTOP];
3311 h->left_type[LBOT] = left_type[LBOT];
3313 if (IS_INTRA(mb_type))
3316 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3317 top_type, left_type, mb_xy, 0);
3318 if (h->list_count == 2)
3319 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3320 top_type, left_type, mb_xy, 1);
3322 nnz = h->non_zero_count[mb_xy];
3323 nnz_cache = h->non_zero_count_cache;
3324 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3325 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3326 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3327 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3328 h->cbp = h->cbp_table[mb_xy];
3331 nnz = h->non_zero_count[top_xy];
3332 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3335 if (left_type[LTOP]) {
3336 nnz = h->non_zero_count[left_xy[LTOP]];
3337 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3338 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3339 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3340 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3343 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3344 * from what the loop filter needs */
3345 if (!CABAC && h->pps.transform_8x8_mode) {
3346 if (IS_8x8DCT(top_type)) {
3347 nnz_cache[4 + 8 * 0] =
3348 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3349 nnz_cache[6 + 8 * 0] =
3350 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3352 if (IS_8x8DCT(left_type[LTOP])) {
3353 nnz_cache[3 + 8 * 1] =
3354 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3356 if (IS_8x8DCT(left_type[LBOT])) {
3357 nnz_cache[3 + 8 * 3] =
3358 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3361 if (IS_8x8DCT(mb_type)) {
3362 nnz_cache[scan8[0]] =
3363 nnz_cache[scan8[1]] =
3364 nnz_cache[scan8[2]] =
3365 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3367 nnz_cache[scan8[0 + 4]] =
3368 nnz_cache[scan8[1 + 4]] =
3369 nnz_cache[scan8[2 + 4]] =
3370 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3372 nnz_cache[scan8[0 + 8]] =
3373 nnz_cache[scan8[1 + 8]] =
3374 nnz_cache[scan8[2 + 8]] =
3375 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3377 nnz_cache[scan8[0 + 12]] =
3378 nnz_cache[scan8[1 + 12]] =
3379 nnz_cache[scan8[2 + 12]] =
3380 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3387 static void loop_filter(H264Context *h, int start_x, int end_x)
3389 MpegEncContext *const s = &h->s;
3390 uint8_t *dest_y, *dest_cb, *dest_cr;
3391 int linesize, uvlinesize, mb_x, mb_y;
3392 const int end_mb_y = s->mb_y + FRAME_MBAFF;
3393 const int old_slice_type = h->slice_type;
3394 const int pixel_shift = h->pixel_shift;
3395 const int block_h = 16 >> s->chroma_y_shift;
3397 if (h->deblocking_filter) {
3398 for (mb_x = start_x; mb_x < end_x; mb_x++)
3399 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
3401 mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
3402 h->slice_num = h->slice_table[mb_xy];
3403 mb_type = s->current_picture.f.mb_type[mb_xy];
3404 h->list_count = h->list_counts[mb_xy];
3408 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3412 dest_y = s->current_picture.f.data[0] +
3413 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
3414 dest_cb = s->current_picture.f.data[1] +
3415 (mb_x << pixel_shift) * (8 << CHROMA444) +
3416 mb_y * s->uvlinesize * block_h;
3417 dest_cr = s->current_picture.f.data[2] +
3418 (mb_x << pixel_shift) * (8 << CHROMA444) +
3419 mb_y * s->uvlinesize * block_h;
3420 // FIXME simplify above
3423 linesize = h->mb_linesize = s->linesize * 2;
3424 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3425 if (mb_y & 1) { // FIXME move out of this function?
3426 dest_y -= s->linesize * 15;
3427 dest_cb -= s->uvlinesize * (block_h - 1);
3428 dest_cr -= s->uvlinesize * (block_h - 1);
3431 linesize = h->mb_linesize = s->linesize;
3432 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3434 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
3436 if (fill_filter_caches(h, mb_type))
3438 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3439 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3442 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
3443 linesize, uvlinesize);
3445 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
3446 dest_cr, linesize, uvlinesize);
3450 h->slice_type = old_slice_type;
3452 s->mb_y = end_mb_y - FRAME_MBAFF;
3453 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3454 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3457 static void predict_field_decoding_flag(H264Context *h)
3459 MpegEncContext *const s = &h->s;
3460 const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
3461 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
3462 s->current_picture.f.mb_type[mb_xy - 1] :
3463 (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
3464 s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
3465 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3469 * Draw edges and report progress for the last MB row.
3471 static void decode_finish_row(H264Context *h)
3473 MpegEncContext *const s = &h->s;
3474 int top = 16 * (s->mb_y >> FIELD_PICTURE);
3475 int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
3476 int height = 16 << FRAME_MBAFF;
3477 int deblock_border = (16 + 4) << FRAME_MBAFF;
3479 if (h->deblocking_filter) {
3480 if ((top + height) >= pic_height)
3481 height += deblock_border;
3482 top -= deblock_border;
3485 if (top >= pic_height || (top + height) < h->emu_edge_height)
3488 height = FFMIN(height, pic_height - top);
3489 if (top < h->emu_edge_height) {
3490 height = top + height;
3494 ff_draw_horiz_band(s, top, height);
3499 ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
3500 s->picture_structure == PICT_BOTTOM_FIELD);
3503 static int decode_slice(struct AVCodecContext *avctx, void *arg)
3505 H264Context *h = *(void **)arg;
3506 MpegEncContext *const s = &h->s;
3507 const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
3509 int lf_x_start = s->mb_x;
3511 s->mb_skip_run = -1;
3513 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
3514 s->codec_id != CODEC_ID_H264 ||
3515 (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
3519 align_get_bits(&s->gb);
3522 ff_init_cabac_states(&h->cabac);
3523 ff_init_cabac_decoder(&h->cabac,
3524 s->gb.buffer + get_bits_count(&s->gb) / 8,
3525 (get_bits_left(&s->gb) + 7) / 8);
3527 ff_h264_init_cabac_states(h);
3531 int ret = ff_h264_decode_mb_cabac(h);
3533 // STOP_TIMER("decode_mb_cabac")
3536 ff_h264_hl_decode_mb(h);
3538 // FIXME optimal? or let mb_decode decode 16x32 ?
3539 if (ret >= 0 && FRAME_MBAFF) {
3542 ret = ff_h264_decode_mb_cabac(h);
3545 ff_h264_hl_decode_mb(h);
3548 eos = get_cabac_terminate(&h->cabac);
3550 if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
3551 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3552 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3553 s->mb_y, ER_MB_END & part_mask);
3554 if (s->mb_x >= lf_x_start)
3555 loop_filter(h, lf_x_start, s->mb_x + 1);
3558 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
3559 av_log(h->s.avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
3560 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
3561 av_log(h->s.avctx, AV_LOG_ERROR,
3562 "error while decoding MB %d %d, bytestream (%td)\n",
3564 h->cabac.bytestream_end - h->cabac.bytestream);
3565 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3566 s->mb_y, ER_MB_ERROR & part_mask);
3570 if (++s->mb_x >= s->mb_width) {
3571 loop_filter(h, lf_x_start, s->mb_x);
3572 s->mb_x = lf_x_start = 0;
3573 decode_finish_row(h);
3575 if (FIELD_OR_MBAFF_PICTURE) {
3577 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3578 predict_field_decoding_flag(h);
3582 if (eos || s->mb_y >= s->mb_height) {
3583 tprintf(s->avctx, "slice end %d %d\n",
3584 get_bits_count(&s->gb), s->gb.size_in_bits);
3585 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3586 s->mb_y, ER_MB_END & part_mask);
3587 if (s->mb_x > lf_x_start)
3588 loop_filter(h, lf_x_start, s->mb_x);
3594 int ret = ff_h264_decode_mb_cavlc(h);
3597 ff_h264_hl_decode_mb(h);
3599 // FIXME optimal? or let mb_decode decode 16x32 ?
3600 if (ret >= 0 && FRAME_MBAFF) {
3602 ret = ff_h264_decode_mb_cavlc(h);
3605 ff_h264_hl_decode_mb(h);
3610 av_log(h->s.avctx, AV_LOG_ERROR,
3611 "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3612 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3613 s->mb_y, ER_MB_ERROR & part_mask);
3617 if (++s->mb_x >= s->mb_width) {
3618 loop_filter(h, lf_x_start, s->mb_x);
3619 s->mb_x = lf_x_start = 0;
3620 decode_finish_row(h);
3622 if (FIELD_OR_MBAFF_PICTURE) {
3624 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3625 predict_field_decoding_flag(h);
3627 if (s->mb_y >= s->mb_height) {
3628 tprintf(s->avctx, "slice end %d %d\n",
3629 get_bits_count(&s->gb), s->gb.size_in_bits);
3631 if ( get_bits_left(&s->gb) == 0
3632 || get_bits_left(&s->gb) > 0 && !(s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
3633 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3634 s->mb_x - 1, s->mb_y,
3635 ER_MB_END & part_mask);
3639 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3641 ER_MB_END & part_mask);
3648 if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
3649 tprintf(s->avctx, "slice end %d %d\n",
3650 get_bits_count(&s->gb), s->gb.size_in_bits);
3651 if (get_bits_left(&s->gb) == 0) {
3652 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3653 s->mb_x - 1, s->mb_y,
3654 ER_MB_END & part_mask);
3655 if (s->mb_x > lf_x_start)
3656 loop_filter(h, lf_x_start, s->mb_x);
3660 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3661 s->mb_y, ER_MB_ERROR & part_mask);
3671 * Call decode_slice() for each context.
3673 * @param h h264 master context
3674 * @param context_count number of contexts to execute
3676 static int execute_decode_slices(H264Context *h, int context_count)
3678 MpegEncContext *const s = &h->s;
3679 AVCodecContext *const avctx = s->avctx;
3683 if (s->avctx->hwaccel ||
3684 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3686 if (context_count == 1) {
3687 return decode_slice(avctx, &h);
3689 for (i = 1; i < context_count; i++) {
3690 hx = h->thread_context[i];
3691 hx->s.err_recognition = avctx->err_recognition;
3692 hx->s.error_count = 0;
3693 hx->x264_build = h->x264_build;
3696 avctx->execute(avctx, decode_slice, h->thread_context,
3697 NULL, context_count, sizeof(void *));
3699 /* pull back stuff from slices to master context */
3700 hx = h->thread_context[context_count - 1];
3701 s->mb_x = hx->s.mb_x;
3702 s->mb_y = hx->s.mb_y;
3703 s->dropable = hx->s.dropable;
3704 s->picture_structure = hx->s.picture_structure;
3705 for (i = 1; i < context_count; i++)
3706 h->s.error_count += h->thread_context[i]->s.error_count;
3712 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
3714 MpegEncContext *const s = &h->s;
3715 AVCodecContext *const avctx = s->avctx;
3716 H264Context *hx; ///< thread context
3720 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
3721 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
3724 h->nal_unit_type= 0;
3726 if(!s->slice_context_count)
3727 s->slice_context_count= 1;
3728 h->max_contexts = s->slice_context_count;
3729 if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3730 h->current_slice = 0;
3731 if (!s->first_field)
3732 s->current_picture_ptr = NULL;
3733 ff_h264_reset_sei(h);
3736 for (; pass <= 1; pass++) {
3739 next_avc = h->is_avc ? 0 : buf_size;
3749 if (buf_index >= next_avc) {
3750 if (buf_index >= buf_size - h->nal_length_size)
3753 for (i = 0; i < h->nal_length_size; i++)
3754 nalsize = (nalsize << 8) | buf[buf_index++];
3755 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
3756 av_log(h->s.avctx, AV_LOG_ERROR,
3757 "AVC: nal size %d\n", nalsize);
3760 next_avc = buf_index + nalsize;
3762 // start code prefix search
3763 for (; buf_index + 3 < next_avc; buf_index++)
3764 // This should always succeed in the first iteration.
3765 if (buf[buf_index] == 0 &&
3766 buf[buf_index + 1] == 0 &&
3767 buf[buf_index + 2] == 1)
3770 if (buf_index + 3 >= buf_size)
3774 if (buf_index >= next_avc)
3778 hx = h->thread_context[context_count];
3780 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
3781 &consumed, next_avc - buf_index);
3782 if (ptr == NULL || dst_length < 0) {
3786 i = buf_index + consumed;
3787 if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
3788 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
3789 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
3790 s->workaround_bugs |= FF_BUG_TRUNCATED;
3792 if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
3793 while(dst_length > 0 && ptr[dst_length - 1] == 0)
3795 bit_length = !dst_length ? 0
3797 decode_rbsp_trailing(h, ptr + dst_length - 1));
3799 if (s->avctx->debug & FF_DEBUG_STARTCODE)
3800 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);
3802 if (h->is_avc && (nalsize != consumed) && nalsize)
3803 av_log(h->s.avctx, AV_LOG_DEBUG,
3804 "AVC: Consumed only %d bytes instead of %d\n",
3807 buf_index += consumed;
3811 /* packets can sometimes contain multiple PPS/SPS,
3812 * e.g. two PAFF field pictures in one packet, or a demuxer
3813 * which splits NALs strangely if so, when frame threading we
3814 * can't start the next thread until we've read all of them */
3815 switch (hx->nal_unit_type) {
3818 nals_needed = nal_index;
3822 init_get_bits(&hx->s.gb, ptr, bit_length);
3823 if (!get_ue_golomb(&hx->s.gb))
3824 nals_needed = nal_index;
3829 // FIXME do not discard SEI id
3830 if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
3835 switch (hx->nal_unit_type) {
3837 if (h->nal_unit_type != NAL_IDR_SLICE) {
3838 av_log(h->s.avctx, AV_LOG_ERROR,
3839 "Invalid mix of idr and non-idr slices\n");
3843 idr(h); // FIXME ensure we don't lose some frames if there is reordering
3845 init_get_bits(&hx->s.gb, ptr, bit_length);
3847 hx->inter_gb_ptr = &hx->s.gb;
3848 hx->s.data_partitioning = 0;
3850 if ((err = decode_slice_header(hx, h)))
3853 if ( h->sei_recovery_frame_cnt >= 0
3854 && ( h->recovery_frame<0
3855 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
3856 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
3857 (1 << h->sps.log2_max_frame_num);
3860 s->current_picture_ptr->f.key_frame |=
3861 (hx->nal_unit_type == NAL_IDR_SLICE);
3863 if (h->recovery_frame == h->frame_num) {
3864 s->current_picture_ptr->sync |= 1;
3865 h->recovery_frame = -1;
3868 h->sync |= !!s->current_picture_ptr->f.key_frame;
3869 h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
3870 s->current_picture_ptr->sync |= h->sync;
3872 if (h->current_slice == 1) {
3873 if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
3874 decode_postinit(h, nal_index >= nals_needed);
3876 if (s->avctx->hwaccel &&
3877 s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3879 if (CONFIG_H264_VDPAU_DECODER &&
3880 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3881 ff_vdpau_h264_picture_start(s);
3884 if (hx->redundant_pic_count == 0 &&
3885 (avctx->skip_frame < AVDISCARD_NONREF ||
3887 (avctx->skip_frame < AVDISCARD_BIDIR ||
3888 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
3889 (avctx->skip_frame < AVDISCARD_NONKEY ||
3890 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
3891 avctx->skip_frame < AVDISCARD_ALL) {
3892 if (avctx->hwaccel) {
3893 if (avctx->hwaccel->decode_slice(avctx,
3894 &buf[buf_index - consumed],
3897 } else if (CONFIG_H264_VDPAU_DECODER &&
3898 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
3899 static const uint8_t start_code[] = {
3901 ff_vdpau_add_data_chunk(s, start_code,
3902 sizeof(start_code));
3903 ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
3910 init_get_bits(&hx->s.gb, ptr, bit_length);
3912 hx->inter_gb_ptr = NULL;
3914 if ((err = decode_slice_header(hx, h)) < 0)
3917 hx->s.data_partitioning = 1;
3920 init_get_bits(&hx->intra_gb, ptr, bit_length);
3921 hx->intra_gb_ptr = &hx->intra_gb;
3924 init_get_bits(&hx->inter_gb, ptr, bit_length);
3925 hx->inter_gb_ptr = &hx->inter_gb;
3927 av_log(h->s.avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
3928 return AVERROR_PATCHWELCOME;
3930 if (hx->redundant_pic_count == 0 &&
3932 hx->s.data_partitioning &&
3933 s->context_initialized &&
3934 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
3935 (avctx->skip_frame < AVDISCARD_BIDIR ||
3936 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
3937 (avctx->skip_frame < AVDISCARD_NONKEY ||
3938 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
3939 avctx->skip_frame < AVDISCARD_ALL)
3943 init_get_bits(&s->gb, ptr, bit_length);
3944 ff_h264_decode_sei(h);
3947 init_get_bits(&s->gb, ptr, bit_length);
3948 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
3949 av_log(h->s.avctx, AV_LOG_DEBUG,
3950 "SPS decoding failure, trying again with the complete NAL\n");
3952 av_assert0(next_avc - buf_index + consumed == nalsize);
3953 init_get_bits(&s->gb, &buf[buf_index + 1 - consumed],
3954 8*(next_avc - buf_index + consumed - 1));
3955 ff_h264_decode_seq_parameter_set(h);
3958 if (s->flags & CODEC_FLAG_LOW_DELAY ||
3959 (h->sps.bitstream_restriction_flag &&
3960 !h->sps.num_reorder_frames))
3962 if (avctx->has_b_frames < 2)
3963 avctx->has_b_frames = !s->low_delay;
3966 init_get_bits(&s->gb, ptr, bit_length);
3967 ff_h264_decode_picture_parameter_set(h, bit_length);
3970 case NAL_END_SEQUENCE:
3971 case NAL_END_STREAM:
3972 case NAL_FILLER_DATA:
3974 case NAL_AUXILIARY_SLICE:
3977 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
3978 hx->nal_unit_type, bit_length);
3981 if (context_count == h->max_contexts) {
3982 execute_decode_slices(h, context_count);
3987 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3988 else if (err == 1) {
3989 /* Slice could not be decoded in parallel mode, copy down
3990 * NAL unit stuff to context 0 and restart. Note that
3991 * rbsp_buffer is not transferred, but since we no longer
3992 * run in parallel mode this should not be an issue. */
3993 h->nal_unit_type = hx->nal_unit_type;
3994 h->nal_ref_idc = hx->nal_ref_idc;
4001 execute_decode_slices(h, context_count);
4005 if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
4007 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
4008 s->picture_structure == PICT_BOTTOM_FIELD);
4015 * Return the number of bytes consumed for building the current frame.
4017 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
4020 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4021 if (pos + 10 > buf_size)
4022 pos = buf_size; // oops ;)
4027 static int decode_frame(AVCodecContext *avctx, void *data,
4028 int *data_size, AVPacket *avpkt)
4030 const uint8_t *buf = avpkt->data;
4031 int buf_size = avpkt->size;
4032 H264Context *h = avctx->priv_data;
4033 MpegEncContext *s = &h->s;
4034 AVFrame *pict = data;
4039 s->flags = avctx->flags;
4040 s->flags2 = avctx->flags2;
4042 /* end of stream, output what is still in the buffers */
4043 if (buf_size == 0) {
4046 s->current_picture_ptr = NULL;
4048 // FIXME factorize this with the output code below
4049 out = h->delayed_pic[0];
4052 h->delayed_pic[i] &&
4053 !h->delayed_pic[i]->f.key_frame &&
4054 !h->delayed_pic[i]->mmco_reset;
4056 if (h->delayed_pic[i]->poc < out->poc) {
4057 out = h->delayed_pic[i];
4061 for (i = out_idx; h->delayed_pic[i]; i++)
4062 h->delayed_pic[i] = h->delayed_pic[i + 1];
4065 *data_size = sizeof(AVFrame);
4071 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
4072 int cnt= buf[5]&0x1f;
4073 const uint8_t *p= buf+6;
4075 int nalsize= AV_RB16(p) + 2;
4076 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
4084 int nalsize= AV_RB16(p) + 2;
4085 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
4090 return ff_h264_decode_extradata(h, buf, buf_size);
4094 buf_index = decode_nal_units(h, buf, buf_size);
4098 if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4099 av_assert0(buf_index <= buf_size);
4103 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
4104 if (avctx->skip_frame >= AVDISCARD_NONREF ||
4105 buf_size >= 4 && !memcmp("Q264", buf, 4))
4107 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4111 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
4112 (s->mb_y >= s->mb_height && s->mb_height)) {
4113 if (s->flags2 & CODEC_FLAG2_CHUNKS)
4114 decode_postinit(h, 1);
4118 /* Wait for second field. */
4120 if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
4121 *data_size = sizeof(AVFrame);
4122 *pict = h->next_output_pic->f;
4126 assert(pict->data[0] || !*data_size);
4127 ff_print_debug_info(s, pict);
4128 // printf("out %d\n", (int)pict->data[0]);
4130 return get_consumed_bytes(s, buf_index, buf_size);
4133 av_cold void ff_h264_free_context(H264Context *h)
4137 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4139 for (i = 0; i < MAX_SPS_COUNT; i++)
4140 av_freep(h->sps_buffers + i);
4142 for (i = 0; i < MAX_PPS_COUNT; i++)
4143 av_freep(h->pps_buffers + i);
4146 static av_cold int h264_decode_end(AVCodecContext *avctx)
4148 H264Context *h = avctx->priv_data;
4149 MpegEncContext *s = &h->s;
4151 ff_h264_remove_all_refs(h);
4152 ff_h264_free_context(h);
4154 ff_MPV_common_end(s);
4156 // memset(h, 0, sizeof(H264Context));
4161 static const AVProfile profiles[] = {
4162 { FF_PROFILE_H264_BASELINE, "Baseline" },
4163 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4164 { FF_PROFILE_H264_MAIN, "Main" },
4165 { FF_PROFILE_H264_EXTENDED, "Extended" },
4166 { FF_PROFILE_H264_HIGH, "High" },
4167 { FF_PROFILE_H264_HIGH_10, "High 10" },
4168 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4169 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4170 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4171 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4172 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4173 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4174 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4175 { FF_PROFILE_UNKNOWN },
4178 static const AVOption h264_options[] = {
4179 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
4180 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 4, 0},
4184 static const AVClass h264_class = {
4186 av_default_item_name,
4188 LIBAVUTIL_VERSION_INT,
4191 static const AVClass h264_vdpau_class = {
4192 "H264 VDPAU Decoder",
4193 av_default_item_name,
4195 LIBAVUTIL_VERSION_INT,
4198 AVCodec ff_h264_decoder = {
4200 .type = AVMEDIA_TYPE_VIDEO,
4201 .id = CODEC_ID_H264,
4202 .priv_data_size = sizeof(H264Context),
4203 .init = ff_h264_decode_init,
4204 .close = h264_decode_end,
4205 .decode = decode_frame,
4206 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4207 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4208 CODEC_CAP_FRAME_THREADS,
4210 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4211 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4212 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4213 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4214 .priv_class = &h264_class,
4217 #if CONFIG_H264_VDPAU_DECODER
4218 AVCodec ff_h264_vdpau_decoder = {
4219 .name = "h264_vdpau",
4220 .type = AVMEDIA_TYPE_VIDEO,
4221 .id = CODEC_ID_H264,
4222 .priv_data_size = sizeof(H264Context),
4223 .init = ff_h264_decode_init,
4224 .close = h264_decode_end,
4225 .decode = decode_frame,
4226 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4228 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4229 .pix_fmts = (const enum PixelFormat[]) { PIX_FMT_VDPAU_H264,
4231 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4232 .priv_class = &h264_vdpau_class,