2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/imgutils.h"
31 #include "cabac_functions.h"
34 #include "mpegvideo.h"
37 #include "h264_mvpred.h"
40 #include "rectangle.h"
42 #include "vdpau_internal.h"
43 #include "libavutil/avassert.h"
48 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
50 static const uint8_t rem6[QP_MAX_NUM + 1] = {
51 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
52 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
53 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
56 static const uint8_t div6[QP_MAX_NUM + 1] = {
57 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
58 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
59 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
62 static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
63 #if CONFIG_H264_DXVA2_HWACCEL
66 #if CONFIG_H264_VAAPI_HWACCEL
69 #if CONFIG_H264_VDA_HWACCEL
72 #if CONFIG_H264_VDPAU_HWACCEL
80 * Check if the top & left blocks are available if needed and
81 * change the dc mode so it only uses the available blocks.
83 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
85 MpegEncContext *const s = &h->s;
86 static const int8_t top[12] = {
87 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
89 static const int8_t left[12] = {
90 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
94 if (!(h->top_samples_available & 0x8000)) {
95 for (i = 0; i < 4; i++) {
96 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
98 av_log(h->s.avctx, AV_LOG_ERROR,
99 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
100 status, s->mb_x, s->mb_y);
103 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
108 if ((h->left_samples_available & 0x8888) != 0x8888) {
109 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
110 for (i = 0; i < 4; i++)
111 if (!(h->left_samples_available & mask[i])) {
112 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
114 av_log(h->s.avctx, AV_LOG_ERROR,
115 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
116 status, s->mb_x, s->mb_y);
119 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
125 } // FIXME cleanup like ff_h264_check_intra_pred_mode
128 * Check if the top & left blocks are available if needed and
129 * change the dc mode so it only uses the available blocks.
131 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
133 MpegEncContext *const s = &h->s;
134 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
135 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
138 av_log(h->s.avctx, AV_LOG_ERROR,
139 "out of range intra chroma pred mode at %d %d\n",
144 if (!(h->top_samples_available & 0x8000)) {
147 av_log(h->s.avctx, AV_LOG_ERROR,
148 "top block unavailable for requested intra mode at %d %d\n",
154 if ((h->left_samples_available & 0x8080) != 0x8080) {
156 if (is_chroma && (h->left_samples_available & 0x8080)) {
157 // mad cow disease mode, aka MBAFF + constrained_intra_pred
158 mode = ALZHEIMER_DC_L0T_PRED8x8 +
159 (!(h->left_samples_available & 0x8000)) +
160 2 * (mode == DC_128_PRED8x8);
163 av_log(h->s.avctx, AV_LOG_ERROR,
164 "left block unavailable for requested intra mode at %d %d\n",
173 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
174 int *dst_length, int *consumed, int length)
180 // src[0]&0x80; // forbidden bit
181 h->nal_ref_idc = src[0] >> 5;
182 h->nal_unit_type = src[0] & 0x1F;
187 #define STARTCODE_TEST \
188 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
189 if (src[i + 2] != 3) { \
190 /* startcode, so we must be past the end */ \
195 #if HAVE_FAST_UNALIGNED
196 #define FIND_FIRST_ZERO \
197 if (i > 0 && !src[i]) \
202 for (i = 0; i + 1 < length; i += 9) {
203 if (!((~AV_RN64A(src + i) &
204 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
205 0x8000800080008080ULL))
212 for (i = 0; i + 1 < length; i += 5) {
213 if (!((~AV_RN32A(src + i) &
214 (AV_RN32A(src + i) - 0x01000101U)) &
223 for (i = 0; i + 1 < length; i += 2) {
226 if (i > 0 && src[i - 1] == 0)
232 if (i >= length - 1) { // no escaped 0
233 *dst_length = length;
234 *consumed = length + 1; // +1 for the header
238 // use second escape buffer for inter data
239 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
240 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
241 length + FF_INPUT_BUFFER_PADDING_SIZE);
242 dst = h->rbsp_buffer[bufidx];
249 while (si + 2 < length) {
250 // remove escapes (very rare 1:2^22)
251 if (src[si + 2] > 3) {
252 dst[di++] = src[si++];
253 dst[di++] = src[si++];
254 } else if (src[si] == 0 && src[si + 1] == 0) {
255 if (src[si + 2] == 3) { // escape
260 } else // next start code
264 dst[di++] = src[si++];
267 dst[di++] = src[si++];
270 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
273 *consumed = si + 1; // +1 for the header
274 /* FIXME store exact number of bits in the getbitcontext
275 * (it is needed for decoding) */
280 * Identify the exact end of the bitstream
281 * @return the length of the trailing, or 0 if damaged
283 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
288 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
290 for (r = 1; r < 9; r++) {
298 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
299 int height, int y_offset, int list)
301 int raw_my = h->mv_cache[list][scan8[n]][1];
302 int filter_height_up = (raw_my & 3) ? 2 : 0;
303 int filter_height_down = (raw_my & 3) ? 3 : 0;
304 int full_my = (raw_my >> 2) + y_offset;
305 int top = full_my - filter_height_up;
306 int bottom = full_my + filter_height_down + height;
308 return FFMAX(abs(top), bottom);
311 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
312 int height, int y_offset, int list0,
313 int list1, int *nrefs)
315 MpegEncContext *const s = &h->s;
318 y_offset += 16 * (s->mb_y >> MB_FIELD);
321 int ref_n = h->ref_cache[0][scan8[n]];
322 Picture *ref = &h->ref_list[0][ref_n];
324 // Error resilience puts the current picture in the ref list.
325 // Don't try to wait on these as it will cause a deadlock.
326 // Fields can wait on each other, though.
327 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
328 (ref->f.reference & 3) != s->picture_structure) {
329 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
330 if (refs[0][ref_n] < 0)
332 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
337 int ref_n = h->ref_cache[1][scan8[n]];
338 Picture *ref = &h->ref_list[1][ref_n];
340 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
341 (ref->f.reference & 3) != s->picture_structure) {
342 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
343 if (refs[1][ref_n] < 0)
345 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
351 * Wait until all reference frames are available for MC operations.
353 * @param h the H264 context
355 static void await_references(H264Context *h)
357 MpegEncContext *const s = &h->s;
358 const int mb_xy = h->mb_xy;
359 const int mb_type = s->current_picture.f.mb_type[mb_xy];
361 int nrefs[2] = { 0 };
364 memset(refs, -1, sizeof(refs));
366 if (IS_16X16(mb_type)) {
367 get_lowest_part_y(h, refs, 0, 16, 0,
368 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
369 } else if (IS_16X8(mb_type)) {
370 get_lowest_part_y(h, refs, 0, 8, 0,
371 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
372 get_lowest_part_y(h, refs, 8, 8, 8,
373 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
374 } else if (IS_8X16(mb_type)) {
375 get_lowest_part_y(h, refs, 0, 16, 0,
376 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
377 get_lowest_part_y(h, refs, 4, 16, 0,
378 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
382 assert(IS_8X8(mb_type));
384 for (i = 0; i < 4; i++) {
385 const int sub_mb_type = h->sub_mb_type[i];
387 int y_offset = (i & 2) << 2;
389 if (IS_SUB_8X8(sub_mb_type)) {
390 get_lowest_part_y(h, refs, n, 8, y_offset,
391 IS_DIR(sub_mb_type, 0, 0),
392 IS_DIR(sub_mb_type, 0, 1),
394 } else if (IS_SUB_8X4(sub_mb_type)) {
395 get_lowest_part_y(h, refs, n, 4, y_offset,
396 IS_DIR(sub_mb_type, 0, 0),
397 IS_DIR(sub_mb_type, 0, 1),
399 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
400 IS_DIR(sub_mb_type, 0, 0),
401 IS_DIR(sub_mb_type, 0, 1),
403 } else if (IS_SUB_4X8(sub_mb_type)) {
404 get_lowest_part_y(h, refs, n, 8, y_offset,
405 IS_DIR(sub_mb_type, 0, 0),
406 IS_DIR(sub_mb_type, 0, 1),
408 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
409 IS_DIR(sub_mb_type, 0, 0),
410 IS_DIR(sub_mb_type, 0, 1),
414 assert(IS_SUB_4X4(sub_mb_type));
415 for (j = 0; j < 4; j++) {
416 int sub_y_offset = y_offset + 2 * (j & 2);
417 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
418 IS_DIR(sub_mb_type, 0, 0),
419 IS_DIR(sub_mb_type, 0, 1),
426 for (list = h->list_count - 1; list >= 0; list--)
427 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
428 int row = refs[list][ref];
430 Picture *ref_pic = &h->ref_list[list][ref];
431 int ref_field = ref_pic->f.reference - 1;
432 int ref_field_picture = ref_pic->field_picture;
433 int pic_height = 16 * s->mb_height >> ref_field_picture;
438 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
439 ff_thread_await_progress(&ref_pic->f,
440 FFMIN((row >> 1) - !(row & 1),
443 ff_thread_await_progress(&ref_pic->f,
444 FFMIN((row >> 1), pic_height - 1),
446 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
447 ff_thread_await_progress(&ref_pic->f,
448 FFMIN(row * 2 + ref_field,
451 } else if (FIELD_PICTURE) {
452 ff_thread_await_progress(&ref_pic->f,
453 FFMIN(row, pic_height - 1),
456 ff_thread_await_progress(&ref_pic->f,
457 FFMIN(row, pic_height - 1),
464 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
465 int n, int square, int height,
467 uint8_t *dest_y, uint8_t *dest_cb,
469 int src_x_offset, int src_y_offset,
470 qpel_mc_func *qpix_op,
471 h264_chroma_mc_func chroma_op,
472 int pixel_shift, int chroma_idc)
474 MpegEncContext *const s = &h->s;
475 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
476 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
477 const int luma_xy = (mx & 3) + ((my & 3) << 2);
478 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
479 uint8_t *src_y = pic->f.data[0] + offset;
480 uint8_t *src_cb, *src_cr;
481 int extra_width = h->emu_edge_width;
482 int extra_height = h->emu_edge_height;
484 const int full_mx = mx >> 2;
485 const int full_my = my >> 2;
486 const int pic_width = 16 * s->mb_width;
487 const int pic_height = 16 * s->mb_height >> MB_FIELD;
495 if (full_mx < 0 - extra_width ||
496 full_my < 0 - extra_height ||
497 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
498 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
499 s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
500 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
502 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
503 full_my - 2, pic_width, pic_height);
504 src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
508 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
510 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
512 if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
515 if (chroma_idc == 3 /* yuv444 */) {
516 src_cb = pic->f.data[1] + offset;
518 s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
519 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
521 16 + 5, 16 + 5 /*FIXME*/,
522 full_mx - 2, full_my - 2,
523 pic_width, pic_height);
524 src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
526 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
528 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
530 src_cr = pic->f.data[2] + offset;
532 s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
533 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
535 16 + 5, 16 + 5 /*FIXME*/,
536 full_mx - 2, full_my - 2,
537 pic_width, pic_height);
538 src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
540 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
542 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
546 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
547 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
548 // chroma offset when predicting from a field of opposite parity
549 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
550 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
553 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
554 (my >> ysh) * h->mb_uvlinesize;
555 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
556 (my >> ysh) * h->mb_uvlinesize;
559 s->vdsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
560 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
561 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
562 src_cb = s->edge_emu_buffer;
564 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
565 height >> (chroma_idc == 1 /* yuv420 */),
566 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
569 s->vdsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
570 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
571 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
572 src_cr = s->edge_emu_buffer;
574 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
575 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
578 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
579 int height, int delta,
580 uint8_t *dest_y, uint8_t *dest_cb,
582 int x_offset, int y_offset,
583 qpel_mc_func *qpix_put,
584 h264_chroma_mc_func chroma_put,
585 qpel_mc_func *qpix_avg,
586 h264_chroma_mc_func chroma_avg,
587 int list0, int list1,
588 int pixel_shift, int chroma_idc)
590 MpegEncContext *const s = &h->s;
591 qpel_mc_func *qpix_op = qpix_put;
592 h264_chroma_mc_func chroma_op = chroma_put;
594 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
595 if (chroma_idc == 3 /* yuv444 */) {
596 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
597 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
598 } else if (chroma_idc == 2 /* yuv422 */) {
599 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
600 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
601 } else { /* yuv420 */
602 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
603 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
605 x_offset += 8 * s->mb_x;
606 y_offset += 8 * (s->mb_y >> MB_FIELD);
609 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
610 mc_dir_part(h, ref, n, square, height, delta, 0,
611 dest_y, dest_cb, dest_cr, x_offset, y_offset,
612 qpix_op, chroma_op, pixel_shift, chroma_idc);
615 chroma_op = chroma_avg;
619 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
620 mc_dir_part(h, ref, n, square, height, delta, 1,
621 dest_y, dest_cb, dest_cr, x_offset, y_offset,
622 qpix_op, chroma_op, pixel_shift, chroma_idc);
626 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
627 int height, int delta,
628 uint8_t *dest_y, uint8_t *dest_cb,
630 int x_offset, int y_offset,
631 qpel_mc_func *qpix_put,
632 h264_chroma_mc_func chroma_put,
633 h264_weight_func luma_weight_op,
634 h264_weight_func chroma_weight_op,
635 h264_biweight_func luma_weight_avg,
636 h264_biweight_func chroma_weight_avg,
637 int list0, int list1,
638 int pixel_shift, int chroma_idc)
640 MpegEncContext *const s = &h->s;
643 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
644 if (chroma_idc == 3 /* yuv444 */) {
645 chroma_height = height;
646 chroma_weight_avg = luma_weight_avg;
647 chroma_weight_op = luma_weight_op;
648 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
649 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
650 } else if (chroma_idc == 2 /* yuv422 */) {
651 chroma_height = height;
652 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
653 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
654 } else { /* yuv420 */
655 chroma_height = height >> 1;
656 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
657 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
659 x_offset += 8 * s->mb_x;
660 y_offset += 8 * (s->mb_y >> MB_FIELD);
662 if (list0 && list1) {
663 /* don't optimize for luma-only case, since B-frames usually
664 * use implicit weights => chroma too. */
665 uint8_t *tmp_cb = h->bipred_scratchpad;
666 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
667 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
668 int refn0 = h->ref_cache[0][scan8[n]];
669 int refn1 = h->ref_cache[1][scan8[n]];
671 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
672 dest_y, dest_cb, dest_cr,
673 x_offset, y_offset, qpix_put, chroma_put,
674 pixel_shift, chroma_idc);
675 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
676 tmp_y, tmp_cb, tmp_cr,
677 x_offset, y_offset, qpix_put, chroma_put,
678 pixel_shift, chroma_idc);
680 if (h->use_weight == 2) {
681 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
682 int weight1 = 64 - weight0;
683 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
684 height, 5, weight0, weight1, 0);
685 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
686 chroma_height, 5, weight0, weight1, 0);
687 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
688 chroma_height, 5, weight0, weight1, 0);
690 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
691 h->luma_log2_weight_denom,
692 h->luma_weight[refn0][0][0],
693 h->luma_weight[refn1][1][0],
694 h->luma_weight[refn0][0][1] +
695 h->luma_weight[refn1][1][1]);
696 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
697 h->chroma_log2_weight_denom,
698 h->chroma_weight[refn0][0][0][0],
699 h->chroma_weight[refn1][1][0][0],
700 h->chroma_weight[refn0][0][0][1] +
701 h->chroma_weight[refn1][1][0][1]);
702 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
703 h->chroma_log2_weight_denom,
704 h->chroma_weight[refn0][0][1][0],
705 h->chroma_weight[refn1][1][1][0],
706 h->chroma_weight[refn0][0][1][1] +
707 h->chroma_weight[refn1][1][1][1]);
710 int list = list1 ? 1 : 0;
711 int refn = h->ref_cache[list][scan8[n]];
712 Picture *ref = &h->ref_list[list][refn];
713 mc_dir_part(h, ref, n, square, height, delta, list,
714 dest_y, dest_cb, dest_cr, x_offset, y_offset,
715 qpix_put, chroma_put, pixel_shift, chroma_idc);
717 luma_weight_op(dest_y, h->mb_linesize, height,
718 h->luma_log2_weight_denom,
719 h->luma_weight[refn][list][0],
720 h->luma_weight[refn][list][1]);
721 if (h->use_weight_chroma) {
722 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
723 h->chroma_log2_weight_denom,
724 h->chroma_weight[refn][list][0][0],
725 h->chroma_weight[refn][list][0][1]);
726 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
727 h->chroma_log2_weight_denom,
728 h->chroma_weight[refn][list][1][0],
729 h->chroma_weight[refn][list][1][1]);
734 static av_always_inline void prefetch_motion(H264Context *h, int list,
735 int pixel_shift, int chroma_idc)
737 /* fetch pixels for estimated mv 4 macroblocks ahead
738 * optimized for 64byte cache lines */
739 MpegEncContext *const s = &h->s;
740 const int refn = h->ref_cache[list][scan8[0]];
742 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
743 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
744 uint8_t **src = h->ref_list[list][refn].f.data;
745 int off = (mx << pixel_shift) +
746 (my + (s->mb_x & 3) * 4) * h->mb_linesize +
748 s->vdsp.prefetch(src[0] + off, s->linesize, 4);
749 if (chroma_idc == 3 /* yuv444 */) {
750 s->vdsp.prefetch(src[1] + off, s->linesize, 4);
751 s->vdsp.prefetch(src[2] + off, s->linesize, 4);
753 off = ((mx >> 1) << pixel_shift) +
754 ((my >> 1) + (s->mb_x & 7)) * s->uvlinesize +
756 s->vdsp.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->bipred_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 = s->mb_stride * 2 * s->avctx->thread_count;
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 if (!h->dequant4_coeff[0])
912 init_dequant_tables(h);
922 * Mimic alloc_tables(), but for every context thread.
924 static void clone_tables(H264Context *dst, H264Context *src, int i)
926 MpegEncContext *const s = &src->s;
927 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
928 dst->non_zero_count = src->non_zero_count;
929 dst->slice_table = src->slice_table;
930 dst->cbp_table = src->cbp_table;
931 dst->mb2b_xy = src->mb2b_xy;
932 dst->mb2br_xy = src->mb2br_xy;
933 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
934 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
935 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
936 dst->direct_table = src->direct_table;
937 dst->list_counts = src->list_counts;
938 dst->bipred_scratchpad = NULL;
939 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
940 src->sps.chroma_format_idc);
945 * Allocate buffers which are not shared amongst multiple threads.
947 static int context_init(H264Context *h)
949 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
950 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
951 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
952 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
954 h->ref_cache[0][scan8[5] + 1] =
955 h->ref_cache[0][scan8[7] + 1] =
956 h->ref_cache[0][scan8[13] + 1] =
957 h->ref_cache[1][scan8[5] + 1] =
958 h->ref_cache[1][scan8[7] + 1] =
959 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
964 return -1; // free_tables will clean up for us
967 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
968 int parse_extradata);
970 static av_cold void common_init(H264Context *h)
972 MpegEncContext *const s = &h->s;
974 s->width = s->avctx->width;
975 s->height = s->avctx->height;
976 s->codec_id = s->avctx->codec->id;
978 ff_h264dsp_init(&h->h264dsp, 8, 1);
979 ff_h264qpel_init(&h->h264qpel, 8);
980 ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);
982 h->dequant_coeff_pps = -1;
983 s->unrestricted_mv = 1;
985 /* needed so that IDCT permutation is known early */
986 ff_dsputil_init(&s->dsp, s->avctx);
987 ff_videodsp_init(&s->vdsp, 8);
989 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
990 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
993 int ff_h264_decode_extradata(H264Context *h)
995 AVCodecContext *avctx = h->s.avctx;
997 if (avctx->extradata[0] == 1) {
999 unsigned char *p = avctx->extradata;
1003 if (avctx->extradata_size < 7) {
1004 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1007 /* sps and pps in the avcC always have length coded with 2 bytes,
1008 * so put a fake nal_length_size = 2 while parsing them */
1009 h->nal_length_size = 2;
1010 // Decode sps from avcC
1011 cnt = *(p + 5) & 0x1f; // Number of sps
1013 for (i = 0; i < cnt; i++) {
1014 nalsize = AV_RB16(p) + 2;
1015 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1017 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1018 av_log(avctx, AV_LOG_ERROR,
1019 "Decoding sps %d from avcC failed\n", i);
1024 // Decode pps from avcC
1025 cnt = *(p++); // Number of pps
1026 for (i = 0; i < cnt; i++) {
1027 nalsize = AV_RB16(p) + 2;
1028 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1030 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1031 av_log(avctx, AV_LOG_ERROR,
1032 "Decoding pps %d from avcC failed\n", i);
1037 // Now store right nal length size, that will be used to parse all other nals
1038 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1041 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1) < 0)
1047 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1049 H264Context *h = avctx->priv_data;
1050 MpegEncContext *const s = &h->s;
1053 ff_MPV_decode_defaults(s);
1058 s->out_format = FMT_H264;
1059 s->workaround_bugs = avctx->workaround_bugs;
1062 // s->decode_mb = ff_h263_decode_mb;
1063 s->quarter_sample = 1;
1064 if (!avctx->has_b_frames)
1067 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1069 ff_h264_decode_init_vlc();
1072 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1074 h->thread_context[0] = h;
1075 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1076 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1077 h->last_pocs[i] = INT_MIN;
1078 h->prev_poc_msb = 1 << 16;
1080 ff_h264_reset_sei(h);
1081 if (avctx->codec_id == AV_CODEC_ID_H264) {
1082 if (avctx->ticks_per_frame == 1)
1083 s->avctx->time_base.den *= 2;
1084 avctx->ticks_per_frame = 2;
1087 if (avctx->extradata_size > 0 && avctx->extradata &&
1088 ff_h264_decode_extradata(h))
1091 if (h->sps.bitstream_restriction_flag &&
1092 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1093 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1100 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1102 static void copy_picture_range(Picture **to, Picture **from, int count,
1103 MpegEncContext *new_base,
1104 MpegEncContext *old_base)
1108 for (i = 0; i < count; i++) {
1109 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1110 IN_RANGE(from[i], old_base->picture,
1111 sizeof(Picture) * old_base->picture_count) ||
1113 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1117 static void copy_parameter_set(void **to, void **from, int count, int size)
1121 for (i = 0; i < count; i++) {
1122 if (to[i] && !from[i])
1124 else if (from[i] && !to[i])
1125 to[i] = av_malloc(size);
1128 memcpy(to[i], from[i], size);
1132 static int decode_init_thread_copy(AVCodecContext *avctx)
1134 H264Context *h = avctx->priv_data;
1136 if (!avctx->internal->is_copy)
1138 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1139 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1141 h->s.context_initialized = 0;
1146 #define copy_fields(to, from, start_field, end_field) \
1147 memcpy(&to->start_field, &from->start_field, \
1148 (char *)&to->end_field - (char *)&to->start_field)
1150 static int h264_slice_header_init(H264Context *, int);
1152 static int h264_set_parameter_from_sps(H264Context *h);
1154 static int decode_update_thread_context(AVCodecContext *dst,
1155 const AVCodecContext *src)
1157 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1158 MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1159 int inited = s->context_initialized, err;
1162 if (dst == src || !s1->context_initialized)
1166 (s->width != s1->width ||
1167 s->height != s1->height ||
1168 s->mb_width != s1->mb_width ||
1169 s->mb_height != s1->mb_height ||
1170 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1171 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1172 h->sps.colorspace != h1->sps.colorspace)) {
1174 av_freep(&h->bipred_scratchpad);
1176 s->width = s1->width;
1177 s->height = s1->height;
1178 s->mb_height = s1->mb_height;
1179 h->b_stride = h1->b_stride;
1181 if ((err = h264_slice_header_init(h, 1)) < 0) {
1182 av_log(h->s.avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1185 h->context_reinitialized = 1;
1187 /* update linesize on resize for h264. The h264 decoder doesn't
1188 * necessarily call ff_MPV_frame_start in the new thread */
1189 s->linesize = s1->linesize;
1190 s->uvlinesize = s1->uvlinesize;
1192 /* copy block_offset since frame_start may not be called */
1193 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1194 h264_set_parameter_from_sps(h);
1197 err = ff_mpeg_update_thread_context(dst, src);
1202 for (i = 0; i < MAX_SPS_COUNT; i++)
1203 av_freep(h->sps_buffers + i);
1205 for (i = 0; i < MAX_PPS_COUNT; i++)
1206 av_freep(h->pps_buffers + i);
1208 // copy all fields after MpegEnc
1209 memcpy(&h->s + 1, &h1->s + 1,
1210 sizeof(H264Context) - sizeof(MpegEncContext));
1211 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1212 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1213 if (ff_h264_alloc_tables(h) < 0) {
1214 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1215 return AVERROR(ENOMEM);
1219 for (i = 0; i < 2; i++) {
1220 h->rbsp_buffer[i] = NULL;
1221 h->rbsp_buffer_size[i] = 0;
1223 h->bipred_scratchpad = NULL;
1225 h->thread_context[0] = h;
1227 s->dsp.clear_blocks(h->mb);
1228 s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1231 /* frame_start may not be called for the next thread (if it's decoding
1232 * a bottom field) so this has to be allocated here */
1233 if (!h->bipred_scratchpad)
1234 h->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
1236 // extradata/NAL handling
1237 h->is_avc = h1->is_avc;
1240 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1241 MAX_SPS_COUNT, sizeof(SPS));
1243 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1244 MAX_PPS_COUNT, sizeof(PPS));
1247 // Dequantization matrices
1248 // FIXME these are big - can they be only copied when PPS changes?
1249 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1251 for (i = 0; i < 6; i++)
1252 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1253 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1255 for (i = 0; i < 6; i++)
1256 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1257 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1259 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1262 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1265 copy_fields(h, h1, ref_count, list_count);
1266 copy_fields(h, h1, ref2frm, intra_gb);
1267 copy_fields(h, h1, short_ref, cabac_init_idc);
1269 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1270 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1271 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1272 MAX_DELAYED_PIC_COUNT + 2, s, s1);
1274 h->last_slice_type = h1->last_slice_type;
1276 if (!s->current_picture_ptr)
1279 if (!s->droppable) {
1280 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1281 h->prev_poc_msb = h->poc_msb;
1282 h->prev_poc_lsb = h->poc_lsb;
1284 h->prev_frame_num_offset = h->frame_num_offset;
1285 h->prev_frame_num = h->frame_num;
1286 h->outputed_poc = h->next_outputed_poc;
1291 int ff_h264_frame_start(H264Context *h)
1293 MpegEncContext *const s = &h->s;
1295 const int pixel_shift = h->pixel_shift;
1297 if (ff_MPV_frame_start(s, s->avctx) < 0)
1299 ff_er_frame_start(s);
1301 * ff_MPV_frame_start uses pict_type to derive key_frame.
1302 * This is incorrect for H.264; IDR markings must be used.
1303 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1304 * See decode_nal_units().
1306 s->current_picture_ptr->f.key_frame = 0;
1307 s->current_picture_ptr->mmco_reset = 0;
1309 assert(s->linesize && s->uvlinesize);
1311 for (i = 0; i < 16; i++) {
1312 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1313 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1315 for (i = 0; i < 16; i++) {
1316 h->block_offset[16 + i] =
1317 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1318 h->block_offset[48 + 16 + i] =
1319 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1322 /* can't be in alloc_tables because linesize isn't known there.
1323 * FIXME: redo bipred weight to not require extra buffer? */
1324 for (i = 0; i < s->slice_context_count; i++)
1325 if (h->thread_context[i] && !h->thread_context[i]->bipred_scratchpad)
1326 h->thread_context[i]->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
1328 /* Some macroblocks can be accessed before they're available in case
1329 * of lost slices, MBAFF or threading. */
1330 memset(h->slice_table, -1,
1331 (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1333 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1334 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1336 /* We mark the current picture as non-reference after allocating it, so
1337 * that if we break out due to an error it can be released automatically
1338 * in the next ff_MPV_frame_start().
1339 * SVQ3 as well as most other codecs have only last/next/current and thus
1340 * get released even with set reference, besides SVQ3 and others do not
1341 * mark frames as reference later "naturally". */
1342 if (s->codec_id != AV_CODEC_ID_SVQ3)
1343 s->current_picture_ptr->f.reference = 0;
1345 s->current_picture_ptr->field_poc[0] =
1346 s->current_picture_ptr->field_poc[1] = INT_MAX;
1348 h->next_output_pic = NULL;
1350 assert(s->current_picture_ptr->long_ref == 0);
1356 * Run setup operations that must be run after slice header decoding.
1357 * This includes finding the next displayed frame.
1359 * @param h h264 master context
1360 * @param setup_finished enough NALs have been read that we can call
1361 * ff_thread_finish_setup()
1363 static void decode_postinit(H264Context *h, int setup_finished)
1365 MpegEncContext *const s = &h->s;
1366 Picture *out = s->current_picture_ptr;
1367 Picture *cur = s->current_picture_ptr;
1368 int i, pics, out_of_order, out_idx;
1369 int invalid = 0, cnt = 0;
1371 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1372 s->current_picture_ptr->f.pict_type = s->pict_type;
1374 if (h->next_output_pic)
1377 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1378 /* FIXME: if we have two PAFF fields in one packet, we can't start
1379 * the next thread here. If we have one field per packet, we can.
1380 * The check in decode_nal_units() is not good enough to find this
1381 * yet, so we assume the worst for now. */
1382 // if (setup_finished)
1383 // ff_thread_finish_setup(s->avctx);
1387 cur->f.interlaced_frame = 0;
1388 cur->f.repeat_pict = 0;
1390 /* Signal interlacing information externally. */
1391 /* Prioritize picture timing SEI information over used
1392 * decoding process if it exists. */
1394 if (h->sps.pic_struct_present_flag) {
1395 switch (h->sei_pic_struct) {
1396 case SEI_PIC_STRUCT_FRAME:
1398 case SEI_PIC_STRUCT_TOP_FIELD:
1399 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1400 cur->f.interlaced_frame = 1;
1402 case SEI_PIC_STRUCT_TOP_BOTTOM:
1403 case SEI_PIC_STRUCT_BOTTOM_TOP:
1404 if (FIELD_OR_MBAFF_PICTURE)
1405 cur->f.interlaced_frame = 1;
1407 // try to flag soft telecine progressive
1408 cur->f.interlaced_frame = h->prev_interlaced_frame;
1410 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1411 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1412 /* Signal the possibility of telecined film externally
1413 * (pic_struct 5,6). From these hints, let the applications
1414 * decide if they apply deinterlacing. */
1415 cur->f.repeat_pict = 1;
1417 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1418 // Force progressive here, doubling interlaced frame is a bad idea.
1419 cur->f.repeat_pict = 2;
1421 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1422 cur->f.repeat_pict = 4;
1426 if ((h->sei_ct_type & 3) &&
1427 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1428 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1430 /* Derive interlacing flag from used decoding process. */
1431 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1433 h->prev_interlaced_frame = cur->f.interlaced_frame;
1435 if (cur->field_poc[0] != cur->field_poc[1]) {
1436 /* Derive top_field_first from field pocs. */
1437 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1439 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1440 /* Use picture timing SEI information. Even if it is a
1441 * information of a past frame, better than nothing. */
1442 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1443 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1444 cur->f.top_field_first = 1;
1446 cur->f.top_field_first = 0;
1448 /* Most likely progressive */
1449 cur->f.top_field_first = 0;
1453 // FIXME do something with unavailable reference frames
1455 /* Sort B-frames into display order */
1457 if (h->sps.bitstream_restriction_flag &&
1458 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1459 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1463 if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1464 !h->sps.bitstream_restriction_flag) {
1465 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1470 while (h->delayed_pic[pics])
1473 assert(pics <= MAX_DELAYED_PIC_COUNT);
1475 h->delayed_pic[pics++] = cur;
1476 if (cur->f.reference == 0)
1477 cur->f.reference = DELAYED_PIC_REF;
1479 /* Frame reordering. This code takes pictures from coding order and sorts
1480 * them by their incremental POC value into display order. It supports POC
1481 * gaps, MMCO reset codes and random resets.
1482 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1483 * and/or can be closed down with a MMCO reset code. In sequences where
1484 * there is no delay, we can't detect that (since the frame was already
1485 * output to the user), so we also set h->mmco_reset to detect the MMCO
1487 * FIXME: if we detect insufficient delays (as per s->avctx->has_b_frames),
1488 * we increase the delay between input and output. All frames affected by
1489 * the lag (e.g. those that should have been output before another frame
1490 * that we already returned to the user) will be dropped. This is a bug
1491 * that we will fix later. */
1492 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1493 cnt += out->poc < h->last_pocs[i];
1494 invalid += out->poc == INT_MIN;
1496 if (!h->mmco_reset && !cur->f.key_frame &&
1497 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1500 h->delayed_pic[pics - 2]->mmco_reset = 2;
1502 if (h->mmco_reset || cur->f.key_frame) {
1503 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1504 h->last_pocs[i] = INT_MIN;
1506 invalid = MAX_DELAYED_PIC_COUNT;
1508 out = h->delayed_pic[0];
1510 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1511 h->delayed_pic[i] &&
1512 !h->delayed_pic[i - 1]->mmco_reset &&
1513 !h->delayed_pic[i]->f.key_frame;
1515 if (h->delayed_pic[i]->poc < out->poc) {
1516 out = h->delayed_pic[i];
1519 if (s->avctx->has_b_frames == 0 &&
1520 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
1521 h->next_outputed_poc = INT_MIN;
1522 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1523 (out->poc < h->next_outputed_poc);
1525 if (h->sps.bitstream_restriction_flag &&
1526 s->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1527 } else if (out_of_order && pics - 1 == s->avctx->has_b_frames &&
1528 s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1529 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1530 s->avctx->has_b_frames = FFMAX(s->avctx->has_b_frames, cnt);
1533 } else if (s->low_delay &&
1534 ((h->next_outputed_poc != INT_MIN &&
1535 out->poc > h->next_outputed_poc + 2) ||
1536 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
1538 s->avctx->has_b_frames++;
1541 if (pics > s->avctx->has_b_frames) {
1542 out->f.reference &= ~DELAYED_PIC_REF;
1543 // for frame threading, the owner must be the second field's thread or
1544 // else the first thread can release the picture and reuse it unsafely
1546 for (i = out_idx; h->delayed_pic[i]; i++)
1547 h->delayed_pic[i] = h->delayed_pic[i + 1];
1549 memmove(h->last_pocs, &h->last_pocs[1],
1550 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1551 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1552 if (!out_of_order && pics > s->avctx->has_b_frames) {
1553 h->next_output_pic = out;
1554 if (out->mmco_reset) {
1556 h->next_outputed_poc = out->poc;
1557 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1559 h->next_outputed_poc = INT_MIN;
1562 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
1563 h->next_outputed_poc = INT_MIN;
1565 h->next_outputed_poc = out->poc;
1570 av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1574 ff_thread_finish_setup(s->avctx);
1577 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1578 uint8_t *src_cb, uint8_t *src_cr,
1579 int linesize, int uvlinesize,
1582 MpegEncContext *const s = &h->s;
1583 uint8_t *top_border;
1585 const int pixel_shift = h->pixel_shift;
1586 int chroma444 = CHROMA444;
1587 int chroma422 = CHROMA422;
1590 src_cb -= uvlinesize;
1591 src_cr -= uvlinesize;
1593 if (!simple && FRAME_MBAFF) {
1596 top_border = h->top_borders[0][s->mb_x];
1597 AV_COPY128(top_border, src_y + 15 * linesize);
1599 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1600 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1603 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1604 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1605 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1606 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1608 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1609 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1611 } else if (chroma422) {
1613 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1614 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1616 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1617 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1621 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1622 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1624 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1625 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1630 } else if (MB_MBAFF) {
1636 top_border = h->top_borders[top_idx][s->mb_x];
1637 /* There are two lines saved, the line above the top macroblock
1638 * of a pair, and the line above the bottom macroblock. */
1639 AV_COPY128(top_border, src_y + 16 * linesize);
1641 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1643 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1646 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1647 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1648 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1649 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1651 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1652 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1654 } else if (chroma422) {
1656 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1657 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1659 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1660 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1664 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1665 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1667 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1668 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1674 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1675 uint8_t *src_cb, uint8_t *src_cr,
1676 int linesize, int uvlinesize,
1677 int xchg, int chroma444,
1678 int simple, int pixel_shift)
1680 MpegEncContext *const s = &h->s;
1681 int deblock_topleft;
1684 uint8_t *top_border_m1;
1685 uint8_t *top_border;
1687 if (!simple && FRAME_MBAFF) {
1692 top_idx = MB_MBAFF ? 0 : 1;
1696 if (h->deblocking_filter == 2) {
1697 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1698 deblock_top = h->top_type;
1700 deblock_topleft = (s->mb_x > 0);
1701 deblock_top = (s->mb_y > !!MB_FIELD);
1704 src_y -= linesize + 1 + pixel_shift;
1705 src_cb -= uvlinesize + 1 + pixel_shift;
1706 src_cr -= uvlinesize + 1 + pixel_shift;
1708 top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1709 top_border = h->top_borders[top_idx][s->mb_x];
1711 #define XCHG(a, b, xchg) \
1712 if (pixel_shift) { \
1714 AV_SWAP64(b + 0, a + 0); \
1715 AV_SWAP64(b + 8, a + 8); \
1725 if (deblock_topleft) {
1726 XCHG(top_border_m1 + (8 << pixel_shift),
1727 src_y - (7 << pixel_shift), 1);
1729 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1730 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1731 if (s->mb_x + 1 < s->mb_width) {
1732 XCHG(h->top_borders[top_idx][s->mb_x + 1],
1733 src_y + (17 << pixel_shift), 1);
1736 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1738 if (deblock_topleft) {
1739 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1740 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1742 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1743 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1744 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1745 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1746 if (s->mb_x + 1 < s->mb_width) {
1747 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1748 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1752 if (deblock_topleft) {
1753 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1754 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1756 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1757 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1763 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
1766 if (high_bit_depth) {
1767 return AV_RN32A(((int32_t *)mb) + index);
1769 return AV_RN16A(mb + index);
1772 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
1773 int index, int value)
1775 if (high_bit_depth) {
1776 AV_WN32A(((int32_t *)mb) + index, value);
1778 AV_WN16A(mb + index, value);
1781 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1782 int mb_type, int is_h264,
1784 int transform_bypass,
1788 uint8_t *dest_y, int p)
1790 MpegEncContext *const s = &h->s;
1791 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
1792 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
1794 int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1795 block_offset += 16 * p;
1796 if (IS_INTRA4x4(mb_type)) {
1797 if (simple || !s->encoding) {
1798 if (IS_8x8DCT(mb_type)) {
1799 if (transform_bypass) {
1801 idct_add = s->dsp.add_pixels8;
1803 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1804 idct_add = h->h264dsp.h264_idct8_add;
1806 for (i = 0; i < 16; i += 4) {
1807 uint8_t *const ptr = dest_y + block_offset[i];
1808 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1809 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1810 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1812 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1813 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1814 (h->topright_samples_available << i) & 0x4000, linesize);
1816 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1817 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1819 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1824 if (transform_bypass) {
1826 idct_add = s->dsp.add_pixels4;
1828 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1829 idct_add = h->h264dsp.h264_idct_add;
1831 for (i = 0; i < 16; i++) {
1832 uint8_t *const ptr = dest_y + block_offset[i];
1833 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1835 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1836 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1841 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1842 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1843 assert(s->mb_y || linesize <= block_offset[i]);
1844 if (!topright_avail) {
1846 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1847 topright = (uint8_t *)&tr_high;
1849 tr = ptr[3 - linesize] * 0x01010101u;
1850 topright = (uint8_t *)&tr;
1853 topright = ptr + (4 << pixel_shift) - linesize;
1857 h->hpc.pred4x4[dir](ptr, topright, linesize);
1858 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1861 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1862 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1864 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1865 } else if (CONFIG_SVQ3_DECODER)
1866 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1873 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1875 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1876 if (!transform_bypass)
1877 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1879 h->dequant4_coeff[p][qscale][0]);
1881 static const uint8_t dc_mapping[16] = {
1882 0 * 16, 1 * 16, 4 * 16, 5 * 16,
1883 2 * 16, 3 * 16, 6 * 16, 7 * 16,
1884 8 * 16, 9 * 16, 12 * 16, 13 * 16,
1885 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1886 for (i = 0; i < 16; i++)
1887 dctcoef_set(h->mb + (p * 256 << pixel_shift),
1888 pixel_shift, dc_mapping[i],
1889 dctcoef_get(h->mb_luma_dc[p],
1893 } else if (CONFIG_SVQ3_DECODER)
1894 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
1895 h->mb_luma_dc[p], qscale);
1899 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
1900 int is_h264, int simple,
1901 int transform_bypass,
1905 uint8_t *dest_y, int p)
1907 MpegEncContext *const s = &h->s;
1908 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
1910 block_offset += 16 * p;
1911 if (!IS_INTRA4x4(mb_type)) {
1913 if (IS_INTRA16x16(mb_type)) {
1914 if (transform_bypass) {
1915 if (h->sps.profile_idc == 244 &&
1916 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
1917 h->intra16x16_pred_mode == HOR_PRED8x8)) {
1918 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
1919 h->mb + (p * 256 << pixel_shift),
1922 for (i = 0; i < 16; i++)
1923 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
1924 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1925 s->dsp.add_pixels4(dest_y + block_offset[i],
1926 h->mb + (i * 16 + p * 256 << pixel_shift),
1930 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
1931 h->mb + (p * 256 << pixel_shift),
1933 h->non_zero_count_cache + p * 5 * 8);
1935 } else if (h->cbp & 15) {
1936 if (transform_bypass) {
1937 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1938 idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
1939 : s->dsp.add_pixels4;
1940 for (i = 0; i < 16; i += di)
1941 if (h->non_zero_count_cache[scan8[i + p * 16]])
1942 idct_add(dest_y + block_offset[i],
1943 h->mb + (i * 16 + p * 256 << pixel_shift),
1946 if (IS_8x8DCT(mb_type))
1947 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
1948 h->mb + (p * 256 << pixel_shift),
1950 h->non_zero_count_cache + p * 5 * 8);
1952 h->h264dsp.h264_idct_add16(dest_y, block_offset,
1953 h->mb + (p * 256 << pixel_shift),
1955 h->non_zero_count_cache + p * 5 * 8);
1958 } else if (CONFIG_SVQ3_DECODER) {
1959 for (i = 0; i < 16; i++)
1960 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
1961 // FIXME benchmark weird rule, & below
1962 uint8_t *const ptr = dest_y + block_offset[i];
1963 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
1964 s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1972 #include "h264_mb_template.c"
1976 #include "h264_mb_template.c"
1980 #include "h264_mb_template.c"
1982 void ff_h264_hl_decode_mb(H264Context *h)
1984 MpegEncContext *const s = &h->s;
1985 const int mb_xy = h->mb_xy;
1986 const int mb_type = s->current_picture.f.mb_type[mb_xy];
1987 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1990 if (is_complex || h->pixel_shift)
1991 hl_decode_mb_444_complex(h);
1993 hl_decode_mb_444_simple_8(h);
1994 } else if (is_complex) {
1995 hl_decode_mb_complex(h);
1996 } else if (h->pixel_shift) {
1997 hl_decode_mb_simple_16(h);
1999 hl_decode_mb_simple_8(h);
2002 static int pred_weight_table(H264Context *h)
2004 MpegEncContext *const s = &h->s;
2006 int luma_def, chroma_def;
2009 h->use_weight_chroma = 0;
2010 h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
2011 if (h->sps.chroma_format_idc)
2012 h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
2013 luma_def = 1 << h->luma_log2_weight_denom;
2014 chroma_def = 1 << h->chroma_log2_weight_denom;
2016 for (list = 0; list < 2; list++) {
2017 h->luma_weight_flag[list] = 0;
2018 h->chroma_weight_flag[list] = 0;
2019 for (i = 0; i < h->ref_count[list]; i++) {
2020 int luma_weight_flag, chroma_weight_flag;
2022 luma_weight_flag = get_bits1(&s->gb);
2023 if (luma_weight_flag) {
2024 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
2025 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
2026 if (h->luma_weight[i][list][0] != luma_def ||
2027 h->luma_weight[i][list][1] != 0) {
2029 h->luma_weight_flag[list] = 1;
2032 h->luma_weight[i][list][0] = luma_def;
2033 h->luma_weight[i][list][1] = 0;
2036 if (h->sps.chroma_format_idc) {
2037 chroma_weight_flag = get_bits1(&s->gb);
2038 if (chroma_weight_flag) {
2040 for (j = 0; j < 2; j++) {
2041 h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
2042 h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
2043 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2044 h->chroma_weight[i][list][j][1] != 0) {
2045 h->use_weight_chroma = 1;
2046 h->chroma_weight_flag[list] = 1;
2051 for (j = 0; j < 2; j++) {
2052 h->chroma_weight[i][list][j][0] = chroma_def;
2053 h->chroma_weight[i][list][j][1] = 0;
2058 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2061 h->use_weight = h->use_weight || h->use_weight_chroma;
2066 * Initialize implicit_weight table.
2067 * @param field 0/1 initialize the weight for interlaced MBAFF
2068 * -1 initializes the rest
2070 static void implicit_weight_table(H264Context *h, int field)
2072 MpegEncContext *const s = &h->s;
2073 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2075 for (i = 0; i < 2; i++) {
2076 h->luma_weight_flag[i] = 0;
2077 h->chroma_weight_flag[i] = 0;
2081 if (s->picture_structure == PICT_FRAME) {
2082 cur_poc = s->current_picture_ptr->poc;
2084 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2086 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2087 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2089 h->use_weight_chroma = 0;
2093 ref_count0 = h->ref_count[0];
2094 ref_count1 = h->ref_count[1];
2096 cur_poc = s->current_picture_ptr->field_poc[field];
2098 ref_count0 = 16 + 2 * h->ref_count[0];
2099 ref_count1 = 16 + 2 * h->ref_count[1];
2103 h->use_weight_chroma = 2;
2104 h->luma_log2_weight_denom = 5;
2105 h->chroma_log2_weight_denom = 5;
2107 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2108 int poc0 = h->ref_list[0][ref0].poc;
2109 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2111 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2112 int poc1 = h->ref_list[1][ref1].poc;
2113 int td = av_clip(poc1 - poc0, -128, 127);
2115 int tb = av_clip(cur_poc - poc0, -128, 127);
2116 int tx = (16384 + (FFABS(td) >> 1)) / td;
2117 int dist_scale_factor = (tb * tx + 32) >> 8;
2118 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2119 w = 64 - dist_scale_factor;
2123 h->implicit_weight[ref0][ref1][0] =
2124 h->implicit_weight[ref0][ref1][1] = w;
2126 h->implicit_weight[ref0][ref1][field] = w;
2133 * instantaneous decoder refresh.
2135 static void idr(H264Context *h)
2137 ff_h264_remove_all_refs(h);
2138 h->prev_frame_num = 0;
2139 h->prev_frame_num_offset = 0;
2141 h->prev_poc_lsb = 0;
2144 /* forget old pics after a seek */
2145 static void flush_change(H264Context *h)
2148 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2149 h->last_pocs[i] = INT_MIN;
2150 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2151 h->prev_interlaced_frame = 1;
2153 if (h->s.current_picture_ptr)
2154 h->s.current_picture_ptr->f.reference = 0;
2155 h->s.first_field = 0;
2156 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2157 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2158 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2159 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2160 ff_h264_reset_sei(h);
2163 /* forget old pics after a seek */
2164 static void flush_dpb(AVCodecContext *avctx)
2166 H264Context *h = avctx->priv_data;
2169 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2170 if (h->delayed_pic[i])
2171 h->delayed_pic[i]->f.reference = 0;
2172 h->delayed_pic[i] = NULL;
2176 ff_mpeg_flush(avctx);
2179 static int init_poc(H264Context *h)
2181 MpegEncContext *const s = &h->s;
2182 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2184 Picture *cur = s->current_picture_ptr;
2186 h->frame_num_offset = h->prev_frame_num_offset;
2187 if (h->frame_num < h->prev_frame_num)
2188 h->frame_num_offset += max_frame_num;
2190 if (h->sps.poc_type == 0) {
2191 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2193 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2194 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2195 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2196 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2198 h->poc_msb = h->prev_poc_msb;
2200 field_poc[1] = h->poc_msb + h->poc_lsb;
2201 if (s->picture_structure == PICT_FRAME)
2202 field_poc[1] += h->delta_poc_bottom;
2203 } else if (h->sps.poc_type == 1) {
2204 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2207 if (h->sps.poc_cycle_length != 0)
2208 abs_frame_num = h->frame_num_offset + h->frame_num;
2212 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2215 expected_delta_per_poc_cycle = 0;
2216 for (i = 0; i < h->sps.poc_cycle_length; i++)
2217 // FIXME integrate during sps parse
2218 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2220 if (abs_frame_num > 0) {
2221 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2222 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2224 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2225 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2226 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2230 if (h->nal_ref_idc == 0)
2231 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2233 field_poc[0] = expectedpoc + h->delta_poc[0];
2234 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2236 if (s->picture_structure == PICT_FRAME)
2237 field_poc[1] += h->delta_poc[1];
2239 int poc = 2 * (h->frame_num_offset + h->frame_num);
2241 if (!h->nal_ref_idc)
2248 if (s->picture_structure != PICT_BOTTOM_FIELD)
2249 s->current_picture_ptr->field_poc[0] = field_poc[0];
2250 if (s->picture_structure != PICT_TOP_FIELD)
2251 s->current_picture_ptr->field_poc[1] = field_poc[1];
2252 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2258 * initialize scan tables
2260 static void init_scan_tables(H264Context *h)
2263 for (i = 0; i < 16; i++) {
2264 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2265 h->zigzag_scan[i] = T(zigzag_scan[i]);
2266 h->field_scan[i] = T(field_scan[i]);
2269 for (i = 0; i < 64; i++) {
2270 #define T(x) (x >> 3) | ((x & 7) << 3)
2271 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2272 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2273 h->field_scan8x8[i] = T(field_scan8x8[i]);
2274 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2277 if (h->sps.transform_bypass) { // FIXME same ugly
2278 h->zigzag_scan_q0 = zigzag_scan;
2279 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2280 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2281 h->field_scan_q0 = field_scan;
2282 h->field_scan8x8_q0 = field_scan8x8;
2283 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2285 h->zigzag_scan_q0 = h->zigzag_scan;
2286 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2287 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2288 h->field_scan_q0 = h->field_scan;
2289 h->field_scan8x8_q0 = h->field_scan8x8;
2290 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2294 static int field_end(H264Context *h, int in_setup)
2296 MpegEncContext *const s = &h->s;
2297 AVCodecContext *const avctx = s->avctx;
2301 if (!in_setup && !s->droppable)
2302 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2303 s->picture_structure == PICT_BOTTOM_FIELD);
2305 if (CONFIG_H264_VDPAU_DECODER &&
2306 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2307 ff_vdpau_h264_set_reference_frames(s);
2309 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2310 if (!s->droppable) {
2311 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2312 h->prev_poc_msb = h->poc_msb;
2313 h->prev_poc_lsb = h->poc_lsb;
2315 h->prev_frame_num_offset = h->frame_num_offset;
2316 h->prev_frame_num = h->frame_num;
2317 h->outputed_poc = h->next_outputed_poc;
2320 if (avctx->hwaccel) {
2321 if (avctx->hwaccel->end_frame(avctx) < 0)
2322 av_log(avctx, AV_LOG_ERROR,
2323 "hardware accelerator failed to decode picture\n");
2326 if (CONFIG_H264_VDPAU_DECODER &&
2327 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2328 ff_vdpau_h264_picture_complete(s);
2331 * FIXME: Error handling code does not seem to support interlaced
2332 * when slices span multiple rows
2333 * The ff_er_add_slice calls don't work right for bottom
2334 * fields; they cause massive erroneous error concealing
2335 * Error marking covers both fields (top and bottom).
2336 * This causes a mismatched s->error_count
2337 * and a bad error table. Further, the error count goes to
2338 * INT_MAX when called for bottom field, because mb_y is
2339 * past end by one (callers fault) and resync_mb_y != 0
2340 * causes problems for the first MB line, too.
2345 ff_MPV_frame_end(s);
2347 h->current_slice = 0;
2353 * Replicate H264 "master" context to thread contexts.
2355 static int clone_slice(H264Context *dst, H264Context *src)
2359 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2360 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2361 dst->s.current_picture = src->s.current_picture;
2362 dst->s.linesize = src->s.linesize;
2363 dst->s.uvlinesize = src->s.uvlinesize;
2364 dst->s.first_field = src->s.first_field;
2366 if (!dst->s.edge_emu_buffer &&
2367 (ret = ff_mpv_frame_size_alloc(&dst->s, dst->s.linesize))) {
2368 av_log(dst->s.avctx, AV_LOG_ERROR,
2369 "Failed to allocate scratch buffers\n");
2373 dst->prev_poc_msb = src->prev_poc_msb;
2374 dst->prev_poc_lsb = src->prev_poc_lsb;
2375 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2376 dst->prev_frame_num = src->prev_frame_num;
2377 dst->short_ref_count = src->short_ref_count;
2379 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2380 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2381 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2383 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2384 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2390 * Compute profile from profile_idc and constraint_set?_flags.
2394 * @return profile as defined by FF_PROFILE_H264_*
2396 int ff_h264_get_profile(SPS *sps)
2398 int profile = sps->profile_idc;
2400 switch (sps->profile_idc) {
2401 case FF_PROFILE_H264_BASELINE:
2402 // constraint_set1_flag set to 1
2403 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2405 case FF_PROFILE_H264_HIGH_10:
2406 case FF_PROFILE_H264_HIGH_422:
2407 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2408 // constraint_set3_flag set to 1
2409 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2416 static int h264_set_parameter_from_sps(H264Context *h)
2418 MpegEncContext *s = &h->s;
2420 if (s->flags & CODEC_FLAG_LOW_DELAY ||
2421 (h->sps.bitstream_restriction_flag &&
2422 !h->sps.num_reorder_frames)) {
2423 if (s->avctx->has_b_frames > 1 || h->delayed_pic[0])
2424 av_log(h->s.avctx, AV_LOG_WARNING, "Delayed frames seen. "
2425 "Reenabling low delay requires a codec flush.\n");
2430 if (s->avctx->has_b_frames < 2)
2431 s->avctx->has_b_frames = !s->low_delay;
2433 if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2434 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2435 if (s->avctx->codec &&
2436 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2437 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2438 av_log(s->avctx, AV_LOG_ERROR,
2439 "VDPAU decoding does not support video colorspace.\n");
2440 return AVERROR_INVALIDDATA;
2442 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
2443 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2444 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2445 h->pixel_shift = h->sps.bit_depth_luma > 8;
2447 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2448 h->sps.chroma_format_idc);
2449 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2450 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma,
2451 h->sps.chroma_format_idc);
2452 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2453 ff_dsputil_init(&s->dsp, s->avctx);
2454 ff_videodsp_init(&s->vdsp, h->sps.bit_depth_luma);
2456 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2457 h->sps.bit_depth_luma);
2458 return AVERROR_INVALIDDATA;
2464 static enum PixelFormat get_pixel_format(H264Context *h)
2466 MpegEncContext *const s = &h->s;
2467 switch (h->sps.bit_depth_luma) {
2470 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2471 return AV_PIX_FMT_GBRP9;
2473 return AV_PIX_FMT_YUV444P9;
2474 } else if (CHROMA422)
2475 return AV_PIX_FMT_YUV422P9;
2477 return AV_PIX_FMT_YUV420P9;
2481 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2482 return AV_PIX_FMT_GBRP10;
2484 return AV_PIX_FMT_YUV444P10;
2485 } else if (CHROMA422)
2486 return AV_PIX_FMT_YUV422P10;
2488 return AV_PIX_FMT_YUV420P10;
2492 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2493 return AV_PIX_FMT_GBRP;
2495 return s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2496 : AV_PIX_FMT_YUV444P;
2497 } else if (CHROMA422) {
2498 return s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2499 : AV_PIX_FMT_YUV422P;
2501 return s->avctx->get_format(s->avctx, s->avctx->codec->pix_fmts ?
2502 s->avctx->codec->pix_fmts :
2503 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2504 hwaccel_pixfmt_list_h264_jpeg_420 :
2505 ff_hwaccel_pixfmt_list_420);
2509 av_log(s->avctx, AV_LOG_ERROR,
2510 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2511 return AVERROR_INVALIDDATA;
2515 static int h264_slice_header_init(H264Context *h, int reinit)
2517 MpegEncContext *const s = &h->s;
2520 avcodec_set_dimensions(s->avctx, s->width, s->height);
2521 s->avctx->sample_aspect_ratio = h->sps.sar;
2522 av_assert0(s->avctx->sample_aspect_ratio.den);
2524 if (h->sps.timing_info_present_flag) {
2525 int64_t den = h->sps.time_scale;
2526 if (h->x264_build < 44U)
2528 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2529 h->sps.num_units_in_tick, den, 1 << 30);
2532 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2536 if ((ret = ff_MPV_common_frame_size_change(s)) < 0) {
2537 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_frame_size_change() failed.\n");
2541 if ((ret = ff_MPV_common_init(s)) < 0) {
2542 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
2547 h->prev_interlaced_frame = 1;
2549 init_scan_tables(h);
2550 if (ff_h264_alloc_tables(h) < 0) {
2551 av_log(h->s.avctx, AV_LOG_ERROR,
2552 "Could not allocate memory for h264\n");
2553 return AVERROR(ENOMEM);
2556 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
2557 if (context_init(h) < 0) {
2558 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2562 for (i = 1; i < s->slice_context_count; i++) {
2564 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2565 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2566 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2567 c->h264dsp = h->h264dsp;
2568 c->h264qpel = h->h264qpel;
2571 c->pixel_shift = h->pixel_shift;
2572 init_scan_tables(c);
2573 clone_tables(c, h, i);
2576 for (i = 0; i < s->slice_context_count; i++)
2577 if (context_init(h->thread_context[i]) < 0) {
2578 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2587 * Decode a slice header.
2588 * This will also call ff_MPV_common_init() and frame_start() as needed.
2590 * @param h h264context
2591 * @param h0 h264 master context (differs from 'h' when doing sliced based
2592 * parallel decoding)
2594 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2596 static int decode_slice_header(H264Context *h, H264Context *h0)
2598 MpegEncContext *const s = &h->s;
2599 MpegEncContext *const s0 = &h0->s;
2600 unsigned int first_mb_in_slice;
2601 unsigned int pps_id;
2602 int num_ref_idx_active_override_flag, max_refs, ret;
2603 unsigned int slice_type, tmp, i, j;
2604 int default_ref_list_done = 0;
2605 int last_pic_structure, last_pic_droppable;
2606 int needs_reinit = 0;
2608 s->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
2609 s->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
2611 first_mb_in_slice = get_ue_golomb(&s->gb);
2613 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2614 if (h0->current_slice && FIELD_PICTURE) {
2618 h0->current_slice = 0;
2619 if (!s0->first_field) {
2620 if (s->current_picture_ptr && !s->droppable &&
2621 s->current_picture_ptr->owner2 == s) {
2622 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2623 s->picture_structure == PICT_BOTTOM_FIELD);
2625 s->current_picture_ptr = NULL;
2629 slice_type = get_ue_golomb_31(&s->gb);
2630 if (slice_type > 9) {
2631 av_log(h->s.avctx, AV_LOG_ERROR,
2632 "slice type too large (%d) at %d %d\n",
2633 h->slice_type, s->mb_x, s->mb_y);
2636 if (slice_type > 4) {
2638 h->slice_type_fixed = 1;
2640 h->slice_type_fixed = 0;
2642 slice_type = golomb_to_pict_type[slice_type];
2643 if (slice_type == AV_PICTURE_TYPE_I ||
2644 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2645 default_ref_list_done = 1;
2647 h->slice_type = slice_type;
2648 h->slice_type_nos = slice_type & 3;
2650 // to make a few old functions happy, it's wrong though
2651 s->pict_type = h->slice_type;
2653 pps_id = get_ue_golomb(&s->gb);
2654 if (pps_id >= MAX_PPS_COUNT) {
2655 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2658 if (!h0->pps_buffers[pps_id]) {
2659 av_log(h->s.avctx, AV_LOG_ERROR,
2660 "non-existing PPS %u referenced\n",
2664 h->pps = *h0->pps_buffers[pps_id];
2666 if (!h0->sps_buffers[h->pps.sps_id]) {
2667 av_log(h->s.avctx, AV_LOG_ERROR,
2668 "non-existing SPS %u referenced\n",
2673 if (h->pps.sps_id != h->current_sps_id ||
2674 h->context_reinitialized ||
2675 h0->sps_buffers[h->pps.sps_id]->new) {
2676 SPS *new_sps = h0->sps_buffers[h->pps.sps_id];
2678 h0->sps_buffers[h->pps.sps_id]->new = 0;
2680 if (h->sps.chroma_format_idc != new_sps->chroma_format_idc ||
2681 h->sps.bit_depth_luma != new_sps->bit_depth_luma)
2684 h->current_sps_id = h->pps.sps_id;
2685 h->sps = *h0->sps_buffers[h->pps.sps_id];
2687 if ((ret = h264_set_parameter_from_sps(h)) < 0)
2691 s->avctx->profile = ff_h264_get_profile(&h->sps);
2692 s->avctx->level = h->sps.level_idc;
2693 s->avctx->refs = h->sps.ref_frame_count;
2695 if (s->mb_width != h->sps.mb_width ||
2696 s->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
2699 s->mb_width = h->sps.mb_width;
2700 s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2702 h->b_stride = s->mb_width * 4;
2704 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2706 s->width = 16 * s->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
2707 if (h->sps.frame_mbs_only_flag)
2708 s->height = 16 * s->mb_height - (1 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2710 s->height = 16 * s->mb_height - (2 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2712 if (FFALIGN(s->avctx->width, 16) == s->width &&
2713 FFALIGN(s->avctx->height, 16) == s->height) {
2714 s->width = s->avctx->width;
2715 s->height = s->avctx->height;
2718 if (h->sps.video_signal_type_present_flag) {
2719 s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
2721 if (h->sps.colour_description_present_flag) {
2722 if (s->avctx->colorspace != h->sps.colorspace)
2724 s->avctx->color_primaries = h->sps.color_primaries;
2725 s->avctx->color_trc = h->sps.color_trc;
2726 s->avctx->colorspace = h->sps.colorspace;
2730 if (s->context_initialized &&
2731 (s->width != s->avctx->width ||
2732 s->height != s->avctx->height ||
2734 av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2737 av_log(s->avctx, AV_LOG_ERROR, "changing width/height on "
2738 "slice %d\n", h0->current_slice + 1);
2739 return AVERROR_INVALIDDATA;
2744 if ((ret = get_pixel_format(h)) < 0)
2746 s->avctx->pix_fmt = ret;
2748 av_log(h->s.avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
2749 "pix_fmt: %d\n", s->width, s->height, s->avctx->pix_fmt);
2751 if ((ret = h264_slice_header_init(h, 1)) < 0) {
2752 av_log(h->s.avctx, AV_LOG_ERROR,
2753 "h264_slice_header_init() failed\n");
2756 h->context_reinitialized = 1;
2758 if (!s->context_initialized) {
2760 av_log(h->s.avctx, AV_LOG_ERROR,
2761 "Cannot (re-)initialize context during parallel decoding.\n");
2765 if ((ret = get_pixel_format(h)) < 0)
2767 s->avctx->pix_fmt = ret;
2769 if ((ret = h264_slice_header_init(h, 0)) < 0) {
2770 av_log(h->s.avctx, AV_LOG_ERROR,
2771 "h264_slice_header_init() failed\n");
2776 if (h == h0 && h->dequant_coeff_pps != pps_id) {
2777 h->dequant_coeff_pps = pps_id;
2778 init_dequant_tables(h);
2781 h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
2784 h->mb_aff_frame = 0;
2785 last_pic_structure = s0->picture_structure;
2786 last_pic_droppable = s0->droppable;
2787 s->droppable = h->nal_ref_idc == 0;
2788 if (h->sps.frame_mbs_only_flag) {
2789 s->picture_structure = PICT_FRAME;
2791 if (get_bits1(&s->gb)) { // field_pic_flag
2792 s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
2794 s->picture_structure = PICT_FRAME;
2795 h->mb_aff_frame = h->sps.mb_aff;
2798 h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
2800 if (h0->current_slice != 0) {
2801 if (last_pic_structure != s->picture_structure ||
2802 last_pic_droppable != s->droppable) {
2803 av_log(h->s.avctx, AV_LOG_ERROR,
2804 "Changing field mode (%d -> %d) between slices is not allowed\n",
2805 last_pic_structure, s->picture_structure);
2806 s->picture_structure = last_pic_structure;
2807 s->droppable = last_pic_droppable;
2808 return AVERROR_INVALIDDATA;
2809 } else if (!s0->current_picture_ptr) {
2810 av_log(s->avctx, AV_LOG_ERROR,
2811 "unset current_picture_ptr on %d. slice\n",
2812 h0->current_slice + 1);
2813 return AVERROR_INVALIDDATA;
2816 /* Shorten frame num gaps so we don't have to allocate reference
2817 * frames just to throw them away */
2818 if (h->frame_num != h->prev_frame_num) {
2819 int unwrap_prev_frame_num = h->prev_frame_num;
2820 int max_frame_num = 1 << h->sps.log2_max_frame_num;
2822 if (unwrap_prev_frame_num > h->frame_num)
2823 unwrap_prev_frame_num -= max_frame_num;
2825 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2826 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2827 if (unwrap_prev_frame_num < 0)
2828 unwrap_prev_frame_num += max_frame_num;
2830 h->prev_frame_num = unwrap_prev_frame_num;
2834 /* See if we have a decoded first field looking for a pair...
2835 * Here, we're using that to see if we should mark previously
2836 * decode frames as "finished".
2837 * We have to do that before the "dummy" in-between frame allocation,
2838 * since that can modify s->current_picture_ptr. */
2839 if (s0->first_field) {
2840 assert(s0->current_picture_ptr);
2841 assert(s0->current_picture_ptr->f.data[0]);
2842 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2844 /* Mark old field/frame as completed */
2845 if (!last_pic_droppable && s0->current_picture_ptr->owner2 == s0) {
2846 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2847 last_pic_structure == PICT_BOTTOM_FIELD);
2850 /* figure out if we have a complementary field pair */
2851 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2852 /* Previous field is unmatched. Don't display it, but let it
2853 * remain for reference if marked as such. */
2854 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
2855 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2856 last_pic_structure == PICT_TOP_FIELD);
2859 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2860 /* This and previous field were reference, but had
2861 * different frame_nums. Consider this field first in
2862 * pair. Throw away previous field except for reference
2864 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
2865 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2866 last_pic_structure == PICT_TOP_FIELD);
2869 /* Second field in complementary pair */
2870 if (!((last_pic_structure == PICT_TOP_FIELD &&
2871 s->picture_structure == PICT_BOTTOM_FIELD) ||
2872 (last_pic_structure == PICT_BOTTOM_FIELD &&
2873 s->picture_structure == PICT_TOP_FIELD))) {
2874 av_log(s->avctx, AV_LOG_ERROR,
2875 "Invalid field mode combination %d/%d\n",
2876 last_pic_structure, s->picture_structure);
2877 s->picture_structure = last_pic_structure;
2878 s->droppable = last_pic_droppable;
2879 return AVERROR_INVALIDDATA;
2880 } else if (last_pic_droppable != s->droppable) {
2881 av_log(s->avctx, AV_LOG_ERROR,
2882 "Cannot combine reference and non-reference fields in the same frame\n");
2883 av_log_ask_for_sample(s->avctx, NULL);
2884 s->picture_structure = last_pic_structure;
2885 s->droppable = last_pic_droppable;
2886 return AVERROR_PATCHWELCOME;
2889 /* Take ownership of this buffer. Note that if another thread owned
2890 * the first field of this buffer, we're not operating on that pointer,
2891 * so the original thread is still responsible for reporting progress
2892 * on that first field (or if that was us, we just did that above).
2893 * By taking ownership, we assign responsibility to ourselves to
2894 * report progress on the second field. */
2895 s0->current_picture_ptr->owner2 = s0;
2900 while (h->frame_num != h->prev_frame_num &&
2901 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
2902 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2903 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
2904 h->frame_num, h->prev_frame_num);
2905 if (ff_h264_frame_start(h) < 0)
2907 h->prev_frame_num++;
2908 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
2909 s->current_picture_ptr->frame_num = h->prev_frame_num;
2910 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
2911 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
2912 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
2913 s->avctx->err_recognition & AV_EF_EXPLODE)
2915 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2916 (s->avctx->err_recognition & AV_EF_EXPLODE))
2917 return AVERROR_INVALIDDATA;
2918 /* Error concealment: if a ref is missing, copy the previous ref in its place.
2919 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2920 * about there being no actual duplicates.
2921 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
2922 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2924 if (h->short_ref_count) {
2926 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2927 (const uint8_t **)prev->f.data, prev->f.linesize,
2928 s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
2929 h->short_ref[0]->poc = prev->poc + 2;
2931 h->short_ref[0]->frame_num = h->prev_frame_num;
2935 /* See if we have a decoded first field looking for a pair...
2936 * We're using that to see whether to continue decoding in that
2937 * frame, or to allocate a new one. */
2938 if (s0->first_field) {
2939 assert(s0->current_picture_ptr);
2940 assert(s0->current_picture_ptr->f.data[0]);
2941 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2943 /* figure out if we have a complementary field pair */
2944 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2945 /* Previous field is unmatched. Don't display it, but let it
2946 * remain for reference if marked as such. */
2947 s0->current_picture_ptr = NULL;
2948 s0->first_field = FIELD_PICTURE;
2950 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2951 /* This and the previous field had different frame_nums.
2952 * Consider this field first in pair. Throw away previous
2953 * one except for reference purposes. */
2954 s0->first_field = 1;
2955 s0->current_picture_ptr = NULL;
2957 /* Second field in complementary pair */
2958 s0->first_field = 0;
2962 /* Frame or first field in a potentially complementary pair */
2963 s0->first_field = FIELD_PICTURE;
2966 if (!FIELD_PICTURE || s0->first_field) {
2967 if (ff_h264_frame_start(h) < 0) {
2968 s0->first_field = 0;
2972 ff_release_unused_pictures(s, 0);
2975 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
2978 s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
2980 assert(s->mb_num == s->mb_width * s->mb_height);
2981 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2982 first_mb_in_slice >= s->mb_num) {
2983 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2986 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2987 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2988 if (s->picture_structure == PICT_BOTTOM_FIELD)
2989 s->resync_mb_y = s->mb_y = s->mb_y + 1;
2990 assert(s->mb_y < s->mb_height);
2992 if (s->picture_structure == PICT_FRAME) {
2993 h->curr_pic_num = h->frame_num;
2994 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
2996 h->curr_pic_num = 2 * h->frame_num + 1;
2997 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3000 if (h->nal_unit_type == NAL_IDR_SLICE)
3001 get_ue_golomb(&s->gb); /* idr_pic_id */
3003 if (h->sps.poc_type == 0) {
3004 h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3006 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3007 h->delta_poc_bottom = get_se_golomb(&s->gb);
3010 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3011 h->delta_poc[0] = get_se_golomb(&s->gb);
3013 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
3014 h->delta_poc[1] = get_se_golomb(&s->gb);
3019 if (h->pps.redundant_pic_cnt_present)
3020 h->redundant_pic_count = get_ue_golomb(&s->gb);
3022 // set defaults, might be overridden a few lines later
3023 h->ref_count[0] = h->pps.ref_count[0];
3024 h->ref_count[1] = h->pps.ref_count[1];
3026 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3027 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3028 h->direct_spatial_mv_pred = get_bits1(&s->gb);
3029 num_ref_idx_active_override_flag = get_bits1(&s->gb);
3031 if (num_ref_idx_active_override_flag) {
3032 h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
3033 if (h->ref_count[0] < 1)
3034 return AVERROR_INVALIDDATA;
3035 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3036 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
3037 if (h->ref_count[1] < 1)
3038 return AVERROR_INVALIDDATA;
3042 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3049 max_refs = s->picture_structure == PICT_FRAME ? 16 : 32;
3051 if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
3052 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3053 h->ref_count[0] = h->ref_count[1] = 1;
3054 return AVERROR_INVALIDDATA;
3057 if (!default_ref_list_done)
3058 ff_h264_fill_default_ref_list(h);
3060 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
3061 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3062 h->ref_count[1] = h->ref_count[0] = 0;
3066 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3067 s->last_picture_ptr = &h->ref_list[0][0];
3068 s->last_picture_ptr->owner2 = s;
3069 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3071 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3072 s->next_picture_ptr = &h->ref_list[1][0];
3073 s->next_picture_ptr->owner2 = s;
3074 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3077 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3078 (h->pps.weighted_bipred_idc == 1 &&
3079 h->slice_type_nos == AV_PICTURE_TYPE_B))
3080 pred_weight_table(h);
3081 else if (h->pps.weighted_bipred_idc == 2 &&
3082 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3083 implicit_weight_table(h, -1);
3086 for (i = 0; i < 2; i++) {
3087 h->luma_weight_flag[i] = 0;
3088 h->chroma_weight_flag[i] = 0;
3092 // If frame-mt is enabled, only update mmco tables for the first slice
3093 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3094 // or h->mmco, which will cause ref list mix-ups and decoding errors
3095 // further down the line. This may break decoding if the first slice is
3096 // corrupt, thus we only do this if frame-mt is enabled.
3097 if (h->nal_ref_idc &&
3098 ff_h264_decode_ref_pic_marking(h0, &s->gb,
3099 !(s->avctx->active_thread_type & FF_THREAD_FRAME) ||
3100 h0->current_slice == 0) < 0 &&
3101 (s->avctx->err_recognition & AV_EF_EXPLODE))
3102 return AVERROR_INVALIDDATA;
3105 ff_h264_fill_mbaff_ref_list(h);
3107 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3108 implicit_weight_table(h, 0);
3109 implicit_weight_table(h, 1);
3113 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3114 ff_h264_direct_dist_scale_factor(h);
3115 ff_h264_direct_ref_list_init(h);
3117 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3118 tmp = get_ue_golomb_31(&s->gb);
3120 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3123 h->cabac_init_idc = tmp;
3126 h->last_qscale_diff = 0;
3127 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3128 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3129 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3133 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3134 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3135 // FIXME qscale / qp ... stuff
3136 if (h->slice_type == AV_PICTURE_TYPE_SP)
3137 get_bits1(&s->gb); /* sp_for_switch_flag */
3138 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3139 h->slice_type == AV_PICTURE_TYPE_SI)
3140 get_se_golomb(&s->gb); /* slice_qs_delta */
3142 h->deblocking_filter = 1;
3143 h->slice_alpha_c0_offset = 52;
3144 h->slice_beta_offset = 52;
3145 if (h->pps.deblocking_filter_parameters_present) {
3146 tmp = get_ue_golomb_31(&s->gb);
3148 av_log(s->avctx, AV_LOG_ERROR,
3149 "deblocking_filter_idc %u out of range\n", tmp);
3152 h->deblocking_filter = tmp;
3153 if (h->deblocking_filter < 2)
3154 h->deblocking_filter ^= 1; // 1<->0
3156 if (h->deblocking_filter) {
3157 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3158 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3159 if (h->slice_alpha_c0_offset > 104U ||
3160 h->slice_beta_offset > 104U) {
3161 av_log(s->avctx, AV_LOG_ERROR,
3162 "deblocking filter parameters %d %d out of range\n",
3163 h->slice_alpha_c0_offset, h->slice_beta_offset);
3169 if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3170 (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3171 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3172 (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3173 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3174 (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3175 h->nal_ref_idc == 0))
3176 h->deblocking_filter = 0;
3178 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3179 if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3180 /* Cheat slightly for speed:
3181 * Do not bother to deblock across slices. */
3182 h->deblocking_filter = 2;
3184 h0->max_contexts = 1;
3185 if (!h0->single_decode_warning) {
3186 av_log(s->avctx, AV_LOG_INFO,
3187 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3188 h0->single_decode_warning = 1;
3191 av_log(h->s.avctx, AV_LOG_ERROR,
3192 "Deblocking switched inside frame.\n");
3197 h->qp_thresh = 15 + 52 -
3198 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3200 h->pps.chroma_qp_index_offset[0],
3201 h->pps.chroma_qp_index_offset[1]) +
3202 6 * (h->sps.bit_depth_luma - 8);
3204 h0->last_slice_type = slice_type;
3205 h->slice_num = ++h0->current_slice;
3206 if (h->slice_num >= MAX_SLICES) {
3207 av_log(s->avctx, AV_LOG_ERROR,
3208 "Too many slices, increase MAX_SLICES and recompile\n");
3211 for (j = 0; j < 2; j++) {
3213 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3214 for (i = 0; i < 16; i++) {
3216 if (h->ref_list[j][i].f.data[0]) {
3218 uint8_t *base = h->ref_list[j][i].f.base[0];
3219 for (k = 0; k < h->short_ref_count; k++)
3220 if (h->short_ref[k]->f.base[0] == base) {
3224 for (k = 0; k < h->long_ref_count; k++)
3225 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3226 id_list[i] = h->short_ref_count + k;
3234 for (i = 0; i < 16; i++)
3235 ref2frm[i + 2] = 4 * id_list[i] +
3236 (h->ref_list[j][i].f.reference & 3);
3238 ref2frm[18 + 1] = -1;
3239 for (i = 16; i < 48; i++)
3240 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3241 (h->ref_list[j][i].f.reference & 3);
3244 // FIXME: fix draw_edges + PAFF + frame threads
3245 h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
3246 (!h->sps.frame_mbs_only_flag &&
3247 s->avctx->active_thread_type))
3249 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3251 if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3252 av_log(h->s.avctx, AV_LOG_DEBUG,
3253 "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",
3255 (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3257 av_get_picture_type_char(h->slice_type),
3258 h->slice_type_fixed ? " fix" : "",
3259 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3260 pps_id, h->frame_num,
3261 s->current_picture_ptr->field_poc[0],
3262 s->current_picture_ptr->field_poc[1],
3263 h->ref_count[0], h->ref_count[1],
3265 h->deblocking_filter,
3266 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3268 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3269 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3275 int ff_h264_get_slice_type(const H264Context *h)
3277 switch (h->slice_type) {
3278 case AV_PICTURE_TYPE_P:
3280 case AV_PICTURE_TYPE_B:
3282 case AV_PICTURE_TYPE_I:
3284 case AV_PICTURE_TYPE_SP:
3286 case AV_PICTURE_TYPE_SI:
3293 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3294 MpegEncContext *const s,
3295 int mb_type, int top_xy,
3296 int left_xy[LEFT_MBS],
3298 int left_type[LEFT_MBS],
3299 int mb_xy, int list)
3301 int b_stride = h->b_stride;
3302 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3303 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3304 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3305 if (USES_LIST(top_type, list)) {
3306 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3307 const int b8_xy = 4 * top_xy + 2;
3308 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3309 AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
3310 ref_cache[0 - 1 * 8] =
3311 ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3312 ref_cache[2 - 1 * 8] =
3313 ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3315 AV_ZERO128(mv_dst - 1 * 8);
3316 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3319 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3320 if (USES_LIST(left_type[LTOP], list)) {
3321 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3322 const int b8_xy = 4 * left_xy[LTOP] + 1;
3323 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3324 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
3325 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
3326 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
3327 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
3329 ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
3330 ref_cache[-1 + 16] =
3331 ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
3333 AV_ZERO32(mv_dst - 1 + 0);
3334 AV_ZERO32(mv_dst - 1 + 8);
3335 AV_ZERO32(mv_dst - 1 + 16);
3336 AV_ZERO32(mv_dst - 1 + 24);
3339 ref_cache[-1 + 16] =
3340 ref_cache[-1 + 24] = LIST_NOT_USED;
3345 if (!USES_LIST(mb_type, list)) {
3346 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3347 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3348 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3349 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3350 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3355 int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
3356 int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3357 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3358 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3359 AV_WN32A(&ref_cache[0 * 8], ref01);
3360 AV_WN32A(&ref_cache[1 * 8], ref01);
3361 AV_WN32A(&ref_cache[2 * 8], ref23);
3362 AV_WN32A(&ref_cache[3 * 8], ref23);
3366 int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
3367 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3368 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3369 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3370 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3376 * @return non zero if the loop filter can be skipped
3378 static int fill_filter_caches(H264Context *h, int mb_type)
3380 MpegEncContext *const s = &h->s;
3381 const int mb_xy = h->mb_xy;
3382 int top_xy, left_xy[LEFT_MBS];
3383 int top_type, left_type[LEFT_MBS];
3387 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3389 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3390 * stuff, I can't imagine that these complex rules are worth it. */
3392 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3394 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3395 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3397 if (left_mb_field_flag != curr_mb_field_flag)
3398 left_xy[LTOP] -= s->mb_stride;
3400 if (curr_mb_field_flag)
3401 top_xy += s->mb_stride &
3402 (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3403 if (left_mb_field_flag != curr_mb_field_flag)
3404 left_xy[LBOT] += s->mb_stride;
3408 h->top_mb_xy = top_xy;
3409 h->left_mb_xy[LTOP] = left_xy[LTOP];
3410 h->left_mb_xy[LBOT] = left_xy[LBOT];
3412 /* For sufficiently low qp, filtering wouldn't do anything.
3413 * This is a conservative estimate: could also check beta_offset
3414 * and more accurate chroma_qp. */
3415 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3416 int qp = s->current_picture.f.qscale_table[mb_xy];
3417 if (qp <= qp_thresh &&
3418 (left_xy[LTOP] < 0 ||
3419 ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3421 ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3424 if ((left_xy[LTOP] < 0 ||
3425 ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3426 (top_xy < s->mb_stride ||
3427 ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3432 top_type = s->current_picture.f.mb_type[top_xy];
3433 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3434 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3435 if (h->deblocking_filter == 2) {
3436 if (h->slice_table[top_xy] != h->slice_num)
3438 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3439 left_type[LTOP] = left_type[LBOT] = 0;
3441 if (h->slice_table[top_xy] == 0xFFFF)
3443 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3444 left_type[LTOP] = left_type[LBOT] = 0;
3446 h->top_type = top_type;
3447 h->left_type[LTOP] = left_type[LTOP];
3448 h->left_type[LBOT] = left_type[LBOT];
3450 if (IS_INTRA(mb_type))
3453 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3454 top_type, left_type, mb_xy, 0);
3455 if (h->list_count == 2)
3456 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3457 top_type, left_type, mb_xy, 1);
3459 nnz = h->non_zero_count[mb_xy];
3460 nnz_cache = h->non_zero_count_cache;
3461 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3462 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3463 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3464 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3465 h->cbp = h->cbp_table[mb_xy];
3468 nnz = h->non_zero_count[top_xy];
3469 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3472 if (left_type[LTOP]) {
3473 nnz = h->non_zero_count[left_xy[LTOP]];
3474 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3475 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3476 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3477 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3480 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3481 * from what the loop filter needs */
3482 if (!CABAC && h->pps.transform_8x8_mode) {
3483 if (IS_8x8DCT(top_type)) {
3484 nnz_cache[4 + 8 * 0] =
3485 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3486 nnz_cache[6 + 8 * 0] =
3487 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3489 if (IS_8x8DCT(left_type[LTOP])) {
3490 nnz_cache[3 + 8 * 1] =
3491 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3493 if (IS_8x8DCT(left_type[LBOT])) {
3494 nnz_cache[3 + 8 * 3] =
3495 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3498 if (IS_8x8DCT(mb_type)) {
3499 nnz_cache[scan8[0]] =
3500 nnz_cache[scan8[1]] =
3501 nnz_cache[scan8[2]] =
3502 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3504 nnz_cache[scan8[0 + 4]] =
3505 nnz_cache[scan8[1 + 4]] =
3506 nnz_cache[scan8[2 + 4]] =
3507 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3509 nnz_cache[scan8[0 + 8]] =
3510 nnz_cache[scan8[1 + 8]] =
3511 nnz_cache[scan8[2 + 8]] =
3512 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3514 nnz_cache[scan8[0 + 12]] =
3515 nnz_cache[scan8[1 + 12]] =
3516 nnz_cache[scan8[2 + 12]] =
3517 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3524 static void loop_filter(H264Context *h, int start_x, int end_x)
3526 MpegEncContext *const s = &h->s;
3527 uint8_t *dest_y, *dest_cb, *dest_cr;
3528 int linesize, uvlinesize, mb_x, mb_y;
3529 const int end_mb_y = s->mb_y + FRAME_MBAFF;
3530 const int old_slice_type = h->slice_type;
3531 const int pixel_shift = h->pixel_shift;
3532 const int block_h = 16 >> s->chroma_y_shift;
3534 if (h->deblocking_filter) {
3535 for (mb_x = start_x; mb_x < end_x; mb_x++)
3536 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
3538 mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
3539 h->slice_num = h->slice_table[mb_xy];
3540 mb_type = s->current_picture.f.mb_type[mb_xy];
3541 h->list_count = h->list_counts[mb_xy];
3545 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3549 dest_y = s->current_picture.f.data[0] +
3550 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
3551 dest_cb = s->current_picture.f.data[1] +
3552 (mb_x << pixel_shift) * (8 << CHROMA444) +
3553 mb_y * s->uvlinesize * block_h;
3554 dest_cr = s->current_picture.f.data[2] +
3555 (mb_x << pixel_shift) * (8 << CHROMA444) +
3556 mb_y * s->uvlinesize * block_h;
3557 // FIXME simplify above
3560 linesize = h->mb_linesize = s->linesize * 2;
3561 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3562 if (mb_y & 1) { // FIXME move out of this function?
3563 dest_y -= s->linesize * 15;
3564 dest_cb -= s->uvlinesize * (block_h - 1);
3565 dest_cr -= s->uvlinesize * (block_h - 1);
3568 linesize = h->mb_linesize = s->linesize;
3569 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3571 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
3573 if (fill_filter_caches(h, mb_type))
3575 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3576 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3579 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
3580 linesize, uvlinesize);
3582 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
3583 dest_cr, linesize, uvlinesize);
3587 h->slice_type = old_slice_type;
3589 s->mb_y = end_mb_y - FRAME_MBAFF;
3590 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3591 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3594 static void predict_field_decoding_flag(H264Context *h)
3596 MpegEncContext *const s = &h->s;
3597 const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
3598 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
3599 s->current_picture.f.mb_type[mb_xy - 1] :
3600 (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
3601 s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
3602 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3606 * Draw edges and report progress for the last MB row.
3608 static void decode_finish_row(H264Context *h)
3610 MpegEncContext *const s = &h->s;
3611 int top = 16 * (s->mb_y >> FIELD_PICTURE);
3612 int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
3613 int height = 16 << FRAME_MBAFF;
3614 int deblock_border = (16 + 4) << FRAME_MBAFF;
3616 if (h->deblocking_filter) {
3617 if ((top + height) >= pic_height)
3618 height += deblock_border;
3619 top -= deblock_border;
3622 if (top >= pic_height || (top + height) < h->emu_edge_height)
3625 height = FFMIN(height, pic_height - top);
3626 if (top < h->emu_edge_height) {
3627 height = top + height;
3631 ff_draw_horiz_band(s, top, height);
3636 ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
3637 s->picture_structure == PICT_BOTTOM_FIELD);
3640 static int decode_slice(struct AVCodecContext *avctx, void *arg)
3642 H264Context *h = *(void **)arg;
3643 MpegEncContext *const s = &h->s;
3644 const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
3646 int lf_x_start = s->mb_x;
3648 s->mb_skip_run = -1;
3650 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
3651 s->codec_id != AV_CODEC_ID_H264 ||
3652 (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
3656 align_get_bits(&s->gb);
3659 ff_init_cabac_states(&h->cabac);
3660 ff_init_cabac_decoder(&h->cabac,
3661 s->gb.buffer + get_bits_count(&s->gb) / 8,
3662 (get_bits_left(&s->gb) + 7) / 8);
3664 ff_h264_init_cabac_states(h);
3668 int ret = ff_h264_decode_mb_cabac(h);
3670 // STOP_TIMER("decode_mb_cabac")
3673 ff_h264_hl_decode_mb(h);
3675 // FIXME optimal? or let mb_decode decode 16x32 ?
3676 if (ret >= 0 && FRAME_MBAFF) {
3679 ret = ff_h264_decode_mb_cabac(h);
3682 ff_h264_hl_decode_mb(h);
3685 eos = get_cabac_terminate(&h->cabac);
3687 if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
3688 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3689 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3690 s->mb_y, ER_MB_END & part_mask);
3691 if (s->mb_x >= lf_x_start)
3692 loop_filter(h, lf_x_start, s->mb_x + 1);
3695 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3696 av_log(h->s.avctx, AV_LOG_ERROR,
3697 "error while decoding MB %d %d, bytestream (%td)\n",
3699 h->cabac.bytestream_end - h->cabac.bytestream);
3700 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3701 s->mb_y, ER_MB_ERROR & part_mask);
3705 if (++s->mb_x >= s->mb_width) {
3706 loop_filter(h, lf_x_start, s->mb_x);
3707 s->mb_x = lf_x_start = 0;
3708 decode_finish_row(h);
3710 if (FIELD_OR_MBAFF_PICTURE) {
3712 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3713 predict_field_decoding_flag(h);
3717 if (eos || s->mb_y >= s->mb_height) {
3718 tprintf(s->avctx, "slice end %d %d\n",
3719 get_bits_count(&s->gb), s->gb.size_in_bits);
3720 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3721 s->mb_y, ER_MB_END & part_mask);
3722 if (s->mb_x > lf_x_start)
3723 loop_filter(h, lf_x_start, s->mb_x);
3729 int ret = ff_h264_decode_mb_cavlc(h);
3732 ff_h264_hl_decode_mb(h);
3734 // FIXME optimal? or let mb_decode decode 16x32 ?
3735 if (ret >= 0 && FRAME_MBAFF) {
3737 ret = ff_h264_decode_mb_cavlc(h);
3740 ff_h264_hl_decode_mb(h);
3745 av_log(h->s.avctx, AV_LOG_ERROR,
3746 "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3747 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3748 s->mb_y, ER_MB_ERROR & part_mask);
3752 if (++s->mb_x >= s->mb_width) {
3753 loop_filter(h, lf_x_start, s->mb_x);
3754 s->mb_x = lf_x_start = 0;
3755 decode_finish_row(h);
3757 if (FIELD_OR_MBAFF_PICTURE) {
3759 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3760 predict_field_decoding_flag(h);
3762 if (s->mb_y >= s->mb_height) {
3763 tprintf(s->avctx, "slice end %d %d\n",
3764 get_bits_count(&s->gb), s->gb.size_in_bits);
3766 if (get_bits_left(&s->gb) == 0) {
3767 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3768 s->mb_x - 1, s->mb_y,
3769 ER_MB_END & part_mask);
3773 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3774 s->mb_x - 1, s->mb_y,
3775 ER_MB_END & part_mask);
3782 if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
3783 tprintf(s->avctx, "slice end %d %d\n",
3784 get_bits_count(&s->gb), s->gb.size_in_bits);
3785 if (get_bits_left(&s->gb) == 0) {
3786 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3787 s->mb_x - 1, s->mb_y,
3788 ER_MB_END & part_mask);
3789 if (s->mb_x > lf_x_start)
3790 loop_filter(h, lf_x_start, s->mb_x);
3794 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3795 s->mb_y, ER_MB_ERROR & part_mask);
3805 * Call decode_slice() for each context.
3807 * @param h h264 master context
3808 * @param context_count number of contexts to execute
3810 static int execute_decode_slices(H264Context *h, int context_count)
3812 MpegEncContext *const s = &h->s;
3813 AVCodecContext *const avctx = s->avctx;
3817 if (s->avctx->hwaccel ||
3818 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3820 if (context_count == 1) {
3821 return decode_slice(avctx, &h);
3823 for (i = 1; i < context_count; i++) {
3824 hx = h->thread_context[i];
3825 hx->s.err_recognition = avctx->err_recognition;
3826 hx->s.error_count = 0;
3829 avctx->execute(avctx, decode_slice, h->thread_context,
3830 NULL, context_count, sizeof(void *));
3832 /* pull back stuff from slices to master context */
3833 hx = h->thread_context[context_count - 1];
3834 s->mb_x = hx->s.mb_x;
3835 s->mb_y = hx->s.mb_y;
3836 s->droppable = hx->s.droppable;
3837 s->picture_structure = hx->s.picture_structure;
3838 for (i = 1; i < context_count; i++)
3839 h->s.error_count += h->thread_context[i]->s.error_count;
3845 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
3846 int parse_extradata)
3848 MpegEncContext *const s = &h->s;
3849 AVCodecContext *const avctx = s->avctx;
3850 H264Context *hx; ///< thread context
3854 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
3855 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
3858 h->max_contexts = s->slice_context_count;
3859 if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3860 h->current_slice = 0;
3861 if (!s->first_field)
3862 s->current_picture_ptr = NULL;
3863 ff_h264_reset_sei(h);
3866 for (; pass <= 1; pass++) {
3869 next_avc = h->is_avc ? 0 : buf_size;
3879 if (buf_index >= next_avc) {
3880 if (buf_index >= buf_size - h->nal_length_size)
3883 for (i = 0; i < h->nal_length_size; i++)
3884 nalsize = (nalsize << 8) | buf[buf_index++];
3885 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
3886 av_log(h->s.avctx, AV_LOG_ERROR,
3887 "AVC: nal size %d\n", nalsize);
3890 next_avc = buf_index + nalsize;
3892 // start code prefix search
3893 for (; buf_index + 3 < next_avc; buf_index++)
3894 // This should always succeed in the first iteration.
3895 if (buf[buf_index] == 0 &&
3896 buf[buf_index + 1] == 0 &&
3897 buf[buf_index + 2] == 1)
3900 if (buf_index + 3 >= buf_size) {
3901 buf_index = buf_size;
3906 if (buf_index >= next_avc)
3910 hx = h->thread_context[context_count];
3912 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
3913 &consumed, next_avc - buf_index);
3914 if (ptr == NULL || dst_length < 0) {
3918 i = buf_index + consumed;
3919 if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
3920 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
3921 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)