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[] = {
71 * Check if the top & left blocks are available if needed and
72 * change the dc mode so it only uses the available blocks.
74 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
76 MpegEncContext *const s = &h->s;
77 static const int8_t top[12] = {
78 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
80 static const int8_t left[12] = {
81 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
85 if (!(h->top_samples_available & 0x8000)) {
86 for (i = 0; i < 4; i++) {
87 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
89 av_log(h->s.avctx, AV_LOG_ERROR,
90 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
91 status, s->mb_x, s->mb_y);
94 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
99 if ((h->left_samples_available & 0x8888) != 0x8888) {
100 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
101 for (i = 0; i < 4; i++)
102 if (!(h->left_samples_available & mask[i])) {
103 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
105 av_log(h->s.avctx, AV_LOG_ERROR,
106 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
107 status, s->mb_x, s->mb_y);
110 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
116 } // FIXME cleanup like ff_h264_check_intra_pred_mode
119 * Check if the top & left blocks are available if needed and
120 * change the dc mode so it only uses the available blocks.
122 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
124 MpegEncContext *const s = &h->s;
125 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
126 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
129 av_log(h->s.avctx, AV_LOG_ERROR,
130 "out of range intra chroma pred mode at %d %d\n",
135 if (!(h->top_samples_available & 0x8000)) {
138 av_log(h->s.avctx, AV_LOG_ERROR,
139 "top block unavailable for requested intra mode at %d %d\n",
145 if ((h->left_samples_available & 0x8080) != 0x8080) {
147 if (is_chroma && (h->left_samples_available & 0x8080)) {
148 // mad cow disease mode, aka MBAFF + constrained_intra_pred
149 mode = ALZHEIMER_DC_L0T_PRED8x8 +
150 (!(h->left_samples_available & 0x8000)) +
151 2 * (mode == DC_128_PRED8x8);
154 av_log(h->s.avctx, AV_LOG_ERROR,
155 "left block unavailable for requested intra mode at %d %d\n",
164 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
165 int *dst_length, int *consumed, int length)
171 // src[0]&0x80; // forbidden bit
172 h->nal_ref_idc = src[0] >> 5;
173 h->nal_unit_type = src[0] & 0x1F;
178 #define STARTCODE_TEST \
179 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
180 if (src[i + 2] != 3) { \
181 /* startcode, so we must be past the end */ \
186 #if HAVE_FAST_UNALIGNED
187 #define FIND_FIRST_ZERO \
188 if (i > 0 && !src[i]) \
193 for (i = 0; i + 1 < length; i += 9) {
194 if (!((~AV_RN64A(src + i) &
195 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
196 0x8000800080008080ULL))
203 for (i = 0; i + 1 < length; i += 5) {
204 if (!((~AV_RN32A(src + i) &
205 (AV_RN32A(src + i) - 0x01000101U)) &
214 for (i = 0; i + 1 < length; i += 2) {
217 if (i > 0 && src[i - 1] == 0)
223 if (i >= length - 1) { // no escaped 0
224 *dst_length = length;
225 *consumed = length + 1; // +1 for the header
229 // use second escape buffer for inter data
230 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
231 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
232 length + FF_INPUT_BUFFER_PADDING_SIZE);
233 dst = h->rbsp_buffer[bufidx];
240 while (si + 2 < length) {
241 // remove escapes (very rare 1:2^22)
242 if (src[si + 2] > 3) {
243 dst[di++] = src[si++];
244 dst[di++] = src[si++];
245 } else if (src[si] == 0 && src[si + 1] == 0) {
246 if (src[si + 2] == 3) { // escape
251 } else // next start code
255 dst[di++] = src[si++];
258 dst[di++] = src[si++];
261 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
264 *consumed = si + 1; // +1 for the header
265 /* FIXME store exact number of bits in the getbitcontext
266 * (it is needed for decoding) */
271 * Identify the exact end of the bitstream
272 * @return the length of the trailing, or 0 if damaged
274 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
279 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
281 for (r = 1; r < 9; r++) {
289 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
290 int height, int y_offset, int list)
292 int raw_my = h->mv_cache[list][scan8[n]][1];
293 int filter_height = (raw_my & 3) ? 2 : 0;
294 int full_my = (raw_my >> 2) + y_offset;
295 int top = full_my - filter_height;
296 int bottom = full_my + filter_height + height;
298 return FFMAX(abs(top), bottom);
301 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
302 int height, int y_offset, int list0,
303 int list1, int *nrefs)
305 MpegEncContext *const s = &h->s;
308 y_offset += 16 * (s->mb_y >> MB_FIELD);
311 int ref_n = h->ref_cache[0][scan8[n]];
312 Picture *ref = &h->ref_list[0][ref_n];
314 // Error resilience puts the current picture in the ref list.
315 // Don't try to wait on these as it will cause a deadlock.
316 // Fields can wait on each other, though.
317 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
318 (ref->f.reference & 3) != s->picture_structure) {
319 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
320 if (refs[0][ref_n] < 0)
322 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
327 int ref_n = h->ref_cache[1][scan8[n]];
328 Picture *ref = &h->ref_list[1][ref_n];
330 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
331 (ref->f.reference & 3) != s->picture_structure) {
332 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
333 if (refs[1][ref_n] < 0)
335 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
341 * Wait until all reference frames are available for MC operations.
343 * @param h the H264 context
345 static void await_references(H264Context *h)
347 MpegEncContext *const s = &h->s;
348 const int mb_xy = h->mb_xy;
349 const int mb_type = s->current_picture.f.mb_type[mb_xy];
351 int nrefs[2] = { 0 };
354 memset(refs, -1, sizeof(refs));
356 if (IS_16X16(mb_type)) {
357 get_lowest_part_y(h, refs, 0, 16, 0,
358 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
359 } else if (IS_16X8(mb_type)) {
360 get_lowest_part_y(h, refs, 0, 8, 0,
361 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
362 get_lowest_part_y(h, refs, 8, 8, 8,
363 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
364 } else if (IS_8X16(mb_type)) {
365 get_lowest_part_y(h, refs, 0, 16, 0,
366 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
367 get_lowest_part_y(h, refs, 4, 16, 0,
368 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
372 assert(IS_8X8(mb_type));
374 for (i = 0; i < 4; i++) {
375 const int sub_mb_type = h->sub_mb_type[i];
377 int y_offset = (i & 2) << 2;
379 if (IS_SUB_8X8(sub_mb_type)) {
380 get_lowest_part_y(h, refs, n, 8, y_offset,
381 IS_DIR(sub_mb_type, 0, 0),
382 IS_DIR(sub_mb_type, 0, 1),
384 } else if (IS_SUB_8X4(sub_mb_type)) {
385 get_lowest_part_y(h, refs, n, 4, y_offset,
386 IS_DIR(sub_mb_type, 0, 0),
387 IS_DIR(sub_mb_type, 0, 1),
389 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
390 IS_DIR(sub_mb_type, 0, 0),
391 IS_DIR(sub_mb_type, 0, 1),
393 } else if (IS_SUB_4X8(sub_mb_type)) {
394 get_lowest_part_y(h, refs, n, 8, y_offset,
395 IS_DIR(sub_mb_type, 0, 0),
396 IS_DIR(sub_mb_type, 0, 1),
398 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
399 IS_DIR(sub_mb_type, 0, 0),
400 IS_DIR(sub_mb_type, 0, 1),
404 assert(IS_SUB_4X4(sub_mb_type));
405 for (j = 0; j < 4; j++) {
406 int sub_y_offset = y_offset + 2 * (j & 2);
407 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
408 IS_DIR(sub_mb_type, 0, 0),
409 IS_DIR(sub_mb_type, 0, 1),
416 for (list = h->list_count - 1; list >= 0; list--)
417 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
418 int row = refs[list][ref];
420 Picture *ref_pic = &h->ref_list[list][ref];
421 int ref_field = ref_pic->f.reference - 1;
422 int ref_field_picture = ref_pic->field_picture;
423 int pic_height = 16 * s->mb_height >> ref_field_picture;
428 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
429 ff_thread_await_progress(&ref_pic->f,
430 FFMIN((row >> 1) - !(row & 1),
433 ff_thread_await_progress(&ref_pic->f,
434 FFMIN((row >> 1), pic_height - 1),
436 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
437 ff_thread_await_progress(&ref_pic->f,
438 FFMIN(row * 2 + ref_field,
441 } else if (FIELD_PICTURE) {
442 ff_thread_await_progress(&ref_pic->f,
443 FFMIN(row, pic_height - 1),
446 ff_thread_await_progress(&ref_pic->f,
447 FFMIN(row, pic_height - 1),
454 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
455 int n, int square, int height,
457 uint8_t *dest_y, uint8_t *dest_cb,
459 int src_x_offset, int src_y_offset,
460 qpel_mc_func *qpix_op,
461 h264_chroma_mc_func chroma_op,
462 int pixel_shift, int chroma_idc)
464 MpegEncContext *const s = &h->s;
465 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
466 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
467 const int luma_xy = (mx & 3) + ((my & 3) << 2);
468 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
469 uint8_t *src_y = pic->f.data[0] + offset;
470 uint8_t *src_cb, *src_cr;
471 int extra_width = h->emu_edge_width;
472 int extra_height = h->emu_edge_height;
474 const int full_mx = mx >> 2;
475 const int full_my = my >> 2;
476 const int pic_width = 16 * s->mb_width;
477 const int pic_height = 16 * s->mb_height >> MB_FIELD;
485 if (full_mx < 0 - extra_width ||
486 full_my < 0 - extra_height ||
487 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
488 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
489 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
490 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
492 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
493 full_my - 2, pic_width, pic_height);
494 src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
498 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
500 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
502 if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
505 if (chroma_idc == 3 /* yuv444 */) {
506 src_cb = pic->f.data[1] + offset;
508 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
509 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
511 16 + 5, 16 + 5 /*FIXME*/,
512 full_mx - 2, full_my - 2,
513 pic_width, pic_height);
514 src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
516 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
518 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
520 src_cr = pic->f.data[2] + offset;
522 s->dsp.emulated_edge_mc(s->edge_emu_buffer,
523 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
525 16 + 5, 16 + 5 /*FIXME*/,
526 full_mx - 2, full_my - 2,
527 pic_width, pic_height);
528 src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
530 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
532 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
536 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
537 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
538 // chroma offset when predicting from a field of opposite parity
539 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
540 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
543 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
544 (my >> ysh) * h->mb_uvlinesize;
545 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
546 (my >> ysh) * h->mb_uvlinesize;
549 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
550 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
551 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
552 src_cb = s->edge_emu_buffer;
554 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
555 height >> (chroma_idc == 1 /* yuv420 */),
556 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
559 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, 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_cr = s->edge_emu_buffer;
564 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
565 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
568 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
569 int height, int delta,
570 uint8_t *dest_y, uint8_t *dest_cb,
572 int x_offset, int y_offset,
573 qpel_mc_func *qpix_put,
574 h264_chroma_mc_func chroma_put,
575 qpel_mc_func *qpix_avg,
576 h264_chroma_mc_func chroma_avg,
577 int list0, int list1,
578 int pixel_shift, int chroma_idc)
580 MpegEncContext *const s = &h->s;
581 qpel_mc_func *qpix_op = qpix_put;
582 h264_chroma_mc_func chroma_op = chroma_put;
584 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
585 if (chroma_idc == 3 /* yuv444 */) {
586 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
587 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
588 } else if (chroma_idc == 2 /* yuv422 */) {
589 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
590 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
591 } else { /* yuv420 */
592 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
593 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
595 x_offset += 8 * s->mb_x;
596 y_offset += 8 * (s->mb_y >> MB_FIELD);
599 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
600 mc_dir_part(h, ref, n, square, height, delta, 0,
601 dest_y, dest_cb, dest_cr, x_offset, y_offset,
602 qpix_op, chroma_op, pixel_shift, chroma_idc);
605 chroma_op = chroma_avg;
609 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
610 mc_dir_part(h, ref, n, square, height, delta, 1,
611 dest_y, dest_cb, dest_cr, x_offset, y_offset,
612 qpix_op, chroma_op, pixel_shift, chroma_idc);
616 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
617 int height, int delta,
618 uint8_t *dest_y, uint8_t *dest_cb,
620 int x_offset, int y_offset,
621 qpel_mc_func *qpix_put,
622 h264_chroma_mc_func chroma_put,
623 h264_weight_func luma_weight_op,
624 h264_weight_func chroma_weight_op,
625 h264_biweight_func luma_weight_avg,
626 h264_biweight_func chroma_weight_avg,
627 int list0, int list1,
628 int pixel_shift, int chroma_idc)
630 MpegEncContext *const s = &h->s;
633 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
634 if (chroma_idc == 3 /* yuv444 */) {
635 chroma_height = height;
636 chroma_weight_avg = luma_weight_avg;
637 chroma_weight_op = luma_weight_op;
638 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
639 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
640 } else if (chroma_idc == 2 /* yuv422 */) {
641 chroma_height = height;
642 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
643 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
644 } else { /* yuv420 */
645 chroma_height = height >> 1;
646 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
647 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
649 x_offset += 8 * s->mb_x;
650 y_offset += 8 * (s->mb_y >> MB_FIELD);
652 if (list0 && list1) {
653 /* don't optimize for luma-only case, since B-frames usually
654 * use implicit weights => chroma too. */
655 uint8_t *tmp_cb = h->bipred_scratchpad;
656 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
657 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
658 int refn0 = h->ref_cache[0][scan8[n]];
659 int refn1 = h->ref_cache[1][scan8[n]];
661 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
662 dest_y, dest_cb, dest_cr,
663 x_offset, y_offset, qpix_put, chroma_put,
664 pixel_shift, chroma_idc);
665 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
666 tmp_y, tmp_cb, tmp_cr,
667 x_offset, y_offset, qpix_put, chroma_put,
668 pixel_shift, chroma_idc);
670 if (h->use_weight == 2) {
671 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
672 int weight1 = 64 - weight0;
673 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
674 height, 5, weight0, weight1, 0);
675 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
676 chroma_height, 5, weight0, weight1, 0);
677 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
678 chroma_height, 5, weight0, weight1, 0);
680 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
681 h->luma_log2_weight_denom,
682 h->luma_weight[refn0][0][0],
683 h->luma_weight[refn1][1][0],
684 h->luma_weight[refn0][0][1] +
685 h->luma_weight[refn1][1][1]);
686 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
687 h->chroma_log2_weight_denom,
688 h->chroma_weight[refn0][0][0][0],
689 h->chroma_weight[refn1][1][0][0],
690 h->chroma_weight[refn0][0][0][1] +
691 h->chroma_weight[refn1][1][0][1]);
692 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
693 h->chroma_log2_weight_denom,
694 h->chroma_weight[refn0][0][1][0],
695 h->chroma_weight[refn1][1][1][0],
696 h->chroma_weight[refn0][0][1][1] +
697 h->chroma_weight[refn1][1][1][1]);
700 int list = list1 ? 1 : 0;
701 int refn = h->ref_cache[list][scan8[n]];
702 Picture *ref = &h->ref_list[list][refn];
703 mc_dir_part(h, ref, n, square, height, delta, list,
704 dest_y, dest_cb, dest_cr, x_offset, y_offset,
705 qpix_put, chroma_put, pixel_shift, chroma_idc);
707 luma_weight_op(dest_y, h->mb_linesize, height,
708 h->luma_log2_weight_denom,
709 h->luma_weight[refn][list][0],
710 h->luma_weight[refn][list][1]);
711 if (h->use_weight_chroma) {
712 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
713 h->chroma_log2_weight_denom,
714 h->chroma_weight[refn][list][0][0],
715 h->chroma_weight[refn][list][0][1]);
716 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
717 h->chroma_log2_weight_denom,
718 h->chroma_weight[refn][list][1][0],
719 h->chroma_weight[refn][list][1][1]);
724 static av_always_inline void prefetch_motion(H264Context *h, int list,
725 int pixel_shift, int chroma_idc)
727 /* fetch pixels for estimated mv 4 macroblocks ahead
728 * optimized for 64byte cache lines */
729 MpegEncContext *const s = &h->s;
730 const int refn = h->ref_cache[list][scan8[0]];
732 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
733 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
734 uint8_t **src = h->ref_list[list][refn].f.data;
735 int off = (mx << pixel_shift) +
736 (my + (s->mb_x & 3) * 4) * h->mb_linesize +
738 s->dsp.prefetch(src[0] + off, s->linesize, 4);
739 if (chroma_idc == 3 /* yuv444 */) {
740 s->dsp.prefetch(src[1] + off, s->linesize, 4);
741 s->dsp.prefetch(src[2] + off, s->linesize, 4);
743 off = ((mx >> 1) << pixel_shift) +
744 ((my >> 1) + (s->mb_x & 7)) * s->uvlinesize +
746 s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
751 static void free_tables(H264Context *h, int free_rbsp)
756 av_freep(&h->intra4x4_pred_mode);
757 av_freep(&h->chroma_pred_mode_table);
758 av_freep(&h->cbp_table);
759 av_freep(&h->mvd_table[0]);
760 av_freep(&h->mvd_table[1]);
761 av_freep(&h->direct_table);
762 av_freep(&h->non_zero_count);
763 av_freep(&h->slice_table_base);
764 h->slice_table = NULL;
765 av_freep(&h->list_counts);
767 av_freep(&h->mb2b_xy);
768 av_freep(&h->mb2br_xy);
770 for (i = 0; i < MAX_THREADS; i++) {
771 hx = h->thread_context[i];
774 av_freep(&hx->top_borders[1]);
775 av_freep(&hx->top_borders[0]);
776 av_freep(&hx->bipred_scratchpad);
778 av_freep(&hx->rbsp_buffer[1]);
779 av_freep(&hx->rbsp_buffer[0]);
780 hx->rbsp_buffer_size[0] = 0;
781 hx->rbsp_buffer_size[1] = 0;
784 av_freep(&h->thread_context[i]);
788 static void init_dequant8_coeff_table(H264Context *h)
791 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
793 for (i = 0; i < 6; i++) {
794 h->dequant8_coeff[i] = h->dequant8_buffer[i];
795 for (j = 0; j < i; j++)
796 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
797 64 * sizeof(uint8_t))) {
798 h->dequant8_coeff[i] = h->dequant8_buffer[j];
804 for (q = 0; q < max_qp + 1; q++) {
807 for (x = 0; x < 64; x++)
808 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
809 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
810 h->pps.scaling_matrix8[i][x]) << shift;
815 static void init_dequant4_coeff_table(H264Context *h)
818 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
819 for (i = 0; i < 6; i++) {
820 h->dequant4_coeff[i] = h->dequant4_buffer[i];
821 for (j = 0; j < i; j++)
822 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
823 16 * sizeof(uint8_t))) {
824 h->dequant4_coeff[i] = h->dequant4_buffer[j];
830 for (q = 0; q < max_qp + 1; q++) {
831 int shift = div6[q] + 2;
833 for (x = 0; x < 16; x++)
834 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
835 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
836 h->pps.scaling_matrix4[i][x]) << shift;
841 static void init_dequant_tables(H264Context *h)
844 init_dequant4_coeff_table(h);
845 if (h->pps.transform_8x8_mode)
846 init_dequant8_coeff_table(h);
847 if (h->sps.transform_bypass) {
848 for (i = 0; i < 6; i++)
849 for (x = 0; x < 16; x++)
850 h->dequant4_coeff[i][0][x] = 1 << 6;
851 if (h->pps.transform_8x8_mode)
852 for (i = 0; i < 6; i++)
853 for (x = 0; x < 64; x++)
854 h->dequant8_coeff[i][0][x] = 1 << 6;
858 int ff_h264_alloc_tables(H264Context *h)
860 MpegEncContext *const s = &h->s;
861 const int big_mb_num = s->mb_stride * (s->mb_height + 1);
862 const int row_mb_num = s->mb_stride * 2 * s->avctx->thread_count;
865 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
866 row_mb_num * 8 * sizeof(uint8_t), fail)
867 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
868 big_mb_num * 48 * sizeof(uint8_t), fail)
869 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
870 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
871 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
872 big_mb_num * sizeof(uint16_t), fail)
873 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
874 big_mb_num * sizeof(uint8_t), fail)
875 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
876 16 * row_mb_num * sizeof(uint8_t), fail);
877 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
878 16 * row_mb_num * sizeof(uint8_t), fail);
879 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
880 4 * big_mb_num * sizeof(uint8_t), fail);
881 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
882 big_mb_num * sizeof(uint8_t), fail)
884 memset(h->slice_table_base, -1,
885 (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
886 h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
888 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
889 big_mb_num * sizeof(uint32_t), fail);
890 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
891 big_mb_num * sizeof(uint32_t), fail);
892 for (y = 0; y < s->mb_height; y++)
893 for (x = 0; x < s->mb_width; x++) {
894 const int mb_xy = x + y * s->mb_stride;
895 const int b_xy = 4 * x + 4 * y * h->b_stride;
897 h->mb2b_xy[mb_xy] = b_xy;
898 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
901 if (!h->dequant4_coeff[0])
902 init_dequant_tables(h);
912 * Mimic alloc_tables(), but for every context thread.
914 static void clone_tables(H264Context *dst, H264Context *src, int i)
916 MpegEncContext *const s = &src->s;
917 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
918 dst->non_zero_count = src->non_zero_count;
919 dst->slice_table = src->slice_table;
920 dst->cbp_table = src->cbp_table;
921 dst->mb2b_xy = src->mb2b_xy;
922 dst->mb2br_xy = src->mb2br_xy;
923 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
924 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
925 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
926 dst->direct_table = src->direct_table;
927 dst->list_counts = src->list_counts;
928 dst->bipred_scratchpad = NULL;
929 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
930 src->sps.chroma_format_idc);
935 * Allocate buffers which are not shared amongst multiple threads.
937 static int context_init(H264Context *h)
939 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
940 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
941 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
942 h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
944 h->ref_cache[0][scan8[5] + 1] =
945 h->ref_cache[0][scan8[7] + 1] =
946 h->ref_cache[0][scan8[13] + 1] =
947 h->ref_cache[1][scan8[5] + 1] =
948 h->ref_cache[1][scan8[7] + 1] =
949 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
954 return -1; // free_tables will clean up for us
957 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
958 int parse_extradata);
960 static av_cold void common_init(H264Context *h)
962 MpegEncContext *const s = &h->s;
964 s->width = s->avctx->width;
965 s->height = s->avctx->height;
966 s->codec_id = s->avctx->codec->id;
968 ff_h264dsp_init(&h->h264dsp, 8, 1);
969 ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);
971 h->dequant_coeff_pps = -1;
972 s->unrestricted_mv = 1;
974 /* needed so that IDCT permutation is known early */
975 ff_dsputil_init(&s->dsp, s->avctx);
977 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
978 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
981 int ff_h264_decode_extradata(H264Context *h)
983 AVCodecContext *avctx = h->s.avctx;
985 if (avctx->extradata[0] == 1) {
987 unsigned char *p = avctx->extradata;
991 if (avctx->extradata_size < 7) {
992 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
995 /* sps and pps in the avcC always have length coded with 2 bytes,
996 * so put a fake nal_length_size = 2 while parsing them */
997 h->nal_length_size = 2;
998 // Decode sps from avcC
999 cnt = *(p + 5) & 0x1f; // Number of sps
1001 for (i = 0; i < cnt; i++) {
1002 nalsize = AV_RB16(p) + 2;
1003 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1005 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1006 av_log(avctx, AV_LOG_ERROR,
1007 "Decoding sps %d from avcC failed\n", i);
1012 // Decode pps from avcC
1013 cnt = *(p++); // Number of pps
1014 for (i = 0; i < cnt; i++) {
1015 nalsize = AV_RB16(p) + 2;
1016 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1018 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1019 av_log(avctx, AV_LOG_ERROR,
1020 "Decoding pps %d from avcC failed\n", i);
1025 // Now store right nal length size, that will be used to parse all other nals
1026 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1029 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1) < 0)
1035 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1037 H264Context *h = avctx->priv_data;
1038 MpegEncContext *const s = &h->s;
1041 ff_MPV_decode_defaults(s);
1046 s->out_format = FMT_H264;
1047 s->workaround_bugs = avctx->workaround_bugs;
1050 // s->decode_mb = ff_h263_decode_mb;
1051 s->quarter_sample = 1;
1052 if (!avctx->has_b_frames)
1055 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1057 ff_h264_decode_init_vlc();
1060 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1062 h->thread_context[0] = h;
1063 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1064 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1065 h->last_pocs[i] = INT_MIN;
1066 h->prev_poc_msb = 1 << 16;
1068 ff_h264_reset_sei(h);
1069 if (avctx->codec_id == AV_CODEC_ID_H264) {
1070 if (avctx->ticks_per_frame == 1)
1071 s->avctx->time_base.den *= 2;
1072 avctx->ticks_per_frame = 2;
1075 if (avctx->extradata_size > 0 && avctx->extradata &&
1076 ff_h264_decode_extradata(h))
1079 if (h->sps.bitstream_restriction_flag &&
1080 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1081 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1088 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1090 static void copy_picture_range(Picture **to, Picture **from, int count,
1091 MpegEncContext *new_base,
1092 MpegEncContext *old_base)
1096 for (i = 0; i < count; i++) {
1097 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1098 IN_RANGE(from[i], old_base->picture,
1099 sizeof(Picture) * old_base->picture_count) ||
1101 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1105 static void copy_parameter_set(void **to, void **from, int count, int size)
1109 for (i = 0; i < count; i++) {
1110 if (to[i] && !from[i])
1112 else if (from[i] && !to[i])
1113 to[i] = av_malloc(size);
1116 memcpy(to[i], from[i], size);
1120 static int decode_init_thread_copy(AVCodecContext *avctx)
1122 H264Context *h = avctx->priv_data;
1124 if (!avctx->internal->is_copy)
1126 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1127 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1129 h->s.context_initialized = 0;
1134 #define copy_fields(to, from, start_field, end_field) \
1135 memcpy(&to->start_field, &from->start_field, \
1136 (char *)&to->end_field - (char *)&to->start_field)
1138 static int decode_update_thread_context(AVCodecContext *dst,
1139 const AVCodecContext *src)
1141 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1142 MpegEncContext *const s = &h->s, *const s1 = &h1->s;
1143 int inited = s->context_initialized, err;
1146 if (dst == src || !s1->context_initialized)
1149 err = ff_mpeg_update_thread_context(dst, src);
1153 // FIXME handle width/height changing
1155 for (i = 0; i < MAX_SPS_COUNT; i++)
1156 av_freep(h->sps_buffers + i);
1158 for (i = 0; i < MAX_PPS_COUNT; i++)
1159 av_freep(h->pps_buffers + i);
1161 // copy all fields after MpegEnc
1162 memcpy(&h->s + 1, &h1->s + 1,
1163 sizeof(H264Context) - sizeof(MpegEncContext));
1164 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1165 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1166 if (ff_h264_alloc_tables(h) < 0) {
1167 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1168 return AVERROR(ENOMEM);
1172 for (i = 0; i < 2; i++) {
1173 h->rbsp_buffer[i] = NULL;
1174 h->rbsp_buffer_size[i] = 0;
1176 h->bipred_scratchpad = NULL;
1178 h->thread_context[0] = h;
1180 s->dsp.clear_blocks(h->mb);
1181 s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1184 /* frame_start may not be called for the next thread (if it's decoding
1185 * a bottom field) so this has to be allocated here */
1186 if (!h->bipred_scratchpad)
1187 h->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
1189 // extradata/NAL handling
1190 h->is_avc = h1->is_avc;
1193 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1194 MAX_SPS_COUNT, sizeof(SPS));
1196 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1197 MAX_PPS_COUNT, sizeof(PPS));
1200 // Dequantization matrices
1201 // FIXME these are big - can they be only copied when PPS changes?
1202 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1204 for (i = 0; i < 6; i++)
1205 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1206 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1208 for (i = 0; i < 6; i++)
1209 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1210 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1212 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1215 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1218 copy_fields(h, h1, ref_count, list_count);
1219 copy_fields(h, h1, ref_list, intra_gb);
1220 copy_fields(h, h1, short_ref, cabac_init_idc);
1222 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1223 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1224 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1225 MAX_DELAYED_PIC_COUNT + 2, s, s1);
1227 h->last_slice_type = h1->last_slice_type;
1229 if (!s->current_picture_ptr)
1232 if (!s->droppable) {
1233 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1234 h->prev_poc_msb = h->poc_msb;
1235 h->prev_poc_lsb = h->poc_lsb;
1237 h->prev_frame_num_offset = h->frame_num_offset;
1238 h->prev_frame_num = h->frame_num;
1239 h->outputed_poc = h->next_outputed_poc;
1244 int ff_h264_frame_start(H264Context *h)
1246 MpegEncContext *const s = &h->s;
1248 const int pixel_shift = h->pixel_shift;
1250 if (ff_MPV_frame_start(s, s->avctx) < 0)
1252 ff_er_frame_start(s);
1254 * ff_MPV_frame_start uses pict_type to derive key_frame.
1255 * This is incorrect for H.264; IDR markings must be used.
1256 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1257 * See decode_nal_units().
1259 s->current_picture_ptr->f.key_frame = 0;
1260 s->current_picture_ptr->mmco_reset = 0;
1262 assert(s->linesize && s->uvlinesize);
1264 for (i = 0; i < 16; i++) {
1265 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1266 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
1268 for (i = 0; i < 16; i++) {
1269 h->block_offset[16 + i] =
1270 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1271 h->block_offset[48 + 16 + i] =
1272 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1275 /* can't be in alloc_tables because linesize isn't known there.
1276 * FIXME: redo bipred weight to not require extra buffer? */
1277 for (i = 0; i < s->slice_context_count; i++)
1278 if (h->thread_context[i] && !h->thread_context[i]->bipred_scratchpad)
1279 h->thread_context[i]->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
1281 /* Some macroblocks can be accessed before they're available in case
1282 * of lost slices, MBAFF or threading. */
1283 memset(h->slice_table, -1,
1284 (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
1286 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1287 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1289 /* We mark the current picture as non-reference after allocating it, so
1290 * that if we break out due to an error it can be released automatically
1291 * in the next ff_MPV_frame_start().
1292 * SVQ3 as well as most other codecs have only last/next/current and thus
1293 * get released even with set reference, besides SVQ3 and others do not
1294 * mark frames as reference later "naturally". */
1295 if (s->codec_id != AV_CODEC_ID_SVQ3)
1296 s->current_picture_ptr->f.reference = 0;
1298 s->current_picture_ptr->field_poc[0] =
1299 s->current_picture_ptr->field_poc[1] = INT_MAX;
1301 h->next_output_pic = NULL;
1303 assert(s->current_picture_ptr->long_ref == 0);
1309 * Run setup operations that must be run after slice header decoding.
1310 * This includes finding the next displayed frame.
1312 * @param h h264 master context
1313 * @param setup_finished enough NALs have been read that we can call
1314 * ff_thread_finish_setup()
1316 static void decode_postinit(H264Context *h, int setup_finished)
1318 MpegEncContext *const s = &h->s;
1319 Picture *out = s->current_picture_ptr;
1320 Picture *cur = s->current_picture_ptr;
1321 int i, pics, out_of_order, out_idx;
1322 int invalid = 0, cnt = 0;
1324 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1325 s->current_picture_ptr->f.pict_type = s->pict_type;
1327 if (h->next_output_pic)
1330 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1331 /* FIXME: if we have two PAFF fields in one packet, we can't start
1332 * the next thread here. If we have one field per packet, we can.
1333 * The check in decode_nal_units() is not good enough to find this
1334 * yet, so we assume the worst for now. */
1335 // if (setup_finished)
1336 // ff_thread_finish_setup(s->avctx);
1340 cur->f.interlaced_frame = 0;
1341 cur->f.repeat_pict = 0;
1343 /* Signal interlacing information externally. */
1344 /* Prioritize picture timing SEI information over used
1345 * decoding process if it exists. */
1347 if (h->sps.pic_struct_present_flag) {
1348 switch (h->sei_pic_struct) {
1349 case SEI_PIC_STRUCT_FRAME:
1351 case SEI_PIC_STRUCT_TOP_FIELD:
1352 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1353 cur->f.interlaced_frame = 1;
1355 case SEI_PIC_STRUCT_TOP_BOTTOM:
1356 case SEI_PIC_STRUCT_BOTTOM_TOP:
1357 if (FIELD_OR_MBAFF_PICTURE)
1358 cur->f.interlaced_frame = 1;
1360 // try to flag soft telecine progressive
1361 cur->f.interlaced_frame = h->prev_interlaced_frame;
1363 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1364 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1365 /* Signal the possibility of telecined film externally
1366 * (pic_struct 5,6). From these hints, let the applications
1367 * decide if they apply deinterlacing. */
1368 cur->f.repeat_pict = 1;
1370 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1371 // Force progressive here, doubling interlaced frame is a bad idea.
1372 cur->f.repeat_pict = 2;
1374 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1375 cur->f.repeat_pict = 4;
1379 if ((h->sei_ct_type & 3) &&
1380 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1381 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1383 /* Derive interlacing flag from used decoding process. */
1384 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1386 h->prev_interlaced_frame = cur->f.interlaced_frame;
1388 if (cur->field_poc[0] != cur->field_poc[1]) {
1389 /* Derive top_field_first from field pocs. */
1390 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1392 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1393 /* Use picture timing SEI information. Even if it is a
1394 * information of a past frame, better than nothing. */
1395 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1396 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1397 cur->f.top_field_first = 1;
1399 cur->f.top_field_first = 0;
1401 /* Most likely progressive */
1402 cur->f.top_field_first = 0;
1406 // FIXME do something with unavailable reference frames
1408 /* Sort B-frames into display order */
1410 if (h->sps.bitstream_restriction_flag &&
1411 s->avctx->has_b_frames < h->sps.num_reorder_frames) {
1412 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1416 if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1417 !h->sps.bitstream_restriction_flag) {
1418 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1423 while (h->delayed_pic[pics])
1426 assert(pics <= MAX_DELAYED_PIC_COUNT);
1428 h->delayed_pic[pics++] = cur;
1429 if (cur->f.reference == 0)
1430 cur->f.reference = DELAYED_PIC_REF;
1432 /* Frame reordering. This code takes pictures from coding order and sorts
1433 * them by their incremental POC value into display order. It supports POC
1434 * gaps, MMCO reset codes and random resets.
1435 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1436 * and/or can be closed down with a MMCO reset code. In sequences where
1437 * there is no delay, we can't detect that (since the frame was already
1438 * output to the user), so we also set h->mmco_reset to detect the MMCO
1440 * FIXME: if we detect insufficient delays (as per s->avctx->has_b_frames),
1441 * we increase the delay between input and output. All frames affected by
1442 * the lag (e.g. those that should have been output before another frame
1443 * that we already returned to the user) will be dropped. This is a bug
1444 * that we will fix later. */
1445 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1446 cnt += out->poc < h->last_pocs[i];
1447 invalid += out->poc == INT_MIN;
1449 if (!h->mmco_reset && !cur->f.key_frame &&
1450 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1453 h->delayed_pic[pics - 2]->mmco_reset = 2;
1455 if (h->mmco_reset || cur->f.key_frame) {
1456 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1457 h->last_pocs[i] = INT_MIN;
1459 invalid = MAX_DELAYED_PIC_COUNT;
1461 out = h->delayed_pic[0];
1463 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1464 h->delayed_pic[i] &&
1465 !h->delayed_pic[i - 1]->mmco_reset &&
1466 !h->delayed_pic[i]->f.key_frame;
1468 if (h->delayed_pic[i]->poc < out->poc) {
1469 out = h->delayed_pic[i];
1472 if (s->avctx->has_b_frames == 0 &&
1473 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
1474 h->next_outputed_poc = INT_MIN;
1475 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1476 (out->poc < h->next_outputed_poc);
1478 if (h->sps.bitstream_restriction_flag &&
1479 s->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1480 } else if (out_of_order && pics - 1 == s->avctx->has_b_frames &&
1481 s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1482 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1483 s->avctx->has_b_frames = FFMAX(s->avctx->has_b_frames, cnt);
1486 } else if (s->low_delay &&
1487 ((h->next_outputed_poc != INT_MIN &&
1488 out->poc > h->next_outputed_poc + 2) ||
1489 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
1491 s->avctx->has_b_frames++;
1494 if (pics > s->avctx->has_b_frames) {
1495 out->f.reference &= ~DELAYED_PIC_REF;
1496 // for frame threading, the owner must be the second field's thread or
1497 // else the first thread can release the picture and reuse it unsafely
1499 for (i = out_idx; h->delayed_pic[i]; i++)
1500 h->delayed_pic[i] = h->delayed_pic[i + 1];
1502 memmove(h->last_pocs, &h->last_pocs[1],
1503 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1504 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1505 if (!out_of_order && pics > s->avctx->has_b_frames) {
1506 h->next_output_pic = out;
1507 if (out->mmco_reset) {
1509 h->next_outputed_poc = out->poc;
1510 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1512 h->next_outputed_poc = INT_MIN;
1515 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
1516 h->next_outputed_poc = INT_MIN;
1518 h->next_outputed_poc = out->poc;
1523 av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1527 ff_thread_finish_setup(s->avctx);
1530 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1531 uint8_t *src_cb, uint8_t *src_cr,
1532 int linesize, int uvlinesize,
1535 MpegEncContext *const s = &h->s;
1536 uint8_t *top_border;
1538 const int pixel_shift = h->pixel_shift;
1539 int chroma444 = CHROMA444;
1540 int chroma422 = CHROMA422;
1543 src_cb -= uvlinesize;
1544 src_cr -= uvlinesize;
1546 if (!simple && FRAME_MBAFF) {
1549 top_border = h->top_borders[0][s->mb_x];
1550 AV_COPY128(top_border, src_y + 15 * linesize);
1552 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1553 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1556 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1557 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1558 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1559 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1561 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1562 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1564 } else if (chroma422) {
1566 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1567 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1569 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1570 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1574 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1575 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1577 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1578 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1583 } else if (MB_MBAFF) {
1589 top_border = h->top_borders[top_idx][s->mb_x];
1590 /* There are two lines saved, the line above the top macroblock
1591 * of a pair, and the line above the bottom macroblock. */
1592 AV_COPY128(top_border, src_y + 16 * linesize);
1594 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1596 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1599 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1600 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1601 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1602 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1604 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1605 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1607 } else if (chroma422) {
1609 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1610 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1612 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1613 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1617 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1618 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1620 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1621 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1627 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1628 uint8_t *src_cb, uint8_t *src_cr,
1629 int linesize, int uvlinesize,
1630 int xchg, int chroma444,
1631 int simple, int pixel_shift)
1633 MpegEncContext *const s = &h->s;
1634 int deblock_topleft;
1637 uint8_t *top_border_m1;
1638 uint8_t *top_border;
1640 if (!simple && FRAME_MBAFF) {
1645 top_idx = MB_MBAFF ? 0 : 1;
1649 if (h->deblocking_filter == 2) {
1650 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1651 deblock_top = h->top_type;
1653 deblock_topleft = (s->mb_x > 0);
1654 deblock_top = (s->mb_y > !!MB_FIELD);
1657 src_y -= linesize + 1 + pixel_shift;
1658 src_cb -= uvlinesize + 1 + pixel_shift;
1659 src_cr -= uvlinesize + 1 + pixel_shift;
1661 top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
1662 top_border = h->top_borders[top_idx][s->mb_x];
1664 #define XCHG(a, b, xchg) \
1665 if (pixel_shift) { \
1667 AV_SWAP64(b + 0, a + 0); \
1668 AV_SWAP64(b + 8, a + 8); \
1678 if (deblock_topleft) {
1679 XCHG(top_border_m1 + (8 << pixel_shift),
1680 src_y - (7 << pixel_shift), 1);
1682 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1683 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1684 if (s->mb_x + 1 < s->mb_width) {
1685 XCHG(h->top_borders[top_idx][s->mb_x + 1],
1686 src_y + (17 << pixel_shift), 1);
1689 if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
1691 if (deblock_topleft) {
1692 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1693 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1695 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1696 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1697 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1698 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1699 if (s->mb_x + 1 < s->mb_width) {
1700 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1701 XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1705 if (deblock_topleft) {
1706 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1707 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1709 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
1710 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
1716 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
1719 if (high_bit_depth) {
1720 return AV_RN32A(((int32_t *)mb) + index);
1722 return AV_RN16A(mb + index);
1725 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
1726 int index, int value)
1728 if (high_bit_depth) {
1729 AV_WN32A(((int32_t *)mb) + index, value);
1731 AV_WN16A(mb + index, value);
1734 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
1735 int mb_type, int is_h264,
1737 int transform_bypass,
1741 uint8_t *dest_y, int p)
1743 MpegEncContext *const s = &h->s;
1744 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1745 void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1747 int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
1748 block_offset += 16 * p;
1749 if (IS_INTRA4x4(mb_type)) {
1750 if (simple || !s->encoding) {
1751 if (IS_8x8DCT(mb_type)) {
1752 if (transform_bypass) {
1754 idct_add = s->dsp.add_pixels8;
1756 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1757 idct_add = h->h264dsp.h264_idct8_add;
1759 for (i = 0; i < 16; i += 4) {
1760 uint8_t *const ptr = dest_y + block_offset[i];
1761 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1762 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1763 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1765 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1766 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
1767 (h->topright_samples_available << i) & 0x4000, linesize);
1769 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1770 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1772 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1777 if (transform_bypass) {
1779 idct_add = s->dsp.add_pixels4;
1781 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1782 idct_add = h->h264dsp.h264_idct_add;
1784 for (i = 0; i < 16; i++) {
1785 uint8_t *const ptr = dest_y + block_offset[i];
1786 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
1788 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
1789 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1794 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
1795 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
1796 assert(s->mb_y || linesize <= block_offset[i]);
1797 if (!topright_avail) {
1799 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
1800 topright = (uint8_t *)&tr_high;
1802 tr = ptr[3 - linesize] * 0x01010101u;
1803 topright = (uint8_t *)&tr;
1806 topright = ptr + (4 << pixel_shift) - linesize;
1810 h->hpc.pred4x4[dir](ptr, topright, linesize);
1811 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
1814 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1815 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1817 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
1818 } else if (CONFIG_SVQ3_DECODER)
1819 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
1826 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
1828 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
1829 if (!transform_bypass)
1830 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
1832 h->dequant4_coeff[p][qscale][0]);
1834 static const uint8_t dc_mapping[16] = {
1835 0 * 16, 1 * 16, 4 * 16, 5 * 16,
1836 2 * 16, 3 * 16, 6 * 16, 7 * 16,
1837 8 * 16, 9 * 16, 12 * 16, 13 * 16,
1838 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
1839 for (i = 0; i < 16; i++)
1840 dctcoef_set(h->mb + (p * 256 << pixel_shift),
1841 pixel_shift, dc_mapping[i],
1842 dctcoef_get(h->mb_luma_dc[p],
1846 } else if (CONFIG_SVQ3_DECODER)
1847 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
1848 h->mb_luma_dc[p], qscale);
1852 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
1853 int is_h264, int simple,
1854 int transform_bypass,
1858 uint8_t *dest_y, int p)
1860 MpegEncContext *const s = &h->s;
1861 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1863 block_offset += 16 * p;
1864 if (!IS_INTRA4x4(mb_type)) {
1866 if (IS_INTRA16x16(mb_type)) {
1867 if (transform_bypass) {
1868 if (h->sps.profile_idc == 244 &&
1869 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
1870 h->intra16x16_pred_mode == HOR_PRED8x8)) {
1871 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
1872 h->mb + (p * 256 << pixel_shift),
1875 for (i = 0; i < 16; i++)
1876 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
1877 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
1878 s->dsp.add_pixels4(dest_y + block_offset[i],
1879 h->mb + (i * 16 + p * 256 << pixel_shift),
1883 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
1884 h->mb + (p * 256 << pixel_shift),
1886 h->non_zero_count_cache + p * 5 * 8);
1888 } else if (h->cbp & 15) {
1889 if (transform_bypass) {
1890 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1891 idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
1892 : s->dsp.add_pixels4;
1893 for (i = 0; i < 16; i += di)
1894 if (h->non_zero_count_cache[scan8[i + p * 16]])
1895 idct_add(dest_y + block_offset[i],
1896 h->mb + (i * 16 + p * 256 << pixel_shift),
1899 if (IS_8x8DCT(mb_type))
1900 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
1901 h->mb + (p * 256 << pixel_shift),
1903 h->non_zero_count_cache + p * 5 * 8);
1905 h->h264dsp.h264_idct_add16(dest_y, block_offset,
1906 h->mb + (p * 256 << pixel_shift),
1908 h->non_zero_count_cache + p * 5 * 8);
1911 } else if (CONFIG_SVQ3_DECODER) {
1912 for (i = 0; i < 16; i++)
1913 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
1914 // FIXME benchmark weird rule, & below
1915 uint8_t *const ptr = dest_y + block_offset[i];
1916 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
1917 s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1925 #include "h264_mb_template.c"
1929 #include "h264_mb_template.c"
1933 #include "h264_mb_template.c"
1935 void ff_h264_hl_decode_mb(H264Context *h)
1937 MpegEncContext *const s = &h->s;
1938 const int mb_xy = h->mb_xy;
1939 const int mb_type = s->current_picture.f.mb_type[mb_xy];
1940 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1943 if (is_complex || h->pixel_shift)
1944 hl_decode_mb_444_complex(h);
1946 hl_decode_mb_444_simple_8(h);
1947 } else if (is_complex) {
1948 hl_decode_mb_complex(h);
1949 } else if (h->pixel_shift) {
1950 hl_decode_mb_simple_16(h);
1952 hl_decode_mb_simple_8(h);
1955 static int pred_weight_table(H264Context *h)
1957 MpegEncContext *const s = &h->s;
1959 int luma_def, chroma_def;
1962 h->use_weight_chroma = 0;
1963 h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
1964 if (h->sps.chroma_format_idc)
1965 h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
1966 luma_def = 1 << h->luma_log2_weight_denom;
1967 chroma_def = 1 << h->chroma_log2_weight_denom;
1969 for (list = 0; list < 2; list++) {
1970 h->luma_weight_flag[list] = 0;
1971 h->chroma_weight_flag[list] = 0;
1972 for (i = 0; i < h->ref_count[list]; i++) {
1973 int luma_weight_flag, chroma_weight_flag;
1975 luma_weight_flag = get_bits1(&s->gb);
1976 if (luma_weight_flag) {
1977 h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
1978 h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
1979 if (h->luma_weight[i][list][0] != luma_def ||
1980 h->luma_weight[i][list][1] != 0) {
1982 h->luma_weight_flag[list] = 1;
1985 h->luma_weight[i][list][0] = luma_def;
1986 h->luma_weight[i][list][1] = 0;
1989 if (h->sps.chroma_format_idc) {
1990 chroma_weight_flag = get_bits1(&s->gb);
1991 if (chroma_weight_flag) {
1993 for (j = 0; j < 2; j++) {
1994 h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
1995 h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
1996 if (h->chroma_weight[i][list][j][0] != chroma_def ||
1997 h->chroma_weight[i][list][j][1] != 0) {
1998 h->use_weight_chroma = 1;
1999 h->chroma_weight_flag[list] = 1;
2004 for (j = 0; j < 2; j++) {
2005 h->chroma_weight[i][list][j][0] = chroma_def;
2006 h->chroma_weight[i][list][j][1] = 0;
2011 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2014 h->use_weight = h->use_weight || h->use_weight_chroma;
2019 * Initialize implicit_weight table.
2020 * @param field 0/1 initialize the weight for interlaced MBAFF
2021 * -1 initializes the rest
2023 static void implicit_weight_table(H264Context *h, int field)
2025 MpegEncContext *const s = &h->s;
2026 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2028 for (i = 0; i < 2; i++) {
2029 h->luma_weight_flag[i] = 0;
2030 h->chroma_weight_flag[i] = 0;
2034 if (s->picture_structure == PICT_FRAME) {
2035 cur_poc = s->current_picture_ptr->poc;
2037 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2039 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2040 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2042 h->use_weight_chroma = 0;
2046 ref_count0 = h->ref_count[0];
2047 ref_count1 = h->ref_count[1];
2049 cur_poc = s->current_picture_ptr->field_poc[field];
2051 ref_count0 = 16 + 2 * h->ref_count[0];
2052 ref_count1 = 16 + 2 * h->ref_count[1];
2056 h->use_weight_chroma = 2;
2057 h->luma_log2_weight_denom = 5;
2058 h->chroma_log2_weight_denom = 5;
2060 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2061 int poc0 = h->ref_list[0][ref0].poc;
2062 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2064 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2065 int poc1 = h->ref_list[1][ref1].poc;
2066 int td = av_clip(poc1 - poc0, -128, 127);
2068 int tb = av_clip(cur_poc - poc0, -128, 127);
2069 int tx = (16384 + (FFABS(td) >> 1)) / td;
2070 int dist_scale_factor = (tb * tx + 32) >> 8;
2071 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2072 w = 64 - dist_scale_factor;
2076 h->implicit_weight[ref0][ref1][0] =
2077 h->implicit_weight[ref0][ref1][1] = w;
2079 h->implicit_weight[ref0][ref1][field] = w;
2086 * instantaneous decoder refresh.
2088 static void idr(H264Context *h)
2090 ff_h264_remove_all_refs(h);
2091 h->prev_frame_num = 0;
2092 h->prev_frame_num_offset = 0;
2094 h->prev_poc_lsb = 0;
2097 /* forget old pics after a seek */
2098 static void flush_dpb(AVCodecContext *avctx)
2100 H264Context *h = avctx->priv_data;
2102 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2103 if (h->delayed_pic[i])
2104 h->delayed_pic[i]->f.reference = 0;
2105 h->delayed_pic[i] = NULL;
2107 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2108 h->last_pocs[i] = INT_MIN;
2109 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2110 h->prev_interlaced_frame = 1;
2112 if (h->s.current_picture_ptr)
2113 h->s.current_picture_ptr->f.reference = 0;
2114 h->s.first_field = 0;
2115 ff_h264_reset_sei(h);
2116 ff_mpeg_flush(avctx);
2119 static int init_poc(H264Context *h)
2121 MpegEncContext *const s = &h->s;
2122 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2124 Picture *cur = s->current_picture_ptr;
2126 h->frame_num_offset = h->prev_frame_num_offset;
2127 if (h->frame_num < h->prev_frame_num)
2128 h->frame_num_offset += max_frame_num;
2130 if (h->sps.poc_type == 0) {
2131 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2133 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2134 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2135 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2136 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2138 h->poc_msb = h->prev_poc_msb;
2140 field_poc[1] = h->poc_msb + h->poc_lsb;
2141 if (s->picture_structure == PICT_FRAME)
2142 field_poc[1] += h->delta_poc_bottom;
2143 } else if (h->sps.poc_type == 1) {
2144 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2147 if (h->sps.poc_cycle_length != 0)
2148 abs_frame_num = h->frame_num_offset + h->frame_num;
2152 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2155 expected_delta_per_poc_cycle = 0;
2156 for (i = 0; i < h->sps.poc_cycle_length; i++)
2157 // FIXME integrate during sps parse
2158 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2160 if (abs_frame_num > 0) {
2161 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2162 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2164 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2165 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2166 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2170 if (h->nal_ref_idc == 0)
2171 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2173 field_poc[0] = expectedpoc + h->delta_poc[0];
2174 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2176 if (s->picture_structure == PICT_FRAME)
2177 field_poc[1] += h->delta_poc[1];
2179 int poc = 2 * (h->frame_num_offset + h->frame_num);
2181 if (!h->nal_ref_idc)
2188 if (s->picture_structure != PICT_BOTTOM_FIELD)
2189 s->current_picture_ptr->field_poc[0] = field_poc[0];
2190 if (s->picture_structure != PICT_TOP_FIELD)
2191 s->current_picture_ptr->field_poc[1] = field_poc[1];
2192 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2198 * initialize scan tables
2200 static void init_scan_tables(H264Context *h)
2203 for (i = 0; i < 16; i++) {
2204 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2205 h->zigzag_scan[i] = T(zigzag_scan[i]);
2206 h->field_scan[i] = T(field_scan[i]);
2209 for (i = 0; i < 64; i++) {
2210 #define T(x) (x >> 3) | ((x & 7) << 3)
2211 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2212 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2213 h->field_scan8x8[i] = T(field_scan8x8[i]);
2214 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2217 if (h->sps.transform_bypass) { // FIXME same ugly
2218 h->zigzag_scan_q0 = zigzag_scan;
2219 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2220 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2221 h->field_scan_q0 = field_scan;
2222 h->field_scan8x8_q0 = field_scan8x8;
2223 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2225 h->zigzag_scan_q0 = h->zigzag_scan;
2226 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2227 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2228 h->field_scan_q0 = h->field_scan;
2229 h->field_scan8x8_q0 = h->field_scan8x8;
2230 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2234 static int field_end(H264Context *h, int in_setup)
2236 MpegEncContext *const s = &h->s;
2237 AVCodecContext *const avctx = s->avctx;
2241 if (!in_setup && !s->droppable)
2242 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2243 s->picture_structure == PICT_BOTTOM_FIELD);
2245 if (CONFIG_H264_VDPAU_DECODER &&
2246 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2247 ff_vdpau_h264_set_reference_frames(s);
2249 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2250 if (!s->droppable) {
2251 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2252 h->prev_poc_msb = h->poc_msb;
2253 h->prev_poc_lsb = h->poc_lsb;
2255 h->prev_frame_num_offset = h->frame_num_offset;
2256 h->prev_frame_num = h->frame_num;
2257 h->outputed_poc = h->next_outputed_poc;
2260 if (avctx->hwaccel) {
2261 if (avctx->hwaccel->end_frame(avctx) < 0)
2262 av_log(avctx, AV_LOG_ERROR,
2263 "hardware accelerator failed to decode picture\n");
2266 if (CONFIG_H264_VDPAU_DECODER &&
2267 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2268 ff_vdpau_h264_picture_complete(s);
2271 * FIXME: Error handling code does not seem to support interlaced
2272 * when slices span multiple rows
2273 * The ff_er_add_slice calls don't work right for bottom
2274 * fields; they cause massive erroneous error concealing
2275 * Error marking covers both fields (top and bottom).
2276 * This causes a mismatched s->error_count
2277 * and a bad error table. Further, the error count goes to
2278 * INT_MAX when called for bottom field, because mb_y is
2279 * past end by one (callers fault) and resync_mb_y != 0
2280 * causes problems for the first MB line, too.
2285 ff_MPV_frame_end(s);
2287 h->current_slice = 0;
2293 * Replicate H264 "master" context to thread contexts.
2295 static void clone_slice(H264Context *dst, H264Context *src)
2297 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2298 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2299 dst->s.current_picture = src->s.current_picture;
2300 dst->s.linesize = src->s.linesize;
2301 dst->s.uvlinesize = src->s.uvlinesize;
2302 dst->s.first_field = src->s.first_field;
2304 dst->prev_poc_msb = src->prev_poc_msb;
2305 dst->prev_poc_lsb = src->prev_poc_lsb;
2306 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2307 dst->prev_frame_num = src->prev_frame_num;
2308 dst->short_ref_count = src->short_ref_count;
2310 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2311 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2312 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2313 memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
2315 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2316 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2320 * Compute profile from profile_idc and constraint_set?_flags.
2324 * @return profile as defined by FF_PROFILE_H264_*
2326 int ff_h264_get_profile(SPS *sps)
2328 int profile = sps->profile_idc;
2330 switch (sps->profile_idc) {
2331 case FF_PROFILE_H264_BASELINE:
2332 // constraint_set1_flag set to 1
2333 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2335 case FF_PROFILE_H264_HIGH_10:
2336 case FF_PROFILE_H264_HIGH_422:
2337 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2338 // constraint_set3_flag set to 1
2339 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2346 static int h264_set_parameter_from_sps(H264Context *h)
2348 MpegEncContext *s = &h->s;
2350 if (s->flags & CODEC_FLAG_LOW_DELAY ||
2351 (h->sps.bitstream_restriction_flag &&
2352 !h->sps.num_reorder_frames)) {
2353 if (s->avctx->has_b_frames > 1 || h->delayed_pic[0])
2354 av_log(h->s.avctx, AV_LOG_WARNING, "Delayed frames seen. "
2355 "Reenabling low delay requires a codec flush.\n");
2360 if (s->avctx->has_b_frames < 2)
2361 s->avctx->has_b_frames = !s->low_delay;
2363 if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2364 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2365 if (s->avctx->codec &&
2366 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2367 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2368 av_log(s->avctx, AV_LOG_ERROR,
2369 "VDPAU decoding does not support video colorspace.\n");
2370 return AVERROR_INVALIDDATA;
2372 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
2373 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2374 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2375 h->pixel_shift = h->sps.bit_depth_luma > 8;
2377 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2378 h->sps.chroma_format_idc);
2379 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma,
2380 h->sps.chroma_format_idc);
2381 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2382 ff_dsputil_init(&s->dsp, s->avctx);
2384 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2385 h->sps.bit_depth_luma);
2386 return AVERROR_INVALIDDATA;
2393 * Decode a slice header.
2394 * This will also call ff_MPV_common_init() and frame_start() as needed.
2396 * @param h h264context
2397 * @param h0 h264 master context (differs from 'h' when doing sliced based
2398 * parallel decoding)
2400 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2402 static int decode_slice_header(H264Context *h, H264Context *h0)
2404 MpegEncContext *const s = &h->s;
2405 MpegEncContext *const s0 = &h0->s;
2406 unsigned int first_mb_in_slice;
2407 unsigned int pps_id;
2408 int num_ref_idx_active_override_flag, max_refs, ret;
2409 unsigned int slice_type, tmp, i, j;
2410 int default_ref_list_done = 0;
2411 int last_pic_structure, last_pic_droppable;
2413 /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2414 if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
2415 !h->nal_ref_idc && !h->pixel_shift) {
2416 s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
2417 s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
2419 s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
2420 s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
2423 first_mb_in_slice = get_ue_golomb(&s->gb);
2425 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2426 if (h0->current_slice && FIELD_PICTURE) {
2430 h0->current_slice = 0;
2431 if (!s0->first_field) {
2432 if (s->current_picture_ptr && !s->droppable &&
2433 s->current_picture_ptr->owner2 == s) {
2434 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
2435 s->picture_structure == PICT_BOTTOM_FIELD);
2437 s->current_picture_ptr = NULL;
2441 slice_type = get_ue_golomb_31(&s->gb);
2442 if (slice_type > 9) {
2443 av_log(h->s.avctx, AV_LOG_ERROR,
2444 "slice type too large (%d) at %d %d\n",
2445 h->slice_type, s->mb_x, s->mb_y);
2448 if (slice_type > 4) {
2450 h->slice_type_fixed = 1;
2452 h->slice_type_fixed = 0;
2454 slice_type = golomb_to_pict_type[slice_type];
2455 if (slice_type == AV_PICTURE_TYPE_I ||
2456 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
2457 default_ref_list_done = 1;
2459 h->slice_type = slice_type;
2460 h->slice_type_nos = slice_type & 3;
2462 // to make a few old functions happy, it's wrong though
2463 s->pict_type = h->slice_type;
2465 pps_id = get_ue_golomb(&s->gb);
2466 if (pps_id >= MAX_PPS_COUNT) {
2467 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2470 if (!h0->pps_buffers[pps_id]) {
2471 av_log(h->s.avctx, AV_LOG_ERROR,
2472 "non-existing PPS %u referenced\n",
2476 h->pps = *h0->pps_buffers[pps_id];
2478 if (!h0->sps_buffers[h->pps.sps_id]) {
2479 av_log(h->s.avctx, AV_LOG_ERROR,
2480 "non-existing SPS %u referenced\n",
2485 if (h->pps.sps_id != h->current_sps_id ||
2486 h0->sps_buffers[h->pps.sps_id]->new) {
2487 h0->sps_buffers[h->pps.sps_id]->new = 0;
2489 h->current_sps_id = h->pps.sps_id;
2490 h->sps = *h0->sps_buffers[h->pps.sps_id];
2492 if ((ret = h264_set_parameter_from_sps(h)) < 0)
2496 s->avctx->profile = ff_h264_get_profile(&h->sps);
2497 s->avctx->level = h->sps.level_idc;
2498 s->avctx->refs = h->sps.ref_frame_count;
2500 s->mb_width = h->sps.mb_width;
2501 s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2503 h->b_stride = s->mb_width * 4;
2505 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2507 s->width = 16 * s->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
2508 if (h->sps.frame_mbs_only_flag)
2509 s->height = 16 * s->mb_height - (1 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2511 s->height = 16 * s->mb_height - (2 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
2513 if (FFALIGN(s->avctx->width, 16) == s->width &&
2514 FFALIGN(s->avctx->height, 16) == s->height) {
2515 s->width = s->avctx->width;
2516 s->height = s->avctx->height;
2519 if (s->context_initialized &&
2520 (s->width != s->avctx->width || s->height != s->avctx->height ||
2521 av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2522 if (h != h0 || (HAVE_THREADS && h->s.avctx->active_thread_type & FF_THREAD_FRAME)) {
2523 av_log_missing_feature(s->avctx,
2524 "Width/height changing with threads", 0);
2525 return AVERROR_PATCHWELCOME; // width / height changed during parallelized decoding
2528 flush_dpb(s->avctx);
2529 ff_MPV_common_end(s);
2531 if (!s->context_initialized) {
2533 av_log(h->s.avctx, AV_LOG_ERROR,
2534 "Cannot (re-)initialize context during parallel decoding.\n");
2538 avcodec_set_dimensions(s->avctx, s->width, s->height);
2539 s->avctx->sample_aspect_ratio = h->sps.sar;
2540 av_assert0(s->avctx->sample_aspect_ratio.den);
2542 if (h->sps.video_signal_type_present_flag) {
2543 s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
2545 if (h->sps.colour_description_present_flag) {
2546 s->avctx->color_primaries = h->sps.color_primaries;
2547 s->avctx->color_trc = h->sps.color_trc;
2548 s->avctx->colorspace = h->sps.colorspace;
2552 if (h->sps.timing_info_present_flag) {
2553 int64_t den = h->sps.time_scale;
2554 if (h->x264_build < 44U)
2556 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2557 h->sps.num_units_in_tick, den, 1 << 30);
2560 switch (h->sps.bit_depth_luma) {
2563 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2564 s->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
2566 s->avctx->pix_fmt = AV_PIX_FMT_YUV444P9;
2567 } else if (CHROMA422)
2568 s->avctx->pix_fmt = AV_PIX_FMT_YUV422P9;
2570 s->avctx->pix_fmt = AV_PIX_FMT_YUV420P9;
2574 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2575 s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
2577 s->avctx->pix_fmt = AV_PIX_FMT_YUV444P10;
2578 } else if (CHROMA422)
2579 s->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
2581 s->avctx->pix_fmt = AV_PIX_FMT_YUV420P10;
2585 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2586 s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
2588 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2589 : AV_PIX_FMT_YUV444P;
2590 } else if (CHROMA422) {
2591 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2592 : AV_PIX_FMT_YUV422P;
2594 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2595 s->avctx->codec->pix_fmts ?
2596 s->avctx->codec->pix_fmts :
2597 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2598 hwaccel_pixfmt_list_h264_jpeg_420 :
2599 ff_hwaccel_pixfmt_list_420);
2603 av_log(s->avctx, AV_LOG_ERROR,
2604 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2605 return AVERROR_INVALIDDATA;
2608 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
2611 if (ff_MPV_common_init(s) < 0) {
2612 av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
2616 h->prev_interlaced_frame = 1;
2618 init_scan_tables(h);
2619 if (ff_h264_alloc_tables(h) < 0) {
2620 av_log(h->s.avctx, AV_LOG_ERROR,
2621 "Could not allocate memory for h264\n");
2622 return AVERROR(ENOMEM);
2625 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
2626 if (context_init(h) < 0) {
2627 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2631 for (i = 1; i < s->slice_context_count; i++) {
2633 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2634 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2635 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2636 c->h264dsp = h->h264dsp;
2639 c->pixel_shift = h->pixel_shift;
2640 init_scan_tables(c);
2641 clone_tables(c, h, i);
2644 for (i = 0; i < s->slice_context_count; i++)
2645 if (context_init(h->thread_context[i]) < 0) {
2646 av_log(h->s.avctx, AV_LOG_ERROR,
2647 "context_init() failed.\n");
2653 if (h == h0 && h->dequant_coeff_pps != pps_id) {
2654 h->dequant_coeff_pps = pps_id;
2655 init_dequant_tables(h);
2658 h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
2661 h->mb_aff_frame = 0;
2662 last_pic_structure = s0->picture_structure;
2663 last_pic_droppable = s0->droppable;
2664 s->droppable = h->nal_ref_idc == 0;
2665 if (h->sps.frame_mbs_only_flag) {
2666 s->picture_structure = PICT_FRAME;
2668 if (get_bits1(&s->gb)) { // field_pic_flag
2669 s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
2671 s->picture_structure = PICT_FRAME;
2672 h->mb_aff_frame = h->sps.mb_aff;
2675 h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
2677 if (h0->current_slice != 0) {
2678 if (last_pic_structure != s->picture_structure ||
2679 last_pic_droppable != s->droppable) {
2680 av_log(h->s.avctx, AV_LOG_ERROR,
2681 "Changing field mode (%d -> %d) between slices is not allowed\n",
2682 last_pic_structure, s->picture_structure);
2683 s->picture_structure = last_pic_structure;
2684 s->droppable = last_pic_droppable;
2685 return AVERROR_INVALIDDATA;
2686 } else if (!s0->current_picture_ptr) {
2687 av_log(s->avctx, AV_LOG_ERROR,
2688 "unset current_picture_ptr on %d. slice\n",
2689 h0->current_slice + 1);
2690 return AVERROR_INVALIDDATA;
2693 /* Shorten frame num gaps so we don't have to allocate reference
2694 * frames just to throw them away */
2695 if (h->frame_num != h->prev_frame_num) {
2696 int unwrap_prev_frame_num = h->prev_frame_num;
2697 int max_frame_num = 1 << h->sps.log2_max_frame_num;
2699 if (unwrap_prev_frame_num > h->frame_num)
2700 unwrap_prev_frame_num -= max_frame_num;
2702 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2703 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2704 if (unwrap_prev_frame_num < 0)
2705 unwrap_prev_frame_num += max_frame_num;
2707 h->prev_frame_num = unwrap_prev_frame_num;
2711 /* See if we have a decoded first field looking for a pair...
2712 * Here, we're using that to see if we should mark previously
2713 * decode frames as "finished".
2714 * We have to do that before the "dummy" in-between frame allocation,
2715 * since that can modify s->current_picture_ptr. */
2716 if (s0->first_field) {
2717 assert(s0->current_picture_ptr);
2718 assert(s0->current_picture_ptr->f.data[0]);
2719 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2721 /* Mark old field/frame as completed */
2722 if (!last_pic_droppable && s0->current_picture_ptr->owner2 == s0) {
2723 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2724 last_pic_structure == PICT_BOTTOM_FIELD);
2727 /* figure out if we have a complementary field pair */
2728 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2729 /* Previous field is unmatched. Don't display it, but let it
2730 * remain for reference if marked as such. */
2731 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
2732 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2733 last_pic_structure == PICT_TOP_FIELD);
2736 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2737 /* This and previous field were reference, but had
2738 * different frame_nums. Consider this field first in
2739 * pair. Throw away previous field except for reference
2741 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
2742 ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
2743 last_pic_structure == PICT_TOP_FIELD);
2746 /* Second field in complementary pair */
2747 if (!((last_pic_structure == PICT_TOP_FIELD &&
2748 s->picture_structure == PICT_BOTTOM_FIELD) ||
2749 (last_pic_structure == PICT_BOTTOM_FIELD &&
2750 s->picture_structure == PICT_TOP_FIELD))) {
2751 av_log(s->avctx, AV_LOG_ERROR,
2752 "Invalid field mode combination %d/%d\n",
2753 last_pic_structure, s->picture_structure);
2754 s->picture_structure = last_pic_structure;
2755 s->droppable = last_pic_droppable;
2756 return AVERROR_INVALIDDATA;
2757 } else if (last_pic_droppable != s->droppable) {
2758 av_log(s->avctx, AV_LOG_ERROR,
2759 "Cannot combine reference and non-reference fields in the same frame\n");
2760 av_log_ask_for_sample(s->avctx, NULL);
2761 s->picture_structure = last_pic_structure;
2762 s->droppable = last_pic_droppable;
2763 return AVERROR_INVALIDDATA;
2766 /* Take ownership of this buffer. Note that if another thread owned
2767 * the first field of this buffer, we're not operating on that pointer,
2768 * so the original thread is still responsible for reporting progress
2769 * on that first field (or if that was us, we just did that above).
2770 * By taking ownership, we assign responsibility to ourselves to
2771 * report progress on the second field. */
2772 s0->current_picture_ptr->owner2 = s0;
2777 while (h->frame_num != h->prev_frame_num &&
2778 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
2779 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2780 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
2781 h->frame_num, h->prev_frame_num);
2782 if (ff_h264_frame_start(h) < 0)
2784 h->prev_frame_num++;
2785 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
2786 s->current_picture_ptr->frame_num = h->prev_frame_num;
2787 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
2788 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
2789 ff_generate_sliding_window_mmcos(h);
2790 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2791 (s->avctx->err_recognition & AV_EF_EXPLODE))
2792 return AVERROR_INVALIDDATA;
2793 /* Error concealment: if a ref is missing, copy the previous ref in its place.
2794 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2795 * about there being no actual duplicates.
2796 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
2797 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2799 if (h->short_ref_count) {
2801 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2802 (const uint8_t **)prev->f.data, prev->f.linesize,
2803 s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
2804 h->short_ref[0]->poc = prev->poc + 2;
2806 h->short_ref[0]->frame_num = h->prev_frame_num;
2810 /* See if we have a decoded first field looking for a pair...
2811 * We're using that to see whether to continue decoding in that
2812 * frame, or to allocate a new one. */
2813 if (s0->first_field) {
2814 assert(s0->current_picture_ptr);
2815 assert(s0->current_picture_ptr->f.data[0]);
2816 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2818 /* figure out if we have a complementary field pair */
2819 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2820 /* Previous field is unmatched. Don't display it, but let it
2821 * remain for reference if marked as such. */
2822 s0->current_picture_ptr = NULL;
2823 s0->first_field = FIELD_PICTURE;
2825 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2826 /* This and the previous field had different frame_nums.
2827 * Consider this field first in pair. Throw away previous
2828 * one except for reference purposes. */
2829 s0->first_field = 1;
2830 s0->current_picture_ptr = NULL;
2832 /* Second field in complementary pair */
2833 s0->first_field = 0;
2837 /* Frame or first field in a potentially complementary pair */
2838 s0->first_field = FIELD_PICTURE;
2841 if (!FIELD_PICTURE || s0->first_field) {
2842 if (ff_h264_frame_start(h) < 0) {
2843 s0->first_field = 0;
2847 ff_release_unused_pictures(s, 0);
2853 s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
2855 assert(s->mb_num == s->mb_width * s->mb_height);
2856 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2857 first_mb_in_slice >= s->mb_num) {
2858 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2861 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2862 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2863 if (s->picture_structure == PICT_BOTTOM_FIELD)
2864 s->resync_mb_y = s->mb_y = s->mb_y + 1;
2865 assert(s->mb_y < s->mb_height);
2867 if (s->picture_structure == PICT_FRAME) {
2868 h->curr_pic_num = h->frame_num;
2869 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
2871 h->curr_pic_num = 2 * h->frame_num + 1;
2872 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
2875 if (h->nal_unit_type == NAL_IDR_SLICE)
2876 get_ue_golomb(&s->gb); /* idr_pic_id */
2878 if (h->sps.poc_type == 0) {
2879 h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2881 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2882 h->delta_poc_bottom = get_se_golomb(&s->gb);
2885 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
2886 h->delta_poc[0] = get_se_golomb(&s->gb);
2888 if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
2889 h->delta_poc[1] = get_se_golomb(&s->gb);
2894 if (h->pps.redundant_pic_cnt_present)
2895 h->redundant_pic_count = get_ue_golomb(&s->gb);
2897 // set defaults, might be overridden a few lines later
2898 h->ref_count[0] = h->pps.ref_count[0];
2899 h->ref_count[1] = h->pps.ref_count[1];
2901 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2902 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2903 h->direct_spatial_mv_pred = get_bits1(&s->gb);
2904 num_ref_idx_active_override_flag = get_bits1(&s->gb);
2906 if (num_ref_idx_active_override_flag) {
2907 h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
2908 if (h->ref_count[0] < 1)
2909 return AVERROR_INVALIDDATA;
2910 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
2911 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
2912 if (h->ref_count[1] < 1)
2913 return AVERROR_INVALIDDATA;
2917 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
2924 max_refs = s->picture_structure == PICT_FRAME ? 16 : 32;
2926 if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
2927 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2928 h->ref_count[0] = h->ref_count[1] = 1;
2929 return AVERROR_INVALIDDATA;
2932 if (!default_ref_list_done)
2933 ff_h264_fill_default_ref_list(h);
2935 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
2936 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
2937 h->ref_count[1] = h->ref_count[0] = 0;
2941 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
2942 s->last_picture_ptr = &h->ref_list[0][0];
2943 s->last_picture_ptr->owner2 = s;
2944 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2946 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
2947 s->next_picture_ptr = &h->ref_list[1][0];
2948 s->next_picture_ptr->owner2 = s;
2949 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2952 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
2953 (h->pps.weighted_bipred_idc == 1 &&
2954 h->slice_type_nos == AV_PICTURE_TYPE_B))
2955 pred_weight_table(h);
2956 else if (h->pps.weighted_bipred_idc == 2 &&
2957 h->slice_type_nos == AV_PICTURE_TYPE_B) {
2958 implicit_weight_table(h, -1);
2961 for (i = 0; i < 2; i++) {
2962 h->luma_weight_flag[i] = 0;
2963 h->chroma_weight_flag[i] = 0;
2967 if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
2968 (s->avctx->err_recognition & AV_EF_EXPLODE))
2969 return AVERROR_INVALIDDATA;
2972 ff_h264_fill_mbaff_ref_list(h);
2974 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
2975 implicit_weight_table(h, 0);
2976 implicit_weight_table(h, 1);
2980 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
2981 ff_h264_direct_dist_scale_factor(h);
2982 ff_h264_direct_ref_list_init(h);
2984 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
2985 tmp = get_ue_golomb_31(&s->gb);
2987 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2990 h->cabac_init_idc = tmp;
2993 h->last_qscale_diff = 0;
2994 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2995 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
2996 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3000 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3001 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3002 // FIXME qscale / qp ... stuff
3003 if (h->slice_type == AV_PICTURE_TYPE_SP)
3004 get_bits1(&s->gb); /* sp_for_switch_flag */
3005 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3006 h->slice_type == AV_PICTURE_TYPE_SI)
3007 get_se_golomb(&s->gb); /* slice_qs_delta */
3009 h->deblocking_filter = 1;
3010 h->slice_alpha_c0_offset = 52;
3011 h->slice_beta_offset = 52;
3012 if (h->pps.deblocking_filter_parameters_present) {
3013 tmp = get_ue_golomb_31(&s->gb);
3015 av_log(s->avctx, AV_LOG_ERROR,
3016 "deblocking_filter_idc %u out of range\n", tmp);
3019 h->deblocking_filter = tmp;
3020 if (h->deblocking_filter < 2)
3021 h->deblocking_filter ^= 1; // 1<->0
3023 if (h->deblocking_filter) {
3024 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3025 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3026 if (h->slice_alpha_c0_offset > 104U ||
3027 h->slice_beta_offset > 104U) {
3028 av_log(s->avctx, AV_LOG_ERROR,
3029 "deblocking filter parameters %d %d out of range\n",
3030 h->slice_alpha_c0_offset, h->slice_beta_offset);
3036 if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3037 (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3038 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3039 (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3040 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3041 (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3042 h->nal_ref_idc == 0))
3043 h->deblocking_filter = 0;
3045 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3046 if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
3047 /* Cheat slightly for speed:
3048 * Do not bother to deblock across slices. */
3049 h->deblocking_filter = 2;
3051 h0->max_contexts = 1;
3052 if (!h0->single_decode_warning) {
3053 av_log(s->avctx, AV_LOG_INFO,
3054 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3055 h0->single_decode_warning = 1;
3058 av_log(h->s.avctx, AV_LOG_ERROR,
3059 "Deblocking switched inside frame.\n");
3064 h->qp_thresh = 15 + 52 -
3065 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3067 h->pps.chroma_qp_index_offset[0],
3068 h->pps.chroma_qp_index_offset[1]) +
3069 6 * (h->sps.bit_depth_luma - 8);
3071 h0->last_slice_type = slice_type;
3072 h->slice_num = ++h0->current_slice;
3073 if (h->slice_num >= MAX_SLICES) {
3074 av_log(s->avctx, AV_LOG_ERROR,
3075 "Too many slices, increase MAX_SLICES and recompile\n");
3078 for (j = 0; j < 2; j++) {
3080 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3081 for (i = 0; i < 16; i++) {
3083 if (h->ref_list[j][i].f.data[0]) {
3085 uint8_t *base = h->ref_list[j][i].f.base[0];
3086 for (k = 0; k < h->short_ref_count; k++)
3087 if (h->short_ref[k]->f.base[0] == base) {
3091 for (k = 0; k < h->long_ref_count; k++)
3092 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3093 id_list[i] = h->short_ref_count + k;
3101 for (i = 0; i < 16; i++)
3102 ref2frm[i + 2] = 4 * id_list[i] +
3103 (h->ref_list[j][i].f.reference & 3);
3105 ref2frm[18 + 1] = -1;
3106 for (i = 16; i < 48; i++)
3107 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3108 (h->ref_list[j][i].f.reference & 3);
3111 // FIXME: fix draw_edges + PAFF + frame threads
3112 h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
3113 (!h->sps.frame_mbs_only_flag &&
3114 s->avctx->active_thread_type))
3116 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3118 if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3119 av_log(h->s.avctx, AV_LOG_DEBUG,
3120 "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",
3122 (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3124 av_get_picture_type_char(h->slice_type),
3125 h->slice_type_fixed ? " fix" : "",
3126 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3127 pps_id, h->frame_num,
3128 s->current_picture_ptr->field_poc[0],
3129 s->current_picture_ptr->field_poc[1],
3130 h->ref_count[0], h->ref_count[1],
3132 h->deblocking_filter,
3133 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3135 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3136 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3142 int ff_h264_get_slice_type(const H264Context *h)
3144 switch (h->slice_type) {
3145 case AV_PICTURE_TYPE_P:
3147 case AV_PICTURE_TYPE_B:
3149 case AV_PICTURE_TYPE_I:
3151 case AV_PICTURE_TYPE_SP:
3153 case AV_PICTURE_TYPE_SI:
3160 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3161 MpegEncContext *const s,
3162 int mb_type, int top_xy,
3163 int left_xy[LEFT_MBS],
3165 int left_type[LEFT_MBS],
3166 int mb_xy, int list)
3168 int b_stride = h->b_stride;
3169 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3170 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3171 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3172 if (USES_LIST(top_type, list)) {
3173 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3174 const int b8_xy = 4 * top_xy + 2;
3175 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3176 AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
3177 ref_cache[0 - 1 * 8] =
3178 ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3179 ref_cache[2 - 1 * 8] =
3180 ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3182 AV_ZERO128(mv_dst - 1 * 8);
3183 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3186 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3187 if (USES_LIST(left_type[LTOP], list)) {
3188 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3189 const int b8_xy = 4 * left_xy[LTOP] + 1;
3190 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3191 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
3192 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
3193 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
3194 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
3196 ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
3197 ref_cache[-1 + 16] =
3198 ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
3200 AV_ZERO32(mv_dst - 1 + 0);
3201 AV_ZERO32(mv_dst - 1 + 8);
3202 AV_ZERO32(mv_dst - 1 + 16);
3203 AV_ZERO32(mv_dst - 1 + 24);
3206 ref_cache[-1 + 16] =
3207 ref_cache[-1 + 24] = LIST_NOT_USED;
3212 if (!USES_LIST(mb_type, list)) {
3213 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3214 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3215 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3216 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3217 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3222 int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
3223 int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
3224 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3225 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3226 AV_WN32A(&ref_cache[0 * 8], ref01);
3227 AV_WN32A(&ref_cache[1 * 8], ref01);
3228 AV_WN32A(&ref_cache[2 * 8], ref23);
3229 AV_WN32A(&ref_cache[3 * 8], ref23);
3233 int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
3234 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3235 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3236 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3237 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3243 * @return non zero if the loop filter can be skipped
3245 static int fill_filter_caches(H264Context *h, int mb_type)
3247 MpegEncContext *const s = &h->s;
3248 const int mb_xy = h->mb_xy;
3249 int top_xy, left_xy[LEFT_MBS];
3250 int top_type, left_type[LEFT_MBS];
3254 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3256 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3257 * stuff, I can't imagine that these complex rules are worth it. */
3259 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3261 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3262 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3264 if (left_mb_field_flag != curr_mb_field_flag)
3265 left_xy[LTOP] -= s->mb_stride;
3267 if (curr_mb_field_flag)
3268 top_xy += s->mb_stride &
3269 (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3270 if (left_mb_field_flag != curr_mb_field_flag)
3271 left_xy[LBOT] += s->mb_stride;
3275 h->top_mb_xy = top_xy;
3276 h->left_mb_xy[LTOP] = left_xy[LTOP];
3277 h->left_mb_xy[LBOT] = left_xy[LBOT];
3279 /* For sufficiently low qp, filtering wouldn't do anything.
3280 * This is a conservative estimate: could also check beta_offset
3281 * and more accurate chroma_qp. */
3282 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3283 int qp = s->current_picture.f.qscale_table[mb_xy];
3284 if (qp <= qp_thresh &&
3285 (left_xy[LTOP] < 0 ||
3286 ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3288 ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3291 if ((left_xy[LTOP] < 0 ||
3292 ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3293 (top_xy < s->mb_stride ||
3294 ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3299 top_type = s->current_picture.f.mb_type[top_xy];
3300 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3301 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3302 if (h->deblocking_filter == 2) {
3303 if (h->slice_table[top_xy] != h->slice_num)
3305 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3306 left_type[LTOP] = left_type[LBOT] = 0;
3308 if (h->slice_table[top_xy] == 0xFFFF)
3310 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3311 left_type[LTOP] = left_type[LBOT] = 0;
3313 h->top_type = top_type;
3314 h->left_type[LTOP] = left_type[LTOP];
3315 h->left_type[LBOT] = left_type[LBOT];
3317 if (IS_INTRA(mb_type))
3320 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3321 top_type, left_type, mb_xy, 0);
3322 if (h->list_count == 2)
3323 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
3324 top_type, left_type, mb_xy, 1);
3326 nnz = h->non_zero_count[mb_xy];
3327 nnz_cache = h->non_zero_count_cache;
3328 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3329 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3330 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3331 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3332 h->cbp = h->cbp_table[mb_xy];
3335 nnz = h->non_zero_count[top_xy];
3336 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3339 if (left_type[LTOP]) {
3340 nnz = h->non_zero_count[left_xy[LTOP]];
3341 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3342 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3343 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3344 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3347 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3348 * from what the loop filter needs */
3349 if (!CABAC && h->pps.transform_8x8_mode) {
3350 if (IS_8x8DCT(top_type)) {
3351 nnz_cache[4 + 8 * 0] =
3352 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3353 nnz_cache[6 + 8 * 0] =
3354 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3356 if (IS_8x8DCT(left_type[LTOP])) {
3357 nnz_cache[3 + 8 * 1] =
3358 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3360 if (IS_8x8DCT(left_type[LBOT])) {
3361 nnz_cache[3 + 8 * 3] =
3362 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3365 if (IS_8x8DCT(mb_type)) {
3366 nnz_cache[scan8[0]] =
3367 nnz_cache[scan8[1]] =
3368 nnz_cache[scan8[2]] =
3369 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3371 nnz_cache[scan8[0 + 4]] =
3372 nnz_cache[scan8[1 + 4]] =
3373 nnz_cache[scan8[2 + 4]] =
3374 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3376 nnz_cache[scan8[0 + 8]] =
3377 nnz_cache[scan8[1 + 8]] =
3378 nnz_cache[scan8[2 + 8]] =
3379 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3381 nnz_cache[scan8[0 + 12]] =
3382 nnz_cache[scan8[1 + 12]] =
3383 nnz_cache[scan8[2 + 12]] =
3384 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3391 static void loop_filter(H264Context *h, int start_x, int end_x)
3393 MpegEncContext *const s = &h->s;
3394 uint8_t *dest_y, *dest_cb, *dest_cr;
3395 int linesize, uvlinesize, mb_x, mb_y;
3396 const int end_mb_y = s->mb_y + FRAME_MBAFF;
3397 const int old_slice_type = h->slice_type;
3398 const int pixel_shift = h->pixel_shift;
3399 const int block_h = 16 >> s->chroma_y_shift;
3401 if (h->deblocking_filter) {
3402 for (mb_x = start_x; mb_x < end_x; mb_x++)
3403 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
3405 mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
3406 h->slice_num = h->slice_table[mb_xy];
3407 mb_type = s->current_picture.f.mb_type[mb_xy];
3408 h->list_count = h->list_counts[mb_xy];
3412 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3416 dest_y = s->current_picture.f.data[0] +
3417 ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
3418 dest_cb = s->current_picture.f.data[1] +
3419 (mb_x << pixel_shift) * (8 << CHROMA444) +
3420 mb_y * s->uvlinesize * block_h;
3421 dest_cr = s->current_picture.f.data[2] +
3422 (mb_x << pixel_shift) * (8 << CHROMA444) +
3423 mb_y * s->uvlinesize * block_h;
3424 // FIXME simplify above
3427 linesize = h->mb_linesize = s->linesize * 2;
3428 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3429 if (mb_y & 1) { // FIXME move out of this function?
3430 dest_y -= s->linesize * 15;
3431 dest_cb -= s->uvlinesize * (block_h - 1);
3432 dest_cr -= s->uvlinesize * (block_h - 1);
3435 linesize = h->mb_linesize = s->linesize;
3436 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3438 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
3440 if (fill_filter_caches(h, mb_type))
3442 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3443 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3446 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
3447 linesize, uvlinesize);
3449 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
3450 dest_cr, linesize, uvlinesize);
3454 h->slice_type = old_slice_type;
3456 s->mb_y = end_mb_y - FRAME_MBAFF;
3457 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3458 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3461 static void predict_field_decoding_flag(H264Context *h)
3463 MpegEncContext *const s = &h->s;
3464 const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
3465 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
3466 s->current_picture.f.mb_type[mb_xy - 1] :
3467 (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
3468 s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
3469 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3473 * Draw edges and report progress for the last MB row.
3475 static void decode_finish_row(H264Context *h)
3477 MpegEncContext *const s = &h->s;
3478 int top = 16 * (s->mb_y >> FIELD_PICTURE);
3479 int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
3480 int height = 16 << FRAME_MBAFF;
3481 int deblock_border = (16 + 4) << FRAME_MBAFF;
3483 if (h->deblocking_filter) {
3484 if ((top + height) >= pic_height)
3485 height += deblock_border;
3486 top -= deblock_border;
3489 if (top >= pic_height || (top + height) < h->emu_edge_height)
3492 height = FFMIN(height, pic_height - top);
3493 if (top < h->emu_edge_height) {
3494 height = top + height;
3498 ff_draw_horiz_band(s, top, height);
3503 ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
3504 s->picture_structure == PICT_BOTTOM_FIELD);
3507 static int decode_slice(struct AVCodecContext *avctx, void *arg)
3509 H264Context *h = *(void **)arg;
3510 MpegEncContext *const s = &h->s;
3511 const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
3513 int lf_x_start = s->mb_x;
3515 s->mb_skip_run = -1;
3517 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
3518 s->codec_id != AV_CODEC_ID_H264 ||
3519 (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
3523 align_get_bits(&s->gb);
3526 ff_init_cabac_states(&h->cabac);
3527 ff_init_cabac_decoder(&h->cabac,
3528 s->gb.buffer + get_bits_count(&s->gb) / 8,
3529 (get_bits_left(&s->gb) + 7) / 8);
3531 ff_h264_init_cabac_states(h);
3535 int ret = ff_h264_decode_mb_cabac(h);
3537 // STOP_TIMER("decode_mb_cabac")
3540 ff_h264_hl_decode_mb(h);
3542 // FIXME optimal? or let mb_decode decode 16x32 ?
3543 if (ret >= 0 && FRAME_MBAFF) {
3546 ret = ff_h264_decode_mb_cabac(h);
3549 ff_h264_hl_decode_mb(h);
3552 eos = get_cabac_terminate(&h->cabac);
3554 if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
3555 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3556 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3557 s->mb_y, ER_MB_END & part_mask);
3558 if (s->mb_x >= lf_x_start)
3559 loop_filter(h, lf_x_start, s->mb_x + 1);
3562 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3563 av_log(h->s.avctx, AV_LOG_ERROR,
3564 "error while decoding MB %d %d, bytestream (%td)\n",
3566 h->cabac.bytestream_end - h->cabac.bytestream);
3567 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3568 s->mb_y, ER_MB_ERROR & part_mask);
3572 if (++s->mb_x >= s->mb_width) {
3573 loop_filter(h, lf_x_start, s->mb_x);
3574 s->mb_x = lf_x_start = 0;
3575 decode_finish_row(h);
3577 if (FIELD_OR_MBAFF_PICTURE) {
3579 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3580 predict_field_decoding_flag(h);
3584 if (eos || s->mb_y >= s->mb_height) {
3585 tprintf(s->avctx, "slice end %d %d\n",
3586 get_bits_count(&s->gb), s->gb.size_in_bits);
3587 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
3588 s->mb_y, ER_MB_END & part_mask);
3589 if (s->mb_x > lf_x_start)
3590 loop_filter(h, lf_x_start, s->mb_x);
3596 int ret = ff_h264_decode_mb_cavlc(h);
3599 ff_h264_hl_decode_mb(h);
3601 // FIXME optimal? or let mb_decode decode 16x32 ?
3602 if (ret >= 0 && FRAME_MBAFF) {
3604 ret = ff_h264_decode_mb_cavlc(h);
3607 ff_h264_hl_decode_mb(h);
3612 av_log(h->s.avctx, AV_LOG_ERROR,
3613 "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3614 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3615 s->mb_y, ER_MB_ERROR & part_mask);
3619 if (++s->mb_x >= s->mb_width) {
3620 loop_filter(h, lf_x_start, s->mb_x);
3621 s->mb_x = lf_x_start = 0;
3622 decode_finish_row(h);
3624 if (FIELD_OR_MBAFF_PICTURE) {
3626 if (FRAME_MBAFF && s->mb_y < s->mb_height)
3627 predict_field_decoding_flag(h);
3629 if (s->mb_y >= s->mb_height) {
3630 tprintf(s->avctx, "slice end %d %d\n",
3631 get_bits_count(&s->gb), s->gb.size_in_bits);
3633 if (get_bits_left(&s->gb) == 0) {
3634 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3635 s->mb_x - 1, s->mb_y,
3636 ER_MB_END & part_mask);
3640 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3641 s->mb_x - 1, s->mb_y,
3642 ER_MB_END & part_mask);
3649 if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
3650 tprintf(s->avctx, "slice end %d %d\n",
3651 get_bits_count(&s->gb), s->gb.size_in_bits);
3652 if (get_bits_left(&s->gb) == 0) {
3653 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
3654 s->mb_x - 1, s->mb_y,
3655 ER_MB_END & part_mask);
3656 if (s->mb_x > lf_x_start)
3657 loop_filter(h, lf_x_start, s->mb_x);
3661 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
3662 s->mb_y, ER_MB_ERROR & part_mask);
3672 * Call decode_slice() for each context.
3674 * @param h h264 master context
3675 * @param context_count number of contexts to execute
3677 static int execute_decode_slices(H264Context *h, int context_count)
3679 MpegEncContext *const s = &h->s;
3680 AVCodecContext *const avctx = s->avctx;
3684 if (s->avctx->hwaccel ||
3685 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3687 if (context_count == 1) {
3688 return decode_slice(avctx, &h);
3690 for (i = 1; i < context_count; i++) {
3691 hx = h->thread_context[i];
3692 hx->s.err_recognition = avctx->err_recognition;
3693 hx->s.error_count = 0;
3696 avctx->execute(avctx, decode_slice, h->thread_context,
3697 NULL, context_count, sizeof(void *));
3699 /* pull back stuff from slices to master context */
3700 hx = h->thread_context[context_count - 1];
3701 s->mb_x = hx->s.mb_x;
3702 s->mb_y = hx->s.mb_y;
3703 s->droppable = hx->s.droppable;
3704 s->picture_structure = hx->s.picture_structure;
3705 for (i = 1; i < context_count; i++)
3706 h->s.error_count += h->thread_context[i]->s.error_count;
3712 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
3713 int parse_extradata)
3715 MpegEncContext *const s = &h->s;
3716 AVCodecContext *const avctx = s->avctx;
3717 H264Context *hx; ///< thread context
3721 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
3722 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
3725 h->max_contexts = s->slice_context_count;
3726 if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3727 h->current_slice = 0;
3728 if (!s->first_field)
3729 s->current_picture_ptr = NULL;
3730 ff_h264_reset_sei(h);
3733 for (; pass <= 1; pass++) {
3736 next_avc = h->is_avc ? 0 : buf_size;
3746 if (buf_index >= next_avc) {
3747 if (buf_index >= buf_size - h->nal_length_size)
3750 for (i = 0; i < h->nal_length_size; i++)
3751 nalsize = (nalsize << 8) | buf[buf_index++];
3752 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
3753 av_log(h->s.avctx, AV_LOG_ERROR,
3754 "AVC: nal size %d\n", nalsize);
3757 next_avc = buf_index + nalsize;
3759 // start code prefix search
3760 for (; buf_index + 3 < next_avc; buf_index++)
3761 // This should always succeed in the first iteration.
3762 if (buf[buf_index] == 0 &&
3763 buf[buf_index + 1] == 0 &&
3764 buf[buf_index + 2] == 1)
3767 if (buf_index + 3 >= buf_size) {
3768 buf_index = buf_size;
3773 if (buf_index >= next_avc)
3777 hx = h->thread_context[context_count];
3779 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
3780 &consumed, next_avc - buf_index);
3781 if (ptr == NULL || dst_length < 0) {
3785 i = buf_index + consumed;
3786 if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
3787 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
3788 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
3789 s->workaround_bugs |= FF_BUG_TRUNCATED;
3791 if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
3792 while (ptr[dst_length - 1] == 0 && dst_length > 0)
3794 bit_length = !dst_length ? 0
3796 decode_rbsp_trailing(h, ptr + dst_length - 1));
3798 if (s->avctx->debug & FF_DEBUG_STARTCODE)
3799 av_log(h->s.avctx, AV_LOG_DEBUG,
3800 "NAL %d at %d/%d length %d\n",
3801 hx->nal_unit_type, buf_index, buf_size, dst_length);
3803 if (h->is_avc && (nalsize != consumed) && nalsize)
3804 av_log(h->s.avctx, AV_LOG_DEBUG,
3805 "AVC: Consumed only %d bytes instead of %d\n",
3808 buf_index += consumed;
3812 /* packets can sometimes contain multiple PPS/SPS,
3813 * e.g. two PAFF field pictures in one packet, or a demuxer
3814 * which splits NALs strangely if so, when frame threading we
3815 * can't start the next thread until we've read all of them */
3816 switch (hx->nal_unit_type) {
3819 nals_needed = nal_index;
3824 init_get_bits(&hx->s.gb, ptr, bit_length);
3825 if (!get_ue_golomb(&hx->s.gb))
3826 nals_needed = nal_index;
3831 // FIXME do not discard SEI id
3832 if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
3836 /* Ignore every NAL unit type except PPS and SPS during extradata
3837 * parsing. Decoding slices is not possible in codec init
3839 if (parse_extradata && HAVE_THREADS &&
3840 (s->avctx->active_thread_type & FF_THREAD_FRAME) &&
3841 (hx->nal_unit_type != NAL_PPS &&
3842 hx->nal_unit_type != NAL_SPS)) {
3843 av_log(avctx, AV_LOG_INFO, "Ignoring NAL unit %d during "
3844 "extradata parsing\n", hx->nal_unit_type);
3845 hx->nal_unit_type = NAL_FF_IGNORE;
3848 switch (hx->nal_unit_type) {
3850 if (h->nal_unit_type != NAL_IDR_SLICE) {
3851 av_log(h->s.avctx, AV_LOG_ERROR,
3852 "Invalid mix of idr and non-idr slices\n");
3856 idr(h); // FIXME ensure we don't lose some frames if there is reordering
3858 init_get_bits(&hx->s.gb, ptr, bit_length);
3860 hx->inter_gb_ptr = &hx->s.gb;
3861 hx->s.data_partitioning = 0;
3863 if ((err = decode_slice_header(hx, h)))
3866 s->current_picture_ptr->f.key_frame |=
3867 (hx->nal_unit_type == NAL_IDR_SLICE) ||
3868 (h->sei_recovery_frame_cnt >= 0);
3870 if (h->current_slice == 1) {
3871 if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
3872 decode_postinit(h, nal_index >= nals_needed);
3874 if (s->avctx->hwaccel &&
3875 s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3877 if (CONFIG_H264_VDPAU_DECODER &&
3878 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3879 ff_vdpau_h264_picture_start(s);
3882 if (hx->redundant_pic_count == 0 &&
3883 (avctx->skip_frame < AVDISCARD_NONREF ||
3885 (avctx->skip_frame < AVDISCARD_BIDIR ||
3886 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
3887 (avctx->skip_frame < AVDISCARD_NONKEY ||
3888 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
3889 avctx->skip_frame < AVDISCARD_ALL) {
3890 if (avctx->hwaccel) {
3891 if (avctx->hwaccel->decode_slice(avctx,
3892 &buf[buf_index - consumed],
3895 } else if (CONFIG_H264_VDPAU_DECODER &&
3896 s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
3897 static const uint8_t start_code[] = {
3899 ff_vdpau_add_data_chunk(s, start_code,
3900 sizeof(start_code));
3901 ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
3908 init_get_bits(&hx->s.gb, ptr, bit_length);
3910 hx->inter_gb_ptr = NULL;
3912 if ((err = decode_slice_header(hx, h)) < 0)
3915 hx->s.data_partitioning = 1;
3918 init_get_bits(&hx->intra_gb, ptr, bit_length);
3919 hx->intra_gb_ptr = &hx->intra_gb;
3922 init_get_bits(&hx->inter_gb, ptr, bit_length);
3923 hx->inter_gb_ptr = &hx->inter_gb;
3925 if (hx->redundant_pic_count == 0 &&
3927 hx->s.data_partitioning &&
3928 s->current_picture_ptr &&
3929 s->context_initialized &&
3930 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
3931 (avctx->skip_frame < AVDISCARD_BIDIR ||
3932 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
3933 (avctx->skip_frame < AVDISCARD_NONKEY ||
3934 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
3935 avctx->skip_frame < AVDISCARD_ALL)
3939 init_get_bits(&s->gb, ptr, bit_length);
3940 ff_h264_decode_sei(h);
3943 init_get_bits(&s->gb, ptr, bit_length);
3944 if (ff_h264_decode_seq_parameter_set(h) < 0 &&
3945 h->is_avc && (nalsize != consumed) && nalsize) {
3946 av_log(h->s.avctx, AV_LOG_DEBUG,
3947 "SPS decoding failure, trying again with the complete NAL\n");
3948 init_get_bits(&s->gb, buf + buf_index + 1 - consumed,
3950 ff_h264_decode_seq_parameter_set(h);
3953 if (h264_set_parameter_from_sps(h) < 0) {
3959 init_get_bits(&s->gb, ptr, bit_length);
3960 ff_h264_decode_picture_parameter_set(h, bit_length);
3963 case NAL_END_SEQUENCE:
3964 case NAL_END_STREAM:
3965 case NAL_FILLER_DATA:
3967 case NAL_AUXILIARY_SLICE:
3972 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
3973 hx->nal_unit_type, bit_length);
3976 if (context_count == h->max_contexts) {
3977 execute_decode_slices(h, context_count);
3982 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3983 else if (err == 1) {
3984 /* Slice could not be decoded in parallel mode, copy down
3985 * NAL unit stuff to context 0 and restart. Note that
3986 * rbsp_buffer is not transferred, but since we no longer
3987 * run in parallel mode this should not be an issue. */
3988 h->nal_unit_type = hx->nal_unit_type;
3989 h->nal_ref_idc = hx->nal_ref_idc;
3996 execute_decode_slices(h, context_count);
4000 if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
4002 ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
4003 s->picture_structure == PICT_BOTTOM_FIELD);
4010 * Return the number of bytes consumed for building the current frame.
4012 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
4015 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4016 if (pos + 10 > buf_size)
4017 pos = buf_size; // oops ;)
4022 static int decode_frame(AVCodecContext *avctx, void *data,
4023 int *got_frame, AVPacket *avpkt)
4025 const uint8_t *buf = avpkt->data;
4026 int buf_size = avpkt->size;
4027 H264Context *h = avctx->priv_data;
4028 MpegEncContext *s = &h->s;
4029 AVFrame *pict = data;
4032 s->flags = avctx->flags;
4033 s->flags2 = avctx->flags2;
4035 /* end of stream, output what is still in the buffers */
4037 if (buf_size == 0) {
4041 s->current_picture_ptr = NULL;
4043 // FIXME factorize this with the output code below
4044 out = h->delayed_pic[0];
4047 h->delayed_pic[i] &&
4048 !h->delayed_pic[i]->f.key_frame &&
4049 !h->delayed_pic[i]->mmco_reset;
4051 if (h->delayed_pic[i]->poc < out->poc) {
4052 out = h->delayed_pic[i];
4056 for (i = out_idx; h->delayed_pic[i]; i++)
4057 h->delayed_pic[i] = h->delayed_pic[i + 1];
4067 buf_index = decode_nal_units(h, buf, buf_size, 0);
4071 if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4076 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
4077 if (avctx->skip_frame >= AVDISCARD_NONREF)
4079 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4083 if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
4084 (s->mb_y >= s->mb_height && s->mb_height)) {
4085 if (s->flags2 & CODEC_FLAG2_CHUNKS)
4086 decode_postinit(h, 1);
4090 if (!h->next_output_pic) {
4091 /* Wait for second field. */
4095 *pict = h->next_output_pic->f;
4099 assert(pict->data[0] || !*got_frame);
4100 ff_print_debug_info(s, pict);
4102 return get_consumed_bytes(s, buf_index, buf_size);
4105 av_cold void ff_h264_free_context(H264Context *h)
4109 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4111 for (i = 0; i < MAX_SPS_COUNT; i++)
4112 av_freep(h->sps_buffers + i);
4114 for (i = 0; i < MAX_PPS_COUNT; i++)
4115 av_freep(h->pps_buffers + i);
4118 static av_cold int h264_decode_end(AVCodecContext *avctx)
4120 H264Context *h = avctx->priv_data;
4121 MpegEncContext *s = &h->s;
4123 ff_h264_free_context(h);
4125 ff_MPV_common_end(s);
4127 // memset(h, 0, sizeof(H264Context));
4132 static const AVProfile profiles[] = {
4133 { FF_PROFILE_H264_BASELINE, "Baseline" },
4134 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4135 { FF_PROFILE_H264_MAIN, "Main" },
4136 { FF_PROFILE_H264_EXTENDED, "Extended" },
4137 { FF_PROFILE_H264_HIGH, "High" },
4138 { FF_PROFILE_H264_HIGH_10, "High 10" },
4139 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4140 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4141 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4142 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4143 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4144 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4145 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4146 { FF_PROFILE_UNKNOWN },
4149 AVCodec ff_h264_decoder = {
4151 .type = AVMEDIA_TYPE_VIDEO,
4152 .id = AV_CODEC_ID_H264,
4153 .priv_data_size = sizeof(H264Context),
4154 .init = ff_h264_decode_init,
4155 .close = h264_decode_end,
4156 .decode = decode_frame,
4157 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4158 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4159 CODEC_CAP_FRAME_THREADS,
4161 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4162 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4163 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4164 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4167 #if CONFIG_H264_VDPAU_DECODER
4168 AVCodec ff_h264_vdpau_decoder = {
4169 .name = "h264_vdpau",
4170 .type = AVMEDIA_TYPE_VIDEO,
4171 .id = AV_CODEC_ID_H264,
4172 .priv_data_size = sizeof(H264Context),
4173 .init = ff_h264_decode_init,
4174 .close = h264_decode_end,
4175 .decode = decode_frame,
4176 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4178 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4179 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
4181 .profiles = NULL_IF_CONFIG_SMALL(profiles),