PR #25943 opened by kierank URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25943 Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25943.patch
This moves the CABAC decoding of H.264 slice data from CABACContext to a new decoder state, CABAC64Context, which keeps a 64-bit window on the bitstream, and decodes the two exp-Golomb bypass escapes (UEG0 for coeff_abs_level_minus1, UEG3 for mvd) in batches instead of bin by bin. Why: CABACContext holds 16 bits of lookahead and refills after every 16 bits. The window takes in 48 bits at a time, so context-coded and bypass bins refill a third as often, and a run of up to 22 bypass bins is the digits of one division of the offset (and the bits under it) by range. On x86-64 the context-coded decision keeps the cmov/sbb form of x86/cabac.h, as inline asm that leaves low and range in registers. Bit-exactness: the output is the same on every bitstream, including truncated and corrupt ones that run past the end of the slice data. - The arithmetic is CABACContext's with low scaled by 2^37, so every bin, range and offset is the same; the CABACContext state (low, bytestream) can be recovered exactly at any point (cabac64_state16()), which gives the terminate bin's result, the I_PCM pointer and the slice loop's overread checks. - The reads differ only where CABACContext stops at bytestream_end and re-reads the last word: in checked reader files (the terminate bin in h264_slice.c), in the x86 get_cabac_bypass() and in the aarch64 get_cabac_inline(), which stop there in any file. h264_cabac.c is an unchecked reader, so all its other bins keep reading past the end, as the window does. A bin of the first kind is decoded on the window while the window's bytestream is at most bytestream_end - 5, where CABACContext cannot reach the end within the bin (or within a batched step of up to 24 bins, which refills it at most twice); past that it is decoded on the recovered CABACContext state with that engine's checked refill, and the window is rebuilt from the result. - The batched escapes keep the 24th prefix bin of UEG0, the cap of j at 23, the mvd overflow after 22 ones and the number of bins consumed. - Patch 4 adds a checkasm test that runs CABACContext and the window side by side on random slices, many of them shorter than 24 bytes so that every step runs past the end, and requires the same result, context state, range, low and bytestream after every bin, escape, terminate bin and I_PCM restart. Mutating the end handling (an unchecked bypass, a margin too small for a two-refill step, an unchecked refill in either fallback, the UEG0 cap, the mvd prefix length, the I_PCM pointer) makes it fail. - framemd5 of every file in fate-suite h264/ and h264-conformance/ (FRext included, 317 inputs) is identical before and after at -threads 1, and at -threads 4 with frame and with slice threading, both with asm and with --disable-asm. The one exception is FM1_FT_E (FMO/ASO) at 4 threads, whose output differs from run to run without the series too. make fate-h264 passes (236 tests) in all those modes. - The 134 CABAC streams among those files were also cut at 25/50/75/90% and damaged with random bytes at 8 offsets each, 1608 files in total, decoded at 1 and 4 threads: no crash or hang, before or after. Where the output differs, the unpatched decoder also produces both outputs in repeated runs (its output on damaged input varies from run to run, even at 1 thread). ASan, LSan and UBSan report nothing on the conformance and damaged sets. The window's 8-byte loads reach at most 14 bytes past what CABACContext reads, inside the MAX_MBPAIR_SIZE padding of the NAL buffer. The x86 and LoongArch inline asm significance map decoders work on CABACContext and are removed by patch 2; the C loops are used on every arch. The speed figures below include that loss. Speed, decode cycles:u (perf stat), ffmpeg -threads 4 -thread_type frame -f null, 250-frame 1080-line clips, Intel Xeon E-2478 (Raptor Cove, AVX2) at a fixed 2.8 GHz, gcc 11.4, base b9a9bf7a3a vs this series, median of 12 interleaved rounds (faster in 12 of 12 on every clip; A/A noise 0.03-0.10%): 8-bit 4:2:0 MBAFF 1080i, 8 Mbps -1.13% -1.61% (two clips) 8-bit 4:2:0 PAFF 1080i, 10 Mbps -1.95% 8-bit 4:2:0 progressive 1080p50 -2.11% 8-bit 4:2:2 MBAFF 1080i, 50 Mbps -5.32% 10-bit 4:2:2 MBAFF 1080i, 100 Mbps -6.43% Instructions go up by 2.4-5.5%. At -threads 1 (5 rounds): -1.02% (8-bit 4:2:0 MBAFF), -5.44% (8-bit 4:2:2), -6.53% (10-bit 4:2:2). In the base decoder, decode_significance_x86 alone is 3.3-6.4% of the cycles on the 8-bit 4:2:0 clips and 11-16% on the 4:2:2 clips, so the gain is net of replacing it with the C loops. Not tested here: aarch64 (whose context-coded bins take the near-end check), LoongArch and 32-bit builds. The correctness tests above ran on x86-64 (Cascade Lake), including the C path with --disable-asm. >From 034b155e2bc48815eecbaacc176db9ff0a7e58fc Mon Sep 17 00:00:00 2001 From: Kieran Kunhya <[email protected]> Date: Wed, 11 Nov 2026 09:51:42 +0000 Subject: [PATCH 1/4] avcodec/cabac64: add a CABAC decoder on a 64-bit window CABACContext keeps 16 bits of lookahead in low and refills after every 16 bits. CABAC64Context holds the offset at the top of a 64-bit low with the bitstream under it, and takes three 16-bit words in at once, so a context-coded or bypass bin refills a third as often; up to 22 bypass bins are decoded in one step, as the digits of one division of the offset and the bits under it by range. The arithmetic is that of CABACContext with low scaled by 2^37, so the bins are the same. The CABACContext state can be recovered at any point, which gives the position for skip_bytes()-style restarts and the terminate bin's result, and lets a bin be decoded exactly as CABACContext decodes it near the end of the data, with its checked refill. On x86-64 the decision of a context-coded bin uses inline asm with cmov/sbb, as x86/cabac.h does; elsewhere it is C. --- libavcodec/cabac64.h | 58 +++++ libavcodec/cabac64_functions.h | 379 +++++++++++++++++++++++++++++++++ libavcodec/x86/cabac64.h | 78 +++++++ 3 files changed, 515 insertions(+) create mode 100644 libavcodec/cabac64.h create mode 100644 libavcodec/cabac64_functions.h create mode 100644 libavcodec/x86/cabac64.h diff --git a/libavcodec/cabac64.h b/libavcodec/cabac64.h new file mode 100644 index 00000000000..943802c4af5 --- /dev/null +++ b/libavcodec/cabac64.h @@ -0,0 +1,58 @@ +/* + * CABAC decoder on a 64-bit window + * + * Copyright (c) 2026 Open Broadcast Systems Ltd + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AVCODEC_CABAC64_H +#define AVCODEC_CABAC64_H + +#include <stdint.h> + +/* the 9-bit offset sits at bits 54..62 of low */ +#define CABAC64_SHIFT 54 +/* bits below the refill point: a refill is due when none of them is set */ +#define CABAC64_MASK ((UINT64_C(1) << 48) - 1) + +/** + * CABAC decoder state with a 64-bit window on the bitstream. + * + * low holds the 9-bit offset at bits 54..62 (against range << 54), the + * bitstream after it below, and a sentinel, its lowest set bit, under the + * last bit read. Three 16-bit words come in at once when the sentinel + * reaches bit 48, so at rest it is at 0..47, and up to 6 bypass bins need + * no refill. + * + * The arithmetic is that of CABACContext with low scaled by 2^37, so every + * bin is the same, and the CABACContext state can be recovered at any point + * (cabac64_state16()). The window only changes how often bits come in. + * + * Reads are unchecked 8-byte loads, which reach at most 14 bytes past the + * bytes CABACContext would read at the same point; the buffer must be + * padded accordingly. + */ +typedef struct CABAC64Context { + uint64_t low; + unsigned range; + const uint8_t *bytestream; ///< the next byte not in low + const uint8_t *bytestream_start; + const uint8_t *bytestream_end; +} CABAC64Context; + +#endif /* AVCODEC_CABAC64_H */ diff --git a/libavcodec/cabac64_functions.h b/libavcodec/cabac64_functions.h new file mode 100644 index 00000000000..a816da55f01 --- /dev/null +++ b/libavcodec/cabac64_functions.h @@ -0,0 +1,379 @@ +/* + * CABAC decoder on a 64-bit window: inline functions + * + * Copyright (c) 2026 Open Broadcast Systems Ltd + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AVCODEC_CABAC64_FUNCTIONS_H +#define AVCODEC_CABAC64_FUNCTIONS_H + +#include <stdint.h> + +#include "config.h" +#include "libavutil/attributes.h" +#include "libavutil/error.h" +#include "libavutil/intmath.h" +#include "libavutil/common.h" +#include "libavutil/intreadwrite.h" +#include "libavutil/macros.h" + +#include "cabac.h" +#include "cabac64.h" + +#if ARCH_X86 +# include "x86/cabac64.h" +#endif + +/* Three words in, under the window: the sentinel goes from 48..53 to 0..5. */ +static av_always_inline uint64_t cabac64_refill(CABAC64Context *c, uint64_t low) +{ + uint64_t w = AV_RB64(c->bytestream); + int p = ff_ctzll(low); + + low &= low - 1; + low += (w >> 15 | 1) << (p - 48); + c->bytestream += 6; + return low; +} + +/* As many words as fit, the sentinel from 0..53 to 0..15: 38 bits or more of + * lookahead, without a branch. */ +static av_always_inline void cabac64_topup(CABAC64Context *c) +{ + uint64_t w = AV_RB64(c->bytestream); + uint64_t low = c->low; + int p = ff_ctzll(low); + int bits = p & 0x30; + + low &= low - 1; + low += (w >> (63 - bits) | 1) << (p & 15); + c->bytestream += bits >> 3; + c->low = low; +} + +#ifndef cabac64_decision +/* The decision of a context-coded bin before renormalization: for an LPS, + * the MPS subrange is taken off low; returns the state XORed with -1 for an + * LPS, so that bit 0 is the bin. The select is a sign mask. */ +static av_always_inline int cabac64_decision(uint64_t *plow, unsigned *prange, + int s) +{ + uint64_t low = *plow; + unsigned range = *prange; + unsigned lps = ff_h264_cabac_tables[H264_LPS_RANGE_OFFSET + 2 * (range & 0xC0) + s]; + uint64_t mps = (uint64_t)(range - lps) << CABAC64_SHIFT; + int64_t mask = (int64_t)(mps - low) >> 63; /* -1: LPS */ + + *plow = low - (mps & mask); + *prange = (range - lps) + ((2 * lps - range) & (unsigned)mask); + return s ^ (int)mask; +} +#endif + +/* A context-coded bin: get_cabac(), with a refill a third as often. */ +static av_always_inline int cabac64_get(CABAC64Context *c, uint8_t *const state) +{ + uint64_t low = c->low; + unsigned range = c->range; + int s = cabac64_decision(&low, &range, *state); + int shift; + + *state = ff_h264_cabac_tables[H264_MLPS_STATE_OFFSET + 128 + s]; + shift = ff_clz(range) - 23; + c->range = range << shift; + low <<= shift; + if (!(low & CABAC64_MASK)) + low = cabac64_refill(c, low); + c->low = low; + return s & 1; +} + +/* A bypass bin: the doubled offset compared with range, then the refill + * check. The compare needs only bits 54 and up, and the sentinel is at most + * at 48. */ +static av_always_inline int cabac64_bypass(CABAC64Context *c) +{ + uint64_t low = c->low << 1; + uint64_t r = (uint64_t)c->range << CABAC64_SHIFT; + int bit = low >= r; + + low -= r & -(uint64_t)bit; + if (!(low & CABAC64_MASK)) + low = cabac64_refill(c, low); + c->low = low; + return bit; +} + +/* val for a 1 bin, -val for a 0, as get_cabac_bypass_sign() */ +static av_always_inline int cabac64_bypass_sign(CABAC64Context *c, int val) +{ + int m = cabac64_bypass(c) - 1; + return (val ^ m) - m; +} + +/* n bypass bins MSB first, 1 <= n <= 22, in one step: the digits of the + * restoring division of the offset and the n bits under it by range, whose + * remainder is the new offset. */ +static av_always_inline unsigned cabac64_bits(CABAC64Context *c, int n) +{ + uint64_t low; + uint32_t x, q, r; + + cabac64_topup(c); + low = c->low; + x = low >> (CABAC64_SHIFT - n); + q = x / c->range; + r = x % c->range; + c->low = (low << n) - ((uint64_t)x << CABAC64_SHIFT) + + ((uint64_t)r << CABAC64_SHIFT); + /* a conforming state gives q < 2^n; a corrupt one cannot widen it */ + return q & ((1U << n) - 1); +} + +/* The same for 1 <= n <= 44 */ +static av_always_inline unsigned cabac64_bits_long(CABAC64Context *c, int n) +{ + unsigned v; + + if (n <= 22) + return cabac64_bits(c, n); + v = cabac64_bits(c, n - 22); + return v << 22 | cabac64_bits(c, 22); +} + +/* Truncated unary bypass code of at most max <= 32 bins: the number of + * leading 1 bins, consuming the 0 after them unless max is reached. Steps of + * up to 22 bins; the first 0 is the highest zero digit of the quotient. */ +static av_always_inline int cabac64_unary(CABAC64Context *c, int max) +{ + int prefix = 0; + + while (prefix < max) { + int n = FFMIN(max - prefix, 22); + uint64_t low; + uint32_t x, q, r, t; + + cabac64_topup(c); + low = c->low; + x = low >> (CABAC64_SHIFT - n); + q = x / c->range; + r = x % c->range; + t = ~q & ((1U << n) - 1); + if (t) { + /* the window after the n - h bins up to the 0: low << (n - h) + * less q_j * range at the offset, with q_j = q >> h; it wraps to + * the exact value since the true remainder is below range */ + int h = av_log2(t); + c->low = (low << (n - h)) - + (((uint64_t)(q >> h) * c->range) << CABAC64_SHIFT); + return prefix + n - 1 - h; + } + c->low = (low << n) - ((uint64_t)x << CABAC64_SHIFT) + + ((uint64_t)r << CABAC64_SHIFT); + prefix += n; + } + return prefix; +} + +/* The CABACContext state at this point. Of the window's lookahead + * L = 53 - sentinel it holds ((L - 1) & 15) + 1 bits, so the w = (L - 1) >> 4 + * words after those are not read there yet; its sentinel is 16w above this + * one, less 37. Returns its bytestream, and its low in *low16. */ +static av_always_inline const uint8_t *cabac64_state16(const CABAC64Context *c, + int *low16) +{ + uint64_t low = c->low; + int tz = ff_ctzll(low); + int w = (52 - tz) >> 4; + int t = tz + 16 * w; + + *low16 = ((uint32_t)(low >> t) | 1) << (t - 37); + return c->bytestream - 2 * w; +} + +/* The window from a CABACContext state: low16 scaled by 2^37 puts its + * sentinel at 37..52, at rest or one refill from it. */ +static av_always_inline void cabac64_from16(CABAC64Context *c, int low16, + const uint8_t *bytestream) +{ + uint64_t low = (uint64_t)(uint32_t)low16 << 37; + + c->bytestream = bytestream; + if (!(low & CABAC64_MASK)) + low = cabac64_refill(c, low); + c->low = low; +} + +/* ff_init_cabac_decoder(), the reads and the result included. The state is + * set even when the first 9 bits are out of range, as there. */ +static av_unused int cabac64_init(CABAC64Context *c, const uint8_t *buf, + int buf_size) +{ + const uint8_t *bs = buf; + uint32_t low; + + low = *bs++ << 18; + low += *bs++ << 10; + if (((uintptr_t)bs & 1) == 0) + low += 1 << 9; + else + low += (*bs++ << 2) + 2; + + c->bytestream_start = buf; + c->bytestream_end = buf + buf_size; + c->bytestream = bs; + c->range = 0x1FE; + c->low = (uint64_t)low << 37; + return (0x1FE << (CABAC_BITS + 1)) < low ? AVERROR_INVALIDDATA : 0; +} + +/* get_cabac_terminate(): 0, or the number of bytes read at the end */ +static av_always_inline int cabac64_terminate(CABAC64Context *c) +{ + unsigned range = c->range - 2; + uint64_t low = c->low; + + c->range = range; + if (low < (uint64_t)range << CABAC64_SHIFT) { + int shift = range < 0x100; + c->range = range << shift; + low <<= shift; + if (!(low & CABAC64_MASK)) + low = cabac64_refill(c, low); + c->low = low; + return 0; + } else { + int low16; + return cabac64_state16(c, &low16) - c->bytestream_start; + } +} + +/* The first byte after the bins, as skip_bytes() finds it: the CABACContext + * bytestream less the bytes of it not consumed yet. */ +static av_always_inline const uint8_t *cabac64_ptr(const CABAC64Context *c) +{ + int low16; + const uint8_t *ptr = cabac64_state16(c, &low16); + + if (low16 & 0x1) + ptr--; + if (low16 & 0x1FF) + ptr--; + return ptr; +} + +/* + * CABACContext reads stop at bytestream_end where the reader is checked + * (!UNCHECKED_BITSTREAM_READER), and in some arch versions of its bins + * regardless of that; there they read the last word again. A bin of such a + * reader can only differ from the window once CABACContext refills at or + * past bytestream_end. While the window's bytestream is at most + * bytestream_end - 5, that one's is too, and a step of up to 24 bins refills + * it at most twice, so it cannot get there. Past that point, the functions + * below decode the bin on the CABACContext state, with its checked refill, + * and rebuild the window from the result. + */ +static av_always_inline int cabac64_near_end(const CABAC64Context *c) +{ + return (uintptr_t)c->bytestream > (uintptr_t)c->bytestream_end - 5; +} + +static av_always_inline const uint8_t *cabac64_refill16(const CABAC64Context *c, + int *low, + const uint8_t *bs) +{ + *low += (bs[0] << 9) + (bs[1] << 1) - CABAC_MASK; + if (bs < c->bytestream_end) + bs += 2; + return bs; +} + +/* get_cabac_inline() with a checked refill */ +static av_noinline av_unused int cabac64_get_end(CABAC64Context *c, + uint8_t *const state) +{ + int low; + const uint8_t *bs = cabac64_state16(c, &low); + int s = *state; + int range = c->range; + int lps = ff_h264_cabac_tables[H264_LPS_RANGE_OFFSET + 2 * (range & 0xC0) + s]; + int mask, shift; + + range -= lps; + mask = ((range << (CABAC_BITS + 1)) - low) >> 31; + low -= (range << (CABAC_BITS + 1)) & mask; + range += (lps - range) & mask; + s ^= mask; + *state = ff_h264_cabac_tables[H264_MLPS_STATE_OFFSET + 128 + s]; + shift = ff_h264_cabac_tables[H264_NORM_SHIFT_OFFSET + range]; + range <<= shift; + low <<= shift; + if (!(low & CABAC_MASK)) { + int i = 7 - ff_h264_cabac_tables[H264_NORM_SHIFT_OFFSET + + ((low ^ (low - 1)) >> (CABAC_BITS - 1))]; + int x = (bs[0] << 9) + (bs[1] << 1) - CABAC_MASK; + + low += x * (1 << i); + if (bs < c->bytestream_end) + bs += 2; + } + c->range = range; + cabac64_from16(c, low, bs); + return s & 1; +} + +/* get_cabac_bypass() with a checked refill */ +static av_noinline av_unused int cabac64_bypass_end(CABAC64Context *c) +{ + int low; + const uint8_t *bs = cabac64_state16(c, &low); + int range = c->range << (CABAC_BITS + 1); + int bit; + + low += low; + if (!(low & CABAC_MASK)) + bs = cabac64_refill16(c, &low, bs); + bit = low >= range; + if (bit) + low -= range; + cabac64_from16(c, low, bs); + return bit; +} + +/* get_cabac_terminate() with a checked refill */ +static av_noinline av_unused int cabac64_terminate_end(CABAC64Context *c) +{ + int low; + const uint8_t *bs = cabac64_state16(c, &low); + int range = c->range - 2; + + c->range = range; + if (low < range << (CABAC_BITS + 1)) { + int shift = (uint32_t)(range - 0x100) >> 31; + c->range = range << shift; + low <<= shift; + if (!(low & CABAC_MASK)) + bs = cabac64_refill16(c, &low, bs); + cabac64_from16(c, low, bs); + return 0; + } + return bs - c->bytestream_start; +} + +#endif /* AVCODEC_CABAC64_FUNCTIONS_H */ diff --git a/libavcodec/x86/cabac64.h b/libavcodec/x86/cabac64.h new file mode 100644 index 00000000000..9730488344e --- /dev/null +++ b/libavcodec/x86/cabac64.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2026 Open Broadcast Systems Ltd + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AVCODEC_X86_CABAC64_H +#define AVCODEC_X86_CABAC64_H + +#include <stdint.h> + +#include "config.h" +#include "libavutil/attributes.h" +#include "libavutil/macros.h" +#include "libavcodec/cabac.h" +#include "libavcodec/cabac64.h" + +#if HAVE_INLINE_ASM && ARCH_X86_64 + +/* The select with cmov / sbb, as in x86/cabac.h, which is 5 instructions + * shorter than the sign mask the compiler makes of the C version. There is + * no memory clobber, so low and range can stay in registers from one bin to + * the next. Two steps are kept off the range-to-range dependency chain: the + * RangeLPS load adds the range bits to tab + state, so that no lea waits for + * the range, and the MPS test is range - RangeLPS >= (low >> 54) + 1, whose + * right side does not wait for the range. That is the same as + * (range - RangeLPS) << 54 > low, since the sentinel is under bit 54. */ +#define cabac64_decision cabac64_decision_x86 +static av_always_inline int cabac64_decision_x86(uint64_t *plow, unsigned *prange, + int state) +{ + int64_t s = state; + uint64_t low = *plow; + unsigned range = *prange; + uint64_t t, m, base; + + __asm__ ("lea (%[tab], %q[s]), %q[base] \n\t" + "mov %k[rng], %k[t] \n\t" + "and $0xC0, %k[rng] \n\t" + "movzbl "AV_STRINGIFY(H264_LPS_RANGE_OFFSET)"(%q[base], %q[rng], 2), %k[rng] \n\t" + "mov %q[low], %q[m] \n\t" + "shr $"AV_STRINGIFY(CABAC64_SHIFT)", %q[m] \n\t" + "add $1, %k[m] \n\t" + "sub %k[rng], %k[t] \n\t" + "cmp %k[m], %k[t] \n\t" + "cmovae %k[t], %k[rng] \n\t" + "sbb %q[m], %q[m] \n\t" + "shl $"AV_STRINGIFY(CABAC64_SHIFT)", %q[t] \n\t" + "and %q[m], %q[t] \n\t" + "xor %q[m], %q[s] \n\t" + "sub %q[t], %q[low] \n\t" + : [s]"+r"(s), [rng]"+r"(range), [low]"+r"(low), [t]"=&r"(t), + [m]"=&r"(m), [base]"=&r"(base) + : [tab]"r"(ff_h264_cabac_tables) + : "cc"); + + *plow = low; + *prange = range; + return s; +} + +#endif /* HAVE_INLINE_ASM && ARCH_X86_64 */ + +#endif /* AVCODEC_X86_CABAC64_H */ -- 2.54.0 >From 8fc01dbb9f4e369a74b578aa3bc02253e2c5326b Mon Sep 17 00:00:00 2001 From: Kieran Kunhya <[email protected]> Date: Wed, 11 Nov 2026 09:53:32 +0000 Subject: [PATCH 2/4] avcodec/h264_cabac: decode slices on the 64-bit CABAC window Move the slice data of the H.264 decoder from CABACContext to CABAC64Context: init, context-coded bins, bypass and bypass sign bins, both terminate bins, the I_PCM restart and the overread checks of the slice loop. The output is the same on every bitstream, past the end of the slice data included. The window computes the same bins, and the reads differ only in where CABACContext stops at bytestream_end: in a checked reader file (h264_slice.c and its terminate bin), in the x86 get_cabac_bypass() and in the aarch64 get_cabac_inline(), which do so in any file. h264_cabac.c is an unchecked reader, so its other bins keep reading past the end, as the window does. A bin of the first kind is decoded on the window while its bytestream is at most bytestream_end - 5, where CABACContext cannot reach the end within the bin; past that it is decoded on the recovered CABACContext state, with that engine's checked refill, and the window is rebuilt from the result. The slice loop checks the CABACContext bytestream as before. The window's 8-byte loads reach at most 14 bytes past what CABACContext reads, well inside the MAX_MBPAIR_SIZE padding of the NAL buffer. decode_cabac_residual_internal() works on a local copy of the context on every arch. The x86 and LoongArch inline asm significance map decoders work on CABACContext and are removed; the C loops are used. --- libavcodec/h264_cabac.c | 192 +++++++++++---------------- libavcodec/h264_cabac64.h | 102 +++++++++++++++ libavcodec/h264_slice.c | 28 ++-- libavcodec/h264dec.h | 3 +- libavcodec/loongarch/h264_cabac.c | 140 -------------------- libavcodec/x86/h264_cabac.c | 208 ------------------------------ 6 files changed, 196 insertions(+), 477 deletions(-) create mode 100644 libavcodec/h264_cabac64.h delete mode 100644 libavcodec/loongarch/h264_cabac.c delete mode 100644 libavcodec/x86/h264_cabac.c diff --git a/libavcodec/h264_cabac.c b/libavcodec/h264_cabac.c index 7fc4817634d..cbb13b04038 100644 --- a/libavcodec/h264_cabac.c +++ b/libavcodec/h264_cabac.c @@ -34,17 +34,12 @@ #include "config.h" #include "cabac.h" #include "cabac_functions.h" +#include "h264_cabac64.h" #include "h264dec.h" #include "h264data.h" #include "h264_mvpred.h" #include "mpegutils.h" -#if ARCH_X86 -#include "x86/h264_cabac.c" -#elif ARCH_LOONGARCH64 -#include "loongarch/h264_cabac.c" -#endif - /* Cabac pre state table */ static const int8_t cabac_context_init_I[1024][2] = @@ -1298,7 +1293,7 @@ static int decode_cabac_field_decoding_flag(const H264Context *h, H264SliceConte ctx += sl->mb_field_decoding_flag & !!sl->mb_x; //for FMO:(s->current_picture.mb_type[mba_xy] >> 7) & (h->slice_table[mba_xy] == h->slice_num); ctx += (h->cur_pic.mb_type[mbb_xy] >> 7) & (h->slice_table[mbb_xy] == sl->slice_num); - return get_cabac_noinline( &sl->cabac, &(sl->cabac_state+70)[ctx] ); + return h264_cabac_get_noinline( &sl->cabac, &(sl->cabac_state+70)[ctx] ); } static int decode_cabac_intra_mb_type(H264SliceContext *sl, @@ -1313,23 +1308,23 @@ static int decode_cabac_intra_mb_type(H264SliceContext *sl, ctx++; if (sl->top_type & (MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM)) ctx++; - if( get_cabac_noinline( &sl->cabac, &state[ctx] ) == 0 ) + if( h264_cabac_get_noinline( &sl->cabac, &state[ctx] ) == 0 ) return 0; /* I4x4 */ state += 2; }else{ - if( get_cabac_noinline( &sl->cabac, state ) == 0 ) + if( h264_cabac_get_noinline( &sl->cabac, state ) == 0 ) return 0; /* I4x4 */ } - if( get_cabac_terminate( &sl->cabac ) ) + if( h264_cabac_terminate( &sl->cabac ) ) return 25; /* PCM */ mb_type = 1; /* I16x16 */ - mb_type += 12 * get_cabac_noinline( &sl->cabac, &state[1] ); /* cbp_luma != 0 */ - if( get_cabac_noinline( &sl->cabac, &state[2] ) ) /* cbp_chroma */ - mb_type += 4 + 4 * get_cabac_noinline( &sl->cabac, &state[2+intra_slice] ); - mb_type += 2 * get_cabac_noinline( &sl->cabac, &state[3+intra_slice] ); - mb_type += 1 * get_cabac_noinline( &sl->cabac, &state[3+2*intra_slice] ); + mb_type += 12 * h264_cabac_get_noinline( &sl->cabac, &state[1] ); /* cbp_luma != 0 */ + if( h264_cabac_get_noinline( &sl->cabac, &state[2] ) ) /* cbp_chroma */ + mb_type += 4 + 4 * h264_cabac_get_noinline( &sl->cabac, &state[2+intra_slice] ); + mb_type += 2 * h264_cabac_get_noinline( &sl->cabac, &state[3+intra_slice] ); + mb_type += 1 * h264_cabac_get_noinline( &sl->cabac, &state[3+2*intra_slice] ); return mb_type; } @@ -1367,19 +1362,19 @@ static int decode_cabac_mb_skip(const H264Context *h, H264SliceContext *sl, if (sl->slice_type_nos == AV_PICTURE_TYPE_B) ctx += 13; - return get_cabac_noinline( &sl->cabac, &sl->cabac_state[11+ctx] ); + return h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[11+ctx] ); } static int decode_cabac_mb_intra4x4_pred_mode(H264SliceContext *sl, int pred_mode) { int mode = 0; - if( get_cabac( &sl->cabac, &sl->cabac_state[68] ) ) + if( h264_cabac_get( &sl->cabac, &sl->cabac_state[68] ) ) return pred_mode; - mode += 1 * get_cabac( &sl->cabac, &sl->cabac_state[69] ); - mode += 2 * get_cabac( &sl->cabac, &sl->cabac_state[69] ); - mode += 4 * get_cabac( &sl->cabac, &sl->cabac_state[69] ); + mode += 1 * h264_cabac_get( &sl->cabac, &sl->cabac_state[69] ); + mode += 2 * h264_cabac_get( &sl->cabac, &sl->cabac_state[69] ); + mode += 4 * h264_cabac_get( &sl->cabac, &sl->cabac_state[69] ); return mode + ( mode >= pred_mode ); } @@ -1398,12 +1393,12 @@ static int decode_cabac_mb_chroma_pre_mode(const H264Context *h, H264SliceContex if (sl->top_type && h->chroma_pred_mode_table[mbb_xy] != 0) ctx++; - if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[64+ctx] ) == 0 ) + if( h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[64+ctx] ) == 0 ) return 0; - if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[64+3] ) == 0 ) + if( h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[64+3] ) == 0 ) return 1; - if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[64+3] ) == 0 ) + if( h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[64+3] ) == 0 ) return 2; else return 3; @@ -1417,13 +1412,13 @@ static int decode_cabac_mb_cbp_luma(H264SliceContext *sl) cbp_b = sl->top_cbp; ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04); - cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]); + cbp += h264_cabac_get_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]); ctx = !(cbp & 0x01) + 2 * !(cbp_b & 0x08); - cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 1; + cbp += h264_cabac_get_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 1; ctx = !(cbp_a & 0x08) + 2 * !(cbp & 0x01); - cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 2; + cbp += h264_cabac_get_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 2; ctx = !(cbp & 0x04) + 2 * !(cbp & 0x02); - cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 3; + cbp += h264_cabac_get_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 3; return cbp; } static int decode_cabac_mb_cbp_chroma(H264SliceContext *sl) @@ -1437,40 +1432,40 @@ static int decode_cabac_mb_cbp_chroma(H264SliceContext *sl) ctx = 0; if( cbp_a > 0 ) ctx++; if( cbp_b > 0 ) ctx += 2; - if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[77 + ctx] ) == 0 ) + if( h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[77 + ctx] ) == 0 ) return 0; ctx = 4; if( cbp_a == 2 ) ctx++; if( cbp_b == 2 ) ctx += 2; - return 1 + get_cabac_noinline( &sl->cabac, &sl->cabac_state[77 + ctx] ); + return 1 + h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[77 + ctx] ); } static int decode_cabac_p_mb_sub_type(H264SliceContext *sl) { - if( get_cabac( &sl->cabac, &sl->cabac_state[21] ) ) + if( h264_cabac_get( &sl->cabac, &sl->cabac_state[21] ) ) return 0; /* 8x8 */ - if( !get_cabac( &sl->cabac, &sl->cabac_state[22] ) ) + if( !h264_cabac_get( &sl->cabac, &sl->cabac_state[22] ) ) return 1; /* 8x4 */ - if( get_cabac( &sl->cabac, &sl->cabac_state[23] ) ) + if( h264_cabac_get( &sl->cabac, &sl->cabac_state[23] ) ) return 2; /* 4x8 */ return 3; /* 4x4 */ } static int decode_cabac_b_mb_sub_type(H264SliceContext *sl) { int type; - if( !get_cabac( &sl->cabac, &sl->cabac_state[36] ) ) + if( !h264_cabac_get( &sl->cabac, &sl->cabac_state[36] ) ) return 0; /* B_Direct_8x8 */ - if( !get_cabac( &sl->cabac, &sl->cabac_state[37] ) ) - return 1 + get_cabac( &sl->cabac, &sl->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */ + if( !h264_cabac_get( &sl->cabac, &sl->cabac_state[37] ) ) + return 1 + h264_cabac_get( &sl->cabac, &sl->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */ type = 3; - if( get_cabac( &sl->cabac, &sl->cabac_state[38] ) ) { - if( get_cabac( &sl->cabac, &sl->cabac_state[39] ) ) - return 11 + get_cabac( &sl->cabac, &sl->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */ + if( h264_cabac_get( &sl->cabac, &sl->cabac_state[38] ) ) { + if( h264_cabac_get( &sl->cabac, &sl->cabac_state[39] ) ) + return 11 + h264_cabac_get( &sl->cabac, &sl->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */ type += 4; } - type += 2*get_cabac( &sl->cabac, &sl->cabac_state[39] ); - type += get_cabac( &sl->cabac, &sl->cabac_state[39] ); + type += 2*h264_cabac_get( &sl->cabac, &sl->cabac_state[39] ); + type += h264_cabac_get( &sl->cabac, &sl->cabac_state[39] ); return type; } @@ -1493,7 +1488,7 @@ static int decode_cabac_mb_ref(H264SliceContext *sl, int list, int n) ctx += 2; } - while( get_cabac( &sl->cabac, &sl->cabac_state[54+ctx] ) ) { + while( h264_cabac_get( &sl->cabac, &sl->cabac_state[54+ctx] ) ) { ref++; ctx = (ctx>>2)+4; if(ref >= 32 /*h->ref_list[list]*/){ @@ -1507,15 +1502,15 @@ static int decode_cabac_mb_mvd(H264SliceContext *sl, int ctxbase, int amvd, int { int mvd; - if(!get_cabac(&sl->cabac, &sl->cabac_state[ctxbase+((amvd-3)>>(INT_BIT-1))+((amvd-33)>>(INT_BIT-1))+2])){ -// if(!get_cabac(&sl->cabac, &sl->cabac_state[ctxbase+(amvd>2)+(amvd>32)])){ + if(!h264_cabac_get(&sl->cabac, &sl->cabac_state[ctxbase+((amvd-3)>>(INT_BIT-1))+((amvd-33)>>(INT_BIT-1))+2])){ +// if(!h264_cabac_get(&sl->cabac, &sl->cabac_state[ctxbase+(amvd>2)+(amvd>32)])){ *mvda= 0; return 0; } mvd= 1; ctxbase+= 3; - while( mvd < 9 && get_cabac( &sl->cabac, &sl->cabac_state[ctxbase] ) ) { + while( mvd < 9 && h264_cabac_get( &sl->cabac, &sl->cabac_state[ctxbase] ) ) { if( mvd < 4 ) ctxbase++; mvd++; @@ -1523,7 +1518,7 @@ static int decode_cabac_mb_mvd(H264SliceContext *sl, int ctxbase, int amvd, int if( mvd >= 9 ) { int k = 3; - while( get_cabac_bypass( &sl->cabac ) ) { + while( h264_cabac_bypass( &sl->cabac ) ) { mvd += 1 << k; k++; if(k>24){ @@ -1532,12 +1527,12 @@ static int decode_cabac_mb_mvd(H264SliceContext *sl, int ctxbase, int amvd, int } } while( k-- ) { - mvd += get_cabac_bypass( &sl->cabac )<<k; + mvd += h264_cabac_bypass( &sl->cabac )<<k; } *mvda=mvd < 70 ? mvd : 70; }else *mvda=mvd; - return get_cabac_bypass_sign( &sl->cabac, -mvd ); + return h264_cabac_bypass_sign( &sl->cabac, -mvd ); } #define DECODE_CABAC_MB_MVD(sl, list, n )\ @@ -1642,21 +1637,9 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, uint8_t *last_coeff_ctx_base; uint8_t *abs_level_m1_ctx_base; -#if !ARCH_X86 -#define CABAC_ON_STACK -#endif -#ifdef CABAC_ON_STACK + /* a local copy, whose address does not escape, stays in registers */ #define CC &cc - CABACContext cc; - cc.range = sl->cabac.range; - cc.low = sl->cabac.low; - cc.bytestream= sl->cabac.bytestream; -#if !UNCHECKED_BITSTREAM_READER || ARCH_AARCH64 - cc.bytestream_end = sl->cabac.bytestream_end; -#endif -#else -#define CC &sl->cabac -#endif + CABAC64Context cc = sl->cabac; significant_coeff_ctx_base = sl->cabac_state + significant_coeff_flag_offset[MB_FIELD(sl)][cat]; @@ -1669,10 +1652,10 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, #define DECODE_SIGNIFICANCE( coefs, sig_off, last_off ) \ for(last= 0; last < coefs; last++) { \ uint8_t *sig_ctx = significant_coeff_ctx_base + sig_off; \ - if( get_cabac( CC, sig_ctx )) { \ + if( h264_cabac_get( CC, sig_ctx )) { \ uint8_t *last_ctx = last_coeff_ctx_base + last_off; \ index[coeff_count++] = last; \ - if( get_cabac( CC, last_ctx ) ) { \ + if( h264_cabac_get( CC, last_ctx ) ) { \ last= max_coeff; \ break; \ } \ @@ -1682,17 +1665,6 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, index[coeff_count++] = last;\ } const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD(sl)]; -#ifdef decode_significance - coeff_count = decode_significance_8x8(CC, significant_coeff_ctx_base, index, - last_coeff_ctx_base, sig_off); - } else { - if (is_dc && chroma422) { // dc 422 - DECODE_SIGNIFICANCE(7, sig_coeff_offset_dc[last], sig_coeff_offset_dc[last]); - } else { - coeff_count = decode_significance(CC, max_coeff, significant_coeff_ctx_base, index, - last_coeff_ctx_base-significant_coeff_ctx_base); - } -#else DECODE_SIGNIFICANCE( 63, sig_off[last], ff_h264_last_coeff_flag_offset_8x8[last] ); } else { if (is_dc && chroma422) { // dc 422 @@ -1700,7 +1672,6 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, } else { DECODE_SIGNIFICANCE(max_coeff - 1, last, last); } -#endif } av_assert2(coeff_count > 0); @@ -1725,39 +1696,39 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, \ int j= scantable[index[--coeff_count]]; \ \ - if( get_cabac( CC, ctx ) == 0 ) { \ + if( h264_cabac_get( CC, ctx ) == 0 ) { \ node_ctx = coeff_abs_level_transition[0][node_ctx]; \ if( is_dc ) { \ - ((type*)block)[j] = get_cabac_bypass_sign( CC, -1); \ + ((type*)block)[j] = h264_cabac_bypass_sign( CC, -1); \ }else{ \ - ((type*)block)[j] = (get_cabac_bypass_sign( CC, -qmul[j]) + 32) >> 6; \ + ((type*)block)[j] = (h264_cabac_bypass_sign( CC, -qmul[j]) + 32) >> 6; \ } \ } else { \ unsigned coeff_abs = 2; \ ctx = coeff_abs_levelgt1_ctx[is_dc && chroma422][node_ctx] + abs_level_m1_ctx_base; \ node_ctx = coeff_abs_level_transition[1][node_ctx]; \ \ - while( coeff_abs < 15 && get_cabac( CC, ctx ) ) { \ + while( coeff_abs < 15 && h264_cabac_get( CC, ctx ) ) { \ coeff_abs++; \ } \ \ if( coeff_abs >= 15 ) { \ int j = 0; \ - while (get_cabac_bypass(CC) && j < 16+7) { \ + while (h264_cabac_bypass(CC) && j < 16+7) { \ j++; \ } \ \ coeff_abs=1; \ while( j-- ) { \ - coeff_abs += coeff_abs + get_cabac_bypass( CC ); \ + coeff_abs += coeff_abs + h264_cabac_bypass( CC ); \ } \ coeff_abs+= 14U; \ } \ \ if( is_dc ) { \ - ((type*)block)[j] = get_cabac_bypass_sign( CC, -coeff_abs ); \ + ((type*)block)[j] = h264_cabac_bypass_sign( CC, -coeff_abs ); \ }else{ \ - ((type*)block)[j] = ((int)(get_cabac_bypass_sign( CC, -coeff_abs ) * qmul[j] + 32)) >> 6; \ + ((type*)block)[j] = ((int)(h264_cabac_bypass_sign( CC, -coeff_abs ) * qmul[j] + 32)) >> 6; \ } \ } \ } while ( coeff_count ); @@ -1767,12 +1738,7 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, } else { STORE_BLOCK(int16_t) } -#ifdef CABAC_ON_STACK - sl->cabac.range = cc.range ; - sl->cabac.low = cc.low ; - sl->cabac.bytestream= cc.bytestream; -#endif - + sl->cabac = cc; } static av_noinline void decode_cabac_residual_dc_internal(const H264Context *h, @@ -1826,7 +1792,7 @@ static av_always_inline void decode_cabac_residual_dc(const H264Context *h, int max_coeff) { /* read coded block flag */ - if( get_cabac( &sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 1)]) == 0 ) { + if( h264_cabac_get( &sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 1)]) == 0 ) { sl->non_zero_count_cache[scan8[n]] = 0; return; } @@ -1840,7 +1806,7 @@ decode_cabac_residual_dc_422(const H264Context *h, H264SliceContext *sl, int max_coeff) { /* read coded block flag */ - if (get_cabac(&sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 1)]) == 0) { + if (h264_cabac_get(&sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 1)]) == 0) { sl->non_zero_count_cache[scan8[n]] = 0; return; } @@ -1856,7 +1822,7 @@ static av_always_inline void decode_cabac_residual_nondc(const H264Context *h, int max_coeff) { /* read coded block flag */ - if( (cat != 5 || CHROMA444(h)) && get_cabac( &sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 0)]) == 0) { + if( (cat != 5 || CHROMA444(h)) && h264_cabac_get( &sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 0)]) == 0) { if( max_coeff == 64 ) { fill_rectangle(&sl->non_zero_count_cache[scan8[n]], 2, 2, 8, 0, 1); } else { @@ -1974,16 +1940,16 @@ int ff_h264_decode_mb_cabac(const H264Context *h, H264SliceContext *sl) if (!IS_DIRECT(sl->top_type - 1)) ctx++; - if( !get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+ctx] ) ){ + if( !h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+ctx] ) ){ mb_type= 0; /* B_Direct_16x16 */ - }else if( !get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+3] ) ) { - mb_type= 1 + get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ); /* B_L[01]_16x16 */ + }else if( !h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+3] ) ) { + mb_type= 1 + h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+5] ); /* B_L[01]_16x16 */ }else{ int bits; - bits = get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+4] ) << 3; - bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 2; - bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 1; - bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ); + bits = h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+4] ) << 3; + bits+= h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 2; + bits+= h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 1; + bits+= h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+5] ); if( bits < 8 ){ mb_type= bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */ }else if( bits == 13 ){ @@ -1994,21 +1960,21 @@ int ff_h264_decode_mb_cabac(const H264Context *h, H264SliceContext *sl) }else if( bits == 15 ){ mb_type= 22; /* B_8x8 */ }else{ - bits= ( bits<<1 ) + get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ); + bits= ( bits<<1 ) + h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[27+5] ); mb_type= bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */ } } partition_count = ff_h264_b_mb_type_info[mb_type].partition_count; mb_type = ff_h264_b_mb_type_info[mb_type].type; } else if (sl->slice_type_nos == AV_PICTURE_TYPE_P) { - if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[14] ) == 0 ) { + if( h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[14] ) == 0 ) { /* P-type */ - if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[15] ) == 0 ) { + if( h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[15] ) == 0 ) { /* P_L0_D16x16, P_8x8 */ - mb_type= 3 * get_cabac_noinline( &sl->cabac, &sl->cabac_state[16] ); + mb_type= 3 * h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[16] ); } else { /* P_L0_D8x16, P_L0_D16x8 */ - mb_type= 2 - get_cabac_noinline( &sl->cabac, &sl->cabac_state[17] ); + mb_type= 2 - h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[17] ); } partition_count = ff_h264_p_mb_type_info[mb_type].partition_count; mb_type = ff_h264_p_mb_type_info[mb_type].type; @@ -2037,13 +2003,7 @@ decode_intra_mb: int ret; // We assume these blocks are very rare so we do not optimize it. - // FIXME The two following lines get the bitstream position in the cabac - // decode, I think it should be done by a function in cabac.h (or cabac.c). - ptr= sl->cabac.bytestream; - if(sl->cabac.low&0x1) ptr--; - if(CABAC_BITS==16){ - if(sl->cabac.low&0x1FF) ptr--; - } + ptr = cabac64_ptr(&sl->cabac); // The pixels are stored in the same order as levels in h->mb array. if ((int) (sl->cabac.bytestream_end - ptr) < mb_size) @@ -2051,7 +2011,7 @@ decode_intra_mb: sl->intra_pcm_ptr = ptr; ptr += mb_size; - ret = ff_init_cabac_decoder(&sl->cabac, ptr, sl->cabac.bytestream_end - ptr); + ret = cabac64_init(&sl->cabac, ptr, sl->cabac.bytestream_end - ptr); if (ret < 0) return ret; @@ -2072,7 +2032,7 @@ decode_intra_mb: if( IS_INTRA( mb_type ) ) { int i, pred_mode; if( IS_INTRA4x4( mb_type ) ) { - if (dct8x8_allowed && get_cabac_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size])) { + if (dct8x8_allowed && h264_cabac_get_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size])) { mb_type |= MB_TYPE_8x8DCT; for( i = 0; i < 16; i+=4 ) { int pred = pred_intra_mode(h, sl, i); @@ -2343,7 +2303,7 @@ decode_intra_mb: h->cbp_table[mb_xy] = sl->cbp = cbp; if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) { - mb_type |= MB_TYPE_8x8DCT * get_cabac_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size]); + mb_type |= MB_TYPE_8x8DCT * h264_cabac_get_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size]); } /* It would be better to do this in fill_decode_caches, but we don't know @@ -2394,12 +2354,12 @@ decode_intra_mb: const uint32_t *qmul; // decode_cabac_mb_dqp - if(get_cabac_noinline( &sl->cabac, &sl->cabac_state[60 + (sl->last_qscale_diff != 0)])){ + if(h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[60 + (sl->last_qscale_diff != 0)])){ int val = 1; int ctx= 2; const int max_qp = 51 + 6*(sps->bit_depth_luma-8); - while( get_cabac_noinline( &sl->cabac, &sl->cabac_state[60 + ctx] ) ) { + while( h264_cabac_get_noinline( &sl->cabac, &sl->cabac_state[60 + ctx] ) ) { ctx= 3; val++; if(val > 2*max_qp){ //prevent infinite loop diff --git a/libavcodec/h264_cabac64.h b/libavcodec/h264_cabac64.h new file mode 100644 index 00000000000..9152290b75c --- /dev/null +++ b/libavcodec/h264_cabac64.h @@ -0,0 +1,102 @@ +/* + * H.264 CABAC bins on the 64-bit window + * + * Copyright (c) 2026 Open Broadcast Systems Ltd + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AVCODEC_H264_CABAC64_H +#define AVCODEC_H264_CABAC64_H + +#include "config.h" +#include "libavutil/attributes.h" + +/* the CABACContext bins whose behaviour at the end is reproduced, in the + * reader mode of the including file */ +#include "cabac_functions.h" +#include "cabac64.h" +#include "cabac64_functions.h" + +/* + * Every bin is the one CABACContext gives in the including file, past the + * end of the slice data included. There the reads differ by bin type and + * arch: a bin of a checked reader stops at bytestream_end, and so do the + * x86 get_cabac_bypass() and the aarch64 get_cabac_inline() in any reader. + * The other bins keep reading, as the window does. + */ +#if !UNCHECKED_BITSTREAM_READER || (ARCH_AARCH64 && defined(get_cabac_inline)) +#define H264_CABAC_GET_CHECKED 1 +#else +#define H264_CABAC_GET_CHECKED 0 +#endif + +#if !UNCHECKED_BITSTREAM_READER || (ARCH_X86 && defined(get_cabac_bypass)) +#define H264_CABAC_BYPASS_CHECKED 1 +#else +#define H264_CABAC_BYPASS_CHECKED 0 +#endif + +#define H264_CABAC_CHECKED (!UNCHECKED_BITSTREAM_READER) + +static av_always_inline int h264_cabac_get(CABAC64Context *c, uint8_t *const state) +{ + if (H264_CABAC_GET_CHECKED && cabac64_near_end(c)) { + CABAC64Context t = *c; /* keeps c itself out of memory */ + int bit = cabac64_get_end(&t, state); + *c = t; + return bit; + } + return cabac64_get(c, state); +} + +static av_noinline av_unused int h264_cabac_get_noinline(CABAC64Context *c, + uint8_t *const state) +{ + return h264_cabac_get(c, state); +} + +static av_always_inline int h264_cabac_bypass(CABAC64Context *c) +{ + if (H264_CABAC_BYPASS_CHECKED && cabac64_near_end(c)) { + CABAC64Context t = *c; + int bit = cabac64_bypass_end(&t); + *c = t; + return bit; + } + return cabac64_bypass(c); +} + +static av_always_inline int h264_cabac_bypass_sign(CABAC64Context *c, int val) +{ + if (H264_CABAC_CHECKED && cabac64_near_end(c)) { + CABAC64Context t = *c; + int m = cabac64_bypass_end(&t) - 1; + *c = t; + return (val ^ m) - m; + } + return cabac64_bypass_sign(c, val); +} + +static av_always_inline int h264_cabac_terminate(CABAC64Context *c) +{ + if (H264_CABAC_CHECKED && cabac64_near_end(c)) + return cabac64_terminate_end(c); + return cabac64_terminate(c); +} + +#endif /* AVCODEC_H264_CABAC64_H */ diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c index 2bcb64378dc..3720af25911 100644 --- a/libavcodec/h264_slice.c +++ b/libavcodec/h264_slice.c @@ -34,6 +34,7 @@ #include "decode.h" #include "cabac.h" #include "cabac_functions.h" +#include "h264_cabac64.h" #include "error_resilience.h" #include "avcodec.h" #include "h264.h" @@ -2713,16 +2714,17 @@ static int decode_slice(struct AVCodecContext *avctx, void *arg) align_get_bits(&sl->gb); /* init cabac */ - ret = ff_init_cabac_decoder(&sl->cabac, - sl->gb.buffer + get_bits_count(&sl->gb) / 8, - (get_bits_left(&sl->gb) + 7) / 8); + ret = cabac64_init(&sl->cabac, + sl->gb.buffer + get_bits_count(&sl->gb) / 8, + (get_bits_left(&sl->gb) + 7) / 8); if (ret < 0) return ret; ff_h264_init_cabac_states(h, sl); for (;;) { - int ret, eos; + const uint8_t *bs, *end; + int ret, eos, low; if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) { av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n", sl->next_slice_idx); @@ -2746,23 +2748,25 @@ static int decode_slice(struct AVCodecContext *avctx, void *arg) ff_h264_hl_decode_mb(h, sl); sl->mb_y--; } - eos = get_cabac_terminate(&sl->cabac); + eos = h264_cabac_terminate(&sl->cabac); + /* the bytestream position of CABACContext, as these checks + * were written for */ + bs = cabac64_state16(&sl->cabac, &low); + end = sl->cabac.bytestream_end; - if ((h->workaround_bugs & FF_BUG_TRUNCATED) && - sl->cabac.bytestream > sl->cabac.bytestream_end + 2) { + if ((h->workaround_bugs & FF_BUG_TRUNCATED) && bs > end + 2) { er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1, sl->mb_y, ER_MB_END); if (sl->mb_x >= lf_x_start) loop_filter(h, sl, lf_x_start, sl->mb_x + 1); goto finish; } - if (sl->cabac.bytestream > sl->cabac.bytestream_end + 2 ) - av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", sl->cabac.bytestream_end - sl->cabac.bytestream); - if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 4) { + if (bs > end + 2) + av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", end - bs); + if (ret < 0 || bs > end + 4) { av_log(h->avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream %td\n", - sl->mb_x, sl->mb_y, - sl->cabac.bytestream_end - sl->cabac.bytestream); + sl->mb_x, sl->mb_y, end - bs); er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x, sl->mb_y, ER_MB_ERROR); return AVERROR_INVALIDDATA; diff --git a/libavcodec/h264dec.h b/libavcodec/h264dec.h index 7bce897021d..9574011cfdb 100644 --- a/libavcodec/h264dec.h +++ b/libavcodec/h264dec.h @@ -31,6 +31,7 @@ #include "libavutil/mem_internal.h" #include "cabac.h" +#include "cabac64.h" #include "error_resilience.h" #include "h264_parse.h" #include "h264_ps.h" @@ -324,7 +325,7 @@ typedef struct H264SliceContext { /** * Cabac */ - CABACContext cabac; + CABAC64Context cabac; uint8_t cabac_state[1024]; int cabac_init_idc; diff --git a/libavcodec/loongarch/h264_cabac.c b/libavcodec/loongarch/h264_cabac.c deleted file mode 100644 index d88743bed7a..00000000000 --- a/libavcodec/loongarch/h264_cabac.c +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Loongson optimized cabac - * - * Copyright (c) 2021 Loongson Technology Corporation Limited - * Contributed by Hao Chen <[email protected]> - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "libavcodec/cabac.h" -#include "cabac.h" - -#define decode_significance decode_significance_loongarch -static int decode_significance_loongarch(CABACContext *c, int max_coeff, - uint8_t *significant_coeff_ctx_base, int *index, int64_t last_off) -{ - void *end = significant_coeff_ctx_base + max_coeff - 1; - int64_t minusstart = -(int64_t)significant_coeff_ctx_base; - int64_t minusindex = 4 - (int64_t)index; - int64_t bit, tmp0, tmp1, tmp2, one = 1; - uint8_t *state = significant_coeff_ctx_base; - - __asm__ volatile( - "3:" -#if UNCHECKED_BITSTREAM_READER - GET_CABAC_LOONGARCH_UNCBSR -#else - GET_CABAC_LOONGARCH -#endif - "blt %[bit], %[one], 4f \n\t" - "add.d %[state], %[state], %[last_off] \n\t" -#if UNCHECKED_BITSTREAM_READER - GET_CABAC_LOONGARCH_UNCBSR -#else - GET_CABAC_LOONGARCH -#endif - "sub.d %[state], %[state], %[last_off] \n\t" - "add.d %[tmp0], %[state], %[minusstart] \n\t" - "st.w %[tmp0], %[index], 0 \n\t" - "bge %[bit], %[one], 5f \n\t" - "addi.d %[index], %[index], 4 \n\t" - "4: \n\t" - "addi.d %[state], %[state], 1 \n\t" - "blt %[state], %[end], 3b \n\t" - "add.d %[tmp0], %[state], %[minusstart] \n\t" - "st.w %[tmp0], %[index], 0 \n\t" - "5: \n\t" - "add.d %[tmp0], %[index], %[minusindex] \n\t" - "srli.d %[tmp0], %[tmp0], 2 \n\t" - : [bit]"=&r"(bit), [tmp0]"=&r"(tmp0), [tmp1]"=&r"(tmp1), [tmp2]"=&r"(tmp2), - [c_range]"+&r"(c->range), [c_low]"+&r"(c->low), [state]"+&r"(state), - [c_bytestream]"+&r"(c->bytestream), [index]"+&r"(index) - : [tables]"r"(ff_h264_cabac_tables), [end]"r"(end), [one]"r"(one), - [minusstart]"r"(minusstart), [minusindex]"r"(minusindex), - [last_off]"r"(last_off), -#if !UNCHECKED_BITSTREAM_READER - [c_bytestream_end]"r"(c->bytestream_end), -#endif - [lps_off]"i"(H264_LPS_RANGE_OFFSET), - [mlps_off]"i"(H264_MLPS_STATE_OFFSET + 128), - [norm_off]"i"(H264_NORM_SHIFT_OFFSET), - [cabac_mask]"r"(CABAC_MASK) - : "memory" - ); - - return (int)tmp0; -} - -#define decode_significance_8x8 decode_significance_8x8_loongarch -static int decode_significance_8x8_loongarch( - CABACContext *c, uint8_t *significant_coeff_ctx_base, - int *index, uint8_t *last_coeff_ctx_base, const uint8_t *sig_off) -{ - int64_t minusindex = 4 - (int64_t)index; - int64_t bit, tmp0, tmp1, tmp2, one = 1, end = 63, last = 0; - uint8_t *state = 0; - int64_t flag_offset = H264_LAST_COEFF_FLAG_OFFSET_8x8_OFFSET; - - __asm__ volatile( - "3: \n\t" - "ldx.bu %[tmp0], %[sig_off], %[last] \n\t" - "add.d %[state], %[tmp0], %[significant_coeff_ctx_base] \n\t" -#if UNCHECKED_BITSTREAM_READER - GET_CABAC_LOONGARCH_UNCBSR -#else - GET_CABAC_LOONGARCH -#endif - "blt %[bit], %[one], 4f \n\t" - "add.d %[tmp0], %[tables], %[flag_offset] \n\t" - "ldx.bu %[tmp1], %[tmp0], %[last] \n\t" - "add.d %[state], %[tmp1], %[last_coeff_ctx_base] \n\t" -#if UNCHECKED_BITSTREAM_READER - GET_CABAC_LOONGARCH_UNCBSR -#else - GET_CABAC_LOONGARCH -#endif - "st.w %[last], %[index], 0 \n\t" - "bge %[bit], %[one], 5f \n\t" - "addi.d %[index], %[index], 4 \n\t" - "4: \n\t" - "addi.d %[last], %[last], 1 \n\t" - "blt %[last], %[end], 3b \n\t" - "st.w %[last], %[index], 0 \n\t" - "5: \n\t" - "add.d %[tmp0], %[index], %[minusindex] \n\t" - "srli.d %[tmp0], %[tmp0], 2 \n\t" - : [bit]"=&r"(bit), [tmp0]"=&r"(tmp0), [tmp1]"=&r"(tmp1), - [tmp2]"=&r"(tmp2), [c_range]"+&r"(c->range), - [c_low]"+&r"(c->low), [state]"+&r"(state), [last]"+&r"(last), - [c_bytestream]"+&r"(c->bytestream), [index]"+&r"(index) - : [tables]"r"(ff_h264_cabac_tables), [end]"r"(end), - [one]"r"(one), [minusindex]"r"(minusindex), - [last_coeff_ctx_base]"r"(last_coeff_ctx_base), - [flag_offset]"r"(flag_offset), -#if !UNCHECKED_BITSTREAM_READER - [c_bytestream_end]"r"(c->bytestream_end), -#endif - [lps_off]"i"(H264_LPS_RANGE_OFFSET), [sig_off]"r"(sig_off), - [mlps_off]"i"(H264_MLPS_STATE_OFFSET + 128), - [norm_off]"i"(H264_NORM_SHIFT_OFFSET), - [cabac_mask]"r"(CABAC_MASK), - [significant_coeff_ctx_base]"r"(significant_coeff_ctx_base) - ); - - return (int)tmp0; -} diff --git a/libavcodec/x86/h264_cabac.c b/libavcodec/x86/h264_cabac.c deleted file mode 100644 index ac7d07780c9..00000000000 --- a/libavcodec/x86/h264_cabac.c +++ /dev/null @@ -1,208 +0,0 @@ -/* - * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder - * Copyright (c) 2003 Michael Niedermayer <[email protected]> - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * @file - * H.264 / AVC / MPEG-4 part10 codec. - * non-SIMD x86-specific optimizations for H.264 - * @author Michael Niedermayer <[email protected]> - */ - -#include <stddef.h> - -#include "libavcodec/cabac.h" -#include "cabac.h" - -#if HAVE_INLINE_ASM - -#if ARCH_X86_64 -#define REG64 "r" -#else -#define REG64 "m" -#endif - -//FIXME use some macros to avoid duplicating get_cabac (cannot be done yet -//as that would make optimization work hard) -#if HAVE_X86_7REGS && !BROKEN_COMPILER -#define decode_significance decode_significance_x86 -static int decode_significance_x86(CABACContext *c, int max_coeff, - uint8_t *significant_coeff_ctx_base, - int *index, x86_reg last_off){ - void *end= significant_coeff_ctx_base + max_coeff - 1; - int minusstart= -(intptr_t)significant_coeff_ctx_base; - int minusindex= 4-(intptr_t)index; - int bit; - x86_reg coeff_count; - -#ifdef BROKEN_RELOCATIONS - void *tables; - - __asm__ volatile( - "lea "MANGLE(ff_h264_cabac_tables)", %0 \n\t" - : "=&r"(tables) - : NAMED_CONSTRAINTS_ARRAY(ff_h264_cabac_tables) - ); -#endif - - __asm__ volatile( - "3: \n\t" - - BRANCHLESS_GET_CABAC("%4", "%q4", "(%1)", "%3", "%w3", - "%5", "%q5", "%k0", "%b0", - "%c11(%6)", "%c12(%6)", - AV_STRINGIFY(H264_NORM_SHIFT_OFFSET), - AV_STRINGIFY(H264_LPS_RANGE_OFFSET), - AV_STRINGIFY(H264_MLPS_STATE_OFFSET), - "%13") - - "test $1, %4 \n\t" - " jz 4f \n\t" - "add %10, %1 \n\t" - - BRANCHLESS_GET_CABAC("%4", "%q4", "(%1)", "%3", "%w3", - "%5", "%q5", "%k0", "%b0", - "%c11(%6)", "%c12(%6)", - AV_STRINGIFY(H264_NORM_SHIFT_OFFSET), - AV_STRINGIFY(H264_LPS_RANGE_OFFSET), - AV_STRINGIFY(H264_MLPS_STATE_OFFSET), - "%13") - - "sub %10, %1 \n\t" - "mov %2, %0 \n\t" - "movl %7, %%ecx \n\t" - "add %1, %%"FF_REG_c" \n\t" - "movl %%ecx, (%0) \n\t" - - "test $1, %4 \n\t" - " jnz 5f \n\t" - - "add"FF_OPSIZE" $4, %2 \n\t" - - "4: \n\t" - "add $1, %1 \n\t" - "cmp %8, %1 \n\t" - " jb 3b \n\t" - "mov %2, %0 \n\t" - "movl %7, %%ecx \n\t" - "add %1, %%"FF_REG_c" \n\t" - "movl %%ecx, (%0) \n\t" - "5: \n\t" - "add %9, %k0 \n\t" - "shr $2, %k0 \n\t" - : "=&q"(coeff_count), "+r"(significant_coeff_ctx_base), "+m"(index), - "+&r"(c->low), "=&r"(bit), "+&r"(c->range) - : "r"(c), "m"(minusstart), "m"(end), "m"(minusindex), "m"(last_off), - "i"(offsetof(CABACContext, bytestream)), - "i"(offsetof(CABACContext, bytestream_end)) - TABLES_ARG - : "%"FF_REG_c, "memory" - ); - return coeff_count; -} - -#define decode_significance_8x8 decode_significance_8x8_x86 -static int decode_significance_8x8_x86(CABACContext *c, - uint8_t *significant_coeff_ctx_base, - int *index, uint8_t *last_coeff_ctx_base, const uint8_t *sig_off){ - int minusindex= 4-(intptr_t)index; - int bit; - x86_reg coeff_count; - x86_reg last=0; - x86_reg state; - -#ifdef BROKEN_RELOCATIONS - void *tables; - - __asm__ volatile( - "lea "MANGLE(ff_h264_cabac_tables)", %0 \n\t" - : "=&r"(tables) - : NAMED_CONSTRAINTS_ARRAY(ff_h264_cabac_tables) - ); -#endif - - __asm__ volatile( - "mov %1, %6 \n\t" - "3: \n\t" - - "mov %10, %0 \n\t" - "movzb (%0, %6), %6 \n\t" - "add %9, %6 \n\t" - - BRANCHLESS_GET_CABAC("%4", "%q4", "(%6)", "%3", "%w3", - "%5", "%q5", "%k0", "%b0", - "%c12(%7)", "%c13(%7)", - AV_STRINGIFY(H264_NORM_SHIFT_OFFSET), - AV_STRINGIFY(H264_LPS_RANGE_OFFSET), - AV_STRINGIFY(H264_MLPS_STATE_OFFSET), - "%15") - - "mov %1, %6 \n\t" - "test $1, %4 \n\t" - " jz 4f \n\t" - -#ifdef BROKEN_RELOCATIONS - "movzb %c14(%15, %q6), %6\n\t" -#else - "movzb "MANGLE(ff_h264_cabac_tables)"+%c14(%6), %6\n\t" -#endif - "add %11, %6 \n\t" - - BRANCHLESS_GET_CABAC("%4", "%q4", "(%6)", "%3", "%w3", - "%5", "%q5", "%k0", "%b0", - "%c12(%7)", "%c13(%7)", - AV_STRINGIFY(H264_NORM_SHIFT_OFFSET), - AV_STRINGIFY(H264_LPS_RANGE_OFFSET), - AV_STRINGIFY(H264_MLPS_STATE_OFFSET), - "%15") - - "mov %2, %0 \n\t" - "mov %1, %6 \n\t" - "mov %k6, (%0) \n\t" - - "test $1, %4 \n\t" - " jnz 5f \n\t" - - "add"FF_OPSIZE" $4, %2 \n\t" - - "4: \n\t" - "add $1, %6 \n\t" - "mov %6, %1 \n\t" - "cmp $63, %6 \n\t" - " jb 3b \n\t" - "mov %2, %0 \n\t" - "mov %k6, (%0) \n\t" - "5: \n\t" - "addl %8, %k0 \n\t" - "shr $2, %k0 \n\t" - : "=&q"(coeff_count), "+"REG64(last), "+"REG64(index), "+&r"(c->low), - "=&r"(bit), "+&r"(c->range), "=&r"(state) - : "r"(c), "m"(minusindex), "m"(significant_coeff_ctx_base), - REG64(sig_off), REG64(last_coeff_ctx_base), - "i"(offsetof(CABACContext, bytestream)), - "i"(offsetof(CABACContext, bytestream_end)), - "i"(H264_LAST_COEFF_FLAG_OFFSET_8x8_OFFSET) TABLES_ARG - : "%"FF_REG_c, "memory" - ); - return coeff_count; -} -#endif /* HAVE_X86_7REGS && BROKEN_COMPILER */ - -#endif /* HAVE_INLINE_ASM */ -- 2.54.0 >From ab18d70f9b891b6dcdf8adb60b5d33d7495afedc Mon Sep 17 00:00:00 2001 From: Kieran Kunhya <[email protected]> Date: Wed, 11 Nov 2026 09:53:56 +0000 Subject: [PATCH 3/4] avcodec/h264_cabac: decode the UEG0 and UEG3 escapes in batches The coeff_abs_level_minus1 escape (UEG0: a unary prefix of up to 24 bins, then j suffix bins) and the mvd escape (UEG3: up to 22 prefix bins from k = 3, then k suffix bins) were read one bypass bin at a time. Decode them with cabac64_unary() and cabac64_bits(): one division for up to 22 bins, the end of the prefix found from the quotient. The 24th prefix bin of UEG0, the cap of j at 23 and the mvd overflow after 22 ones are kept, as is the number of bins consumed in each case. Where the bypass bin stops at bytestream_end (x86), each step near the end of the slice data falls back to single bins, so that this is reproduced: a step of up to 24 bins refills CABACContext at most twice, so before bytestream_end - 5 it cannot reach the end within the step. --- libavcodec/h264_cabac.c | 29 +++---------- libavcodec/h264_cabac64.h | 88 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 23 deletions(-) diff --git a/libavcodec/h264_cabac.c b/libavcodec/h264_cabac.c index cbb13b04038..928c9a70d89 100644 --- a/libavcodec/h264_cabac.c +++ b/libavcodec/h264_cabac.c @@ -1517,17 +1517,10 @@ static int decode_cabac_mb_mvd(H264SliceContext *sl, int ctxbase, int amvd, int } if( mvd >= 9 ) { - int k = 3; - while( h264_cabac_bypass( &sl->cabac ) ) { - mvd += 1 << k; - k++; - if(k>24){ - av_log(sl->h264->avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n"); - return INT_MIN; - } - } - while( k-- ) { - mvd += h264_cabac_bypass( &sl->cabac )<<k; + mvd = h264_cabac_mvd(&sl->cabac, mvd); + if (mvd == INT_MIN) { + av_log(sl->h264->avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n"); + return INT_MIN; } *mvda=mvd < 70 ? mvd : 70; }else @@ -1712,18 +1705,8 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, coeff_abs++; \ } \ \ - if( coeff_abs >= 15 ) { \ - int j = 0; \ - while (h264_cabac_bypass(CC) && j < 16+7) { \ - j++; \ - } \ -\ - coeff_abs=1; \ - while( j-- ) { \ - coeff_abs += coeff_abs + h264_cabac_bypass( CC ); \ - } \ - coeff_abs+= 14U; \ - } \ + if( coeff_abs >= 15 ) \ + coeff_abs = h264_cabac_ueg0(CC); \ \ if( is_dc ) { \ ((type*)block)[j] = h264_cabac_bypass_sign( CC, -coeff_abs ); \ diff --git a/libavcodec/h264_cabac64.h b/libavcodec/h264_cabac64.h index 9152290b75c..83b8a865180 100644 --- a/libavcodec/h264_cabac64.h +++ b/libavcodec/h264_cabac64.h @@ -23,6 +23,8 @@ #ifndef AVCODEC_H264_CABAC64_H #define AVCODEC_H264_CABAC64_H +#include <limits.h> + #include "config.h" #include "libavutil/attributes.h" @@ -99,4 +101,90 @@ static av_always_inline int h264_cabac_terminate(CABAC64Context *c) return cabac64_terminate(c); } +/* The coeff_abs_level_minus1 escape of decode_cabac_residual(), for + * coeff_abs >= 15: a unary prefix of at most 24 bins (j < 23 ones counted, + * the 24th bin taken whatever it is), then j suffix bins; + * coeff_abs = 2^j + suffix + 14. */ +static av_noinline av_unused unsigned h264_cabac_ueg0_end(CABAC64Context *c) +{ + unsigned coeff_abs = 1; + int j = 0; + + while (h264_cabac_bypass(c) && j < 16 + 7) + j++; + while (j--) + coeff_abs += coeff_abs + h264_cabac_bypass(c); + return coeff_abs + 14U; +} + +static av_always_inline unsigned h264_cabac_ueg0(CABAC64Context *c) +{ + unsigned suffix; + int j; + + if (H264_CABAC_BYPASS_CHECKED && cabac64_near_end(c)) { + CABAC64Context t = *c; + unsigned v = h264_cabac_ueg0_end(&t); + *c = t; + return v; + } + j = cabac64_unary(c, 24); + j = FFMIN(j, 23); + if (!j) + return 15; + if (H264_CABAC_BYPASS_CHECKED && cabac64_near_end(c)) { + CABAC64Context t = *c; + suffix = 0; + for (int i = 0; i < j; i++) + suffix = suffix << 1 | h264_cabac_bypass(&t); + *c = t; + } else { + suffix = cabac64_bits_long(c, j); + } + return (1U << j) + suffix + 14U; +} + +/* The UEG3 suffix of decode_cabac_mb_mvd() for mvd >= 9: a unary prefix of + * up to 22 bins, each 1 adding 2^k from k = 3, then k suffix bins. + * INT_MIN for 22 ones, which overflow. */ +static av_noinline av_unused int h264_cabac_mvd_end(CABAC64Context *c, int mvd) +{ + int k = 3; + + while (h264_cabac_bypass(c)) { + mvd += 1 << k; + k++; + if (k > 24) + return INT_MIN; + } + while (k--) + mvd += h264_cabac_bypass(c) << k; + return mvd; +} + +static av_always_inline int h264_cabac_mvd(CABAC64Context *c, int mvd) +{ + int k; + + if (H264_CABAC_BYPASS_CHECKED && cabac64_near_end(c)) { + CABAC64Context t = *c; + mvd = h264_cabac_mvd_end(&t, mvd); + *c = t; + return mvd; + } + k = cabac64_unary(c, 22); + if (k == 22) + return INT_MIN; + k += 3; + mvd += (1 << k) - 8; + if (H264_CABAC_BYPASS_CHECKED && cabac64_near_end(c)) { + CABAC64Context t = *c; + while (k--) + mvd += h264_cabac_bypass(&t) << k; + *c = t; + return mvd; + } + return mvd + (int)cabac64_bits_long(c, k); +} + #endif /* AVCODEC_H264_CABAC64_H */ -- 2.54.0 >From 8ba24f149e398b929f13a015be9a40a62f29f39f Mon Sep 17 00:00:00 2001 From: Kieran Kunhya <[email protected]> Date: Wed, 11 Nov 2026 09:55:24 +0000 Subject: [PATCH 4/4] checkasm: add a test of the H.264 CABAC bins on the 64-bit window Random slices (random, zero- and one-biased, run-heavy and 0xFF-run data, either pointer parity, half of them shorter than 24 bytes so that every kind of step runs on past the end, into zero padding or other data) are decoded by CABACContext, compiled as in h264_cabac.c, and by CABAC64Context, in random sequences of context-coded, bypass and bypass sign bins, the UEG0 and mvd escapes (against the former bin-by-bin loops), the terminate bin, checked versions of the context-coded, bypass and terminate bins (against the C bins with refills that stop at bytestream_end), and I_PCM restarts. After every step the result, the context state and the CABACContext range, low and bytestream must agree. The bins are inline code that does not depend on the cpu flags, so the test runs once, in the C pass, as a variant against CABACContext. --- tests/checkasm/Makefile | 1 + tests/checkasm/checkasm.c | 3 + tests/checkasm/checkasm.h | 1 + tests/checkasm/h264_cabac.c | 299 ++++++++++++++++++++++++++++++++++++ tests/fate/checkasm.mak | 1 + 5 files changed, 305 insertions(+) create mode 100644 tests/checkasm/h264_cabac.c diff --git a/tests/checkasm/Makefile b/tests/checkasm/Makefile index ab1cc17b56c..7594741435e 100644 --- a/tests/checkasm/Makefile +++ b/tests/checkasm/Makefile @@ -42,6 +42,7 @@ AVCODECOBJS-$(CONFIG_DCA_DECODER) += dcadsp.o synth_filter.o AVCODECOBJS-$(CONFIG_DIRAC_DECODER) += diracdsp.o AVCODECOBJS-$(CONFIG_EXR_DECODER) += exrdsp.o AVCODECOBJS-$(CONFIG_FLAC_DECODER) += flacdsp.o +AVCODECOBJS-$(CONFIG_H264_DECODER) += h264_cabac.o AVCODECOBJS-$(CONFIG_JPEG2000_DECODER) += jpeg2000dsp.o AVCODECOBJS-$(CONFIG_MPEG4_DECODER) += mpeg4videodsp.o AVCODECOBJS-$(CONFIG_OPUS_DECODER) += opusdsp.o diff --git a/tests/checkasm/checkasm.c b/tests/checkasm/checkasm.c index e50d2885a3a..82e12f3ddde 100644 --- a/tests/checkasm/checkasm.c +++ b/tests/checkasm/checkasm.c @@ -112,6 +112,9 @@ static const CheckasmTest tests[] = { #if CONFIG_H263DSP { "h263dsp", checkasm_check_h263dsp }, #endif + #if CONFIG_H264_DECODER + { "h264_cabac", checkasm_check_h264_cabac }, + #endif #if CONFIG_H264CHROMA { "h264chroma", checkasm_check_h264chroma }, #endif diff --git a/tests/checkasm/checkasm.h b/tests/checkasm/checkasm.h index 0fc6823c4fb..01a62a75607 100644 --- a/tests/checkasm/checkasm.h +++ b/tests/checkasm/checkasm.h @@ -58,6 +58,7 @@ void checkasm_check_flacdsp(void); void checkasm_check_float_dsp(void); void checkasm_check_g722dsp(void); void checkasm_check_h263dsp(void); +void checkasm_check_h264_cabac(void); void checkasm_check_h264chroma(void); void checkasm_check_h264dsp(void); void checkasm_check_h264pred(void); diff --git a/tests/checkasm/h264_cabac.c b/tests/checkasm/h264_cabac.c new file mode 100644 index 00000000000..8e1289f6fb5 --- /dev/null +++ b/tests/checkasm/h264_cabac.c @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2026 Open Broadcast Systems Ltd + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with FFmpeg; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/* the reader mode of h264_cabac.c, so that the CABACContext bins below are + * the ones the H.264 decoder used */ +#define UNCHECKED_BITSTREAM_READER 1 + +#include <limits.h> +#include <string.h> + +#include "checkasm.h" +#include "libavcodec/cabac.h" +#include "libavcodec/cabac_functions.h" +#include "libavcodec/h264_cabac64.h" + +#define BUF_SIZE 768 +#define PAD 2048 +#define NCTX 64 + +/* both engines at the same point: range, low and bytestream */ +static int same(const CABAC64Context *c, const CABACContext *r) +{ + int low; + const uint8_t *bs = cabac64_state16(c, &low); + + return c->range == r->range && low == r->low && bs == r->bytestream; +} + +/* the coeff_abs_level_minus1 escape of decode_cabac_residual(), bin by bin */ +static unsigned ref_ueg0(CABACContext *c) +{ + unsigned coeff_abs = 1; + int j = 0; + + while (get_cabac_bypass(c) && j < 16 + 7) + j++; + while (j--) + coeff_abs += coeff_abs + get_cabac_bypass(c); + return coeff_abs + 14U; +} + +/* the UEG3 suffix of decode_cabac_mb_mvd(), bin by bin; INT_MIN for its + * overflow */ +static int ref_mvd(CABACContext *c, int mvd) +{ + int k = 3; + + while (get_cabac_bypass(c)) { + mvd += 1 << k; + k++; + if (k > 24) + return INT_MIN; + } + while (k--) + mvd += get_cabac_bypass(c) << k; + return mvd; +} + +/* the C bins of cabac_functions.h in a checked reader: the refills stop at + * bytestream_end */ +static void ref_refill_checked(CABACContext *c) +{ + c->low += (c->bytestream[0] << 9) + (c->bytestream[1] << 1); + c->low -= CABAC_MASK; + if (c->bytestream < c->bytestream_end) + c->bytestream += 2; +} + +static int ref_get_checked(CABACContext *c, uint8_t *const state) +{ + int s = *state; + int lps = ff_h264_cabac_tables[H264_LPS_RANGE_OFFSET + 2 * (c->range & 0xC0) + s]; + int mask, shift; + + c->range -= lps; + mask = ((c->range << (CABAC_BITS + 1)) - c->low) >> 31; + c->low -= (c->range << (CABAC_BITS + 1)) & mask; + c->range += (lps - c->range) & mask; + s ^= mask; + *state = ff_h264_cabac_tables[H264_MLPS_STATE_OFFSET + 128 + s]; + shift = ff_h264_cabac_tables[H264_NORM_SHIFT_OFFSET + c->range]; + c->range <<= shift; + c->low <<= shift; + if (!(c->low & CABAC_MASK)) { + int i = 7 - ff_h264_cabac_tables[H264_NORM_SHIFT_OFFSET + + ((c->low ^ (c->low - 1)) >> (CABAC_BITS - 1))]; + int x = (c->bytestream[0] << 9) + (c->bytestream[1] << 1) - CABAC_MASK; + + c->low += x * (1 << i); + if (c->bytestream < c->bytestream_end) + c->bytestream += 2; + } + return s & 1; +} + +static int ref_bypass_checked(CABACContext *c) +{ + int range; + + c->low += c->low; + if (!(c->low & CABAC_MASK)) + ref_refill_checked(c); + range = c->range << (CABAC_BITS + 1); + if (c->low < range) + return 0; + c->low -= range; + return 1; +} + +static int ref_terminate_checked(CABACContext *c) +{ + c->range -= 2; + if (c->low < c->range << (CABAC_BITS + 1)) { + int shift = (uint32_t)(c->range - 0x100) >> 31; + c->range <<= shift; + c->low <<= shift; + if (!(c->low & CABAC_MASK)) + ref_refill_checked(c); + return 0; + } + return c->bytestream - c->bytestream_start; +} + +/* the same bins on the window, as a checked reader decodes them */ +static int new_get_checked(CABAC64Context *c, uint8_t *const state) +{ + return cabac64_near_end(c) ? cabac64_get_end(c, state) : cabac64_get(c, state); +} + +static int new_bypass_checked(CABAC64Context *c) +{ + return cabac64_near_end(c) ? cabac64_bypass_end(c) : cabac64_bypass(c); +} + +static int new_terminate_checked(CABAC64Context *c) +{ + return cabac64_near_end(c) ? cabac64_terminate_end(c) : cabac64_terminate(c); +} + +static void fill(uint8_t *buf, int size, int mode) +{ + for (int i = 0; i < size; i++) { + switch (mode) { + case 0: buf[i] = rnd(); break; + case 1: buf[i] = rnd() & rnd(); break; + case 2: buf[i] = rnd() | rnd(); break; + case 3: buf[i] = rnd() & 1 ? 0xFF : rnd() & rnd() & rnd(); break; + case 4: buf[i] = i & 32 ? 0 : rnd(); break; + /* long 0xFF runs: long runs of 1 bypass bins, near the end too */ + default: buf[i] = i & 16 ? 0xFF : rnd(); break; + } + } +} + +/* + * Random slices (random, zero- and one-biased, run-heavy and 0xFF-run data, + * either pointer parity, half of them shorter than 24 bytes, so that every + * kind of step runs on past the end, into zero padding or other data) are + * decoded by CABACContext and by the window in random sequences of the bins + * H.264 uses: + * context-coded, bypass and bypass sign bins, the UEG0 and mvd escapes, the + * terminate bin, checked versions of the context-coded, bypass and + * terminate bins, and I_PCM restarts. After every step the result, the + * context state and the CABACContext range, low and bytestream must agree. + */ +static void check_cabac(void) +{ + static uint8_t buf[BUF_SIZE + PAD]; + uint8_t st_n[NCTX], st_r[NCTX]; + int ok = 1; + + /* The bins are inline code that does not depend on the cpu flags, so + * they are tested once, as a variant of the C version: CABACContext is + * the reference, which is registered first, and the window the + * variant. */ + check_key((CheckasmKey)ref_ueg0, "h264_cabac"); + checkasm_set_func_variant("cabac64"); + if (!check_key((CheckasmKey)check_cabac, "h264_cabac")) + return; + + for (int iter = 0; iter < 4000 && ok; iter++) { + CABAC64Context c; + CABACContext r; + int off = (iter >> 3) & 1; + int size = iter & 1 ? rnd() % 24 : rnd() % BUF_SIZE; + int nctx = 1 + rnd() % NCTX; + int ret_r, ret_n; + + fill(buf, sizeof(buf), (iter >> 1) % 6); + /* past the end: the zero padding of the NAL buffer, or other data */ + if (iter & 2) + memset(buf + off + size, 0, 64); + ret_r = ff_init_cabac_decoder(&r, buf + off, size); + ret_n = cabac64_init(&c, buf + off, size); + if (ret_r != ret_n || !same(&c, &r)) { + ok = 0; + break; + } + if (ret_r < 0) + continue; + for (int i = 0; i < NCTX; i++) + st_n[i] = st_r[i] = rnd() % 126; + + for (int op = 0; op < 4000 && ok; op++) { + int kind = rnd() % 40, ctx = rnd() % nctx; + int a = 0, b = 0, val; + + if ((uintptr_t)r.bytestream > (uintptr_t)r.bytestream_end + 128) + break; + if (kind < 16) { + a = get_cabac_inline(&r, &st_r[ctx]); + b = h264_cabac_get(&c, &st_n[ctx]); + ok = st_r[ctx] == st_n[ctx]; + } else if (kind < 20) { + a = get_cabac_bypass(&r); + b = h264_cabac_bypass(&c); + } else if (kind < 24) { + val = rnd() % 4096 - 2048; + a = get_cabac_bypass_sign(&r, val); + b = h264_cabac_bypass_sign(&c, val); + } else if (kind < 26) { + a = ref_ueg0(&r); + b = h264_cabac_ueg0(&c); + } else if (kind < 28) { + a = ref_mvd(&r, 9); + b = h264_cabac_mvd(&c, 9); + if (a == INT_MIN) + op = INT_MAX - 1; /* the macroblock fails there */ + } else if (kind < 29) { + a = get_cabac_terminate(&r); + b = h264_cabac_terminate(&c); + if (a) + op = INT_MAX - 1; /* end of slice */ + } else if (kind < 31) { + a = ref_terminate_checked(&r); + b = new_terminate_checked(&c); + if (a) + op = INT_MAX - 1; + } else if (kind < 35) { + a = ref_get_checked(&r, &st_r[ctx]); + b = new_get_checked(&c, &st_n[ctx]); + ok = st_r[ctx] == st_n[ctx]; + } else if (kind < 39) { + a = ref_bypass_checked(&r); + b = new_bypass_checked(&c); + } else if (!(rnd() & 7)) { + /* I_PCM: the restart after the bins, as decode_mb_cabac() */ + const uint8_t *pr = r.bytestream, *pn; + int n = rnd() % 16; + + if (r.low & 0x1) + pr--; + if (r.low & 0x1FF) + pr--; + pn = cabac64_ptr(&c); + if (pr != pn) { + ok = 0; + break; + } + if ((int)(r.bytestream_end - pr) < n) + break; + pr += n; + a = ff_init_cabac_decoder(&r, pr, r.bytestream_end - pr); + b = cabac64_init(&c, pr, c.bytestream_end - pr); + if (a < 0) + op = INT_MAX - 1; + } + ok = ok && a == b && same(&c, &r); + if (!ok) + fprintf(stderr, "h264_cabac: slice %d (size %d) step %d, kind %d: " + "%d vs %d\n", iter, size, op, kind, a, b); + } + } + if (!ok) + fail(); +} + +void checkasm_check_h264_cabac(void) +{ + check_cabac(); + report("cabac"); +} diff --git a/tests/fate/checkasm.mak b/tests/fate/checkasm.mak index 19bbe7e571a..5d8760a9b95 100644 --- a/tests/fate/checkasm.mak +++ b/tests/fate/checkasm.mak @@ -23,6 +23,7 @@ FATE_CHECKASM = fate-checkasm-aacencdsp \ fate-checkasm-float_dsp \ fate-checkasm-g722dsp \ fate-checkasm-h263dsp \ + fate-checkasm-h264_cabac \ fate-checkasm-h264chroma \ fate-checkasm-h264dsp \ fate-checkasm-h264pred \ -- 2.54.0 _______________________________________________ ffmpeg-devel mailing list -- [email protected] To unsubscribe send an email to [email protected]
