PR #26413 opened by Justin Jacob (justsrc)
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26413
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26413.patch

# Summary of changes

These five patches speed up the JPEG 2000 decoder by packing the MQ 
probability-state and tier-1 flag representations, skipping no-op ROI 
reconstruction passes, and writing packed three-component 16-bit frames in one 
interleaved pass.

On a 240-frame 4096x1714 XYZ 12-bit 9/7 digital-cinema stream decoded to `-f 
null -` on an Apple M1 Pro (macOS, Apple Clang), the series reaches a 1.10x 
wall-time and 1.09x user-CPU same-round median speedup at 8 threads across nine 
interleaved rounds. Minimum wall time drops from 18.40 s to 16.73 s, and 
minimum user CPU drops from 141.13 s to 128.76 s. At 1 thread in an interleaved 
pass, wall time drops from 112.88 s to 96.15 s (1.17x), and user CPU drops from 
111.47 s to 95.33 s (1.17x). Peak RSS drops from 1454 MiB to 1415 MiB.

Decoded output is bit-exact (`framemd5`-identical) with stock across 1, 2, 4, 
8, and 16 threads. Public APIs and ABIs do not change.

## Patches

1. **avcodec/mqc: decode symbols from packed probability states.** Each symbol 
previously required separate loads for Qe, the MPS, and the next state, and 
renormalization shifted one bit at a time. This patch packs Qe, MPS, next-MPS, 
and next-LPS into one 32-bit `ff_mqc_packed` entry, holds the code register and 
up to 48 bits of read-ahead in a 64-bit register, and renormalizes once per 
multi-bit shift with a branchless decision. State stays caller-local, and raw 
bypass segments remain unchanged. It also adds `libavcodec/tests/mqc.c` and 
`fate-j2k-mqc` to verify every packed table entry and compare packed and raw 
decoding against the scalar decoder over random, 0xFF-stuffed, marker-heavy, 
and exact-length `0xff 0xff` sentinel buffers.
2. **avcodec/jpeg2000: pack the tier-1 context tables.** This patch indexes the 
zero-coding LUT by band first so the band index stays loop-invariant in tier-1, 
packs each sign context with its XOR bit into one entry, and adds the packed 
3x3 window and sign-key LUTs. It also inlines the encoder's significance update 
in `j2kenc.c`.
3. **avcodec/jpeg2000dec: decode tier-1 over packed flag columns.** This patch 
replaces per-coefficient flag words with one `uint32_t` per four-row stripe 
column (`flags32` in `Jpeg2000T1Context`), holding the 3x6 significance 
neighborhood in bits 0-17 alongside per-row sign, refinement, visited, and 
stripe-edge sign bits. A new significant coefficient updates three words 
instead of nine. Visited marks let the significance and refinement passes skip 
clean columns, and the cleanup pass skips all-zero column runs directly. 
`MqcState` stays in registers across passes, and the patch drops the unused 
`ff_jpeg2000_set_significance()` helper. In a four-round rotating per-commit 
chain, this commit alone yields a 1.056x wall-time and 1.058x user-CPU median 
speedup.
4. **avcodec/jpeg2000dec: skip the sample rewrite without ROI.** When 
`roi_shift` is zero, the reconstruction loop masks off the sign bit and writes 
each coefficient back unchanged. Returning early skips that loop.
5. **avcodec/jpeg2000dec: write packed output in one pass.** This patch adds 
`can_write_packed()` and `write_frame_16_packed()` for three-component packed 
>8-bit `FF_DWT97` frames whose components share the same geometry and bit 
depth, replacing three strided per-component loops with one interleaved pass.

## Benchmarks

Nine interleaved rounds on an Apple M1 Pro (10 cores, macOS, Apple Clang) 
decoding 240 frames of 4096x1714 XYZ 12-bit 9/7 JPEG 2000 with `-threads 8 -f 
null -` give the following times.

| Build | Min real (s) | Median real (s) | Min user (s) | Median user (s) | 
Wall (min) | CPU (min) |
|---|---:|---:|---:|---:|---:|---:|
| stock | 18.400 | 18.660 | 141.130 | 141.690 | 1.000x | 1.000x |
| series | 16.730 | 17.280 | 128.760 | 130.150 | 1.100x | 1.096x |

Across the nine rounds, the same-round median ratios are 1.097x real and 1.092x 
user CPU.

## Testing and verification

- On the current rebased branch over upstream `master`, `make fate-j2k-mqc` and 
`libavcodec/tests/mqc` pass. `git diff --check` is clean, and `git range-diff` 
against the pre-rebase series is identical across three unrelated 
`avutil/hwcontext_amf` commits.
- On the pre-rebase series, which has an identical patch diff, every commit 
builds and passes `fate-jpeg2000dec` (16/16) and `fate-j2k-mqc` on its own.
- Both x86_64 and arm64 Linux builds under ASan, LSan, and UBSan, plus a local 
macOS ASan and UBSan build, pass `fate-jpeg2000dec` (16/16), synthetic 
8/12/16-bit 5/3 and 9/7 tiled and JP2 edge-case codestreams (including packed 
`rgb48le`), the 240-frame 4K corpus at 1, 4, and 8 threads, and 2268 malformed 
or truncated inputs with zero crashes, timeouts, or sanitizer findings.
- Corpus `framemd5` output matches stock at auto, 1, 2, 4, 8, and 16 threads.
- Static analysis with `clang --analyze` finds only two pre-existing dead 
stores in `jpeg2000dec.c`, and `tools/patcheck` reports only comment false 
positives.

FATE passes `-flags +bitexact`, which selects the integer 9/7 transform rather 
than `FF_DWT97`, so FATE cannot enter `write_frame_16_packed()`. The 240-frame 
4K corpus and `rgb48le` 9/7 decode tests exercise that function and match stock 
output.

## Notes for review

- Patch 2 touches `j2kenc.c` only to inline the encoder's significance update. 
The decoder's `flags32` array shares a union with `flags` in 
`Jpeg2000T1Context`, leaving the encoder path unchanged.
- Raw bypass arithmetic decoding stays unchanged.


From 1add65f26f789ce1446d60f03f94d12ce3a42529 Mon Sep 17 00:00:00 2001
From: Justin Jacob <[email protected]>
Date: Tue, 24 Nov 2026 00:57:52 +0530
Subject: [PATCH 1/5] avcodec/mqc: decode symbols from packed probability
 states

Each symbol loads Qe, the MPS and the next state from three tables,
and renormalization shifts the 32-bit C register one bit at a time.
Pack the four values into one 32-bit entry, hold C and up to 48 bits of
read-ahead in a 64-bit register, and renormalize once for all the
shifts the read-ahead covers. Raw (bypass) segments keep the 32-bit
byte input.

The tier-1 loops call this for every coded coefficient, so keep the
state caller-local and make the decision branchless: the two exchanges
differ only in which side of the comparison selects the next state.

Add a differential unit test (fate-j2k-mqc) that checks every packed
table entry against the scalar tables and compares the packed and raw
decoders against the scalar decoder over random byte streams with
0xFF stuffing and marker sequences. Seeded context states cover the
whole packed table, and exact-length buffers end in the code-block
0xff 0xff sentinel so the read-ahead and byte pointer are checked at
the tail.

Signed-off-by: Justin Jacob <[email protected]>
---
 libavcodec/Makefile         |   1 +
 libavcodec/mqc.c            |  31 +++
 libavcodec/mqc.h            | 137 ++++++++++++
 libavcodec/mqcdec.c         |  78 +------
 libavcodec/tests/.gitignore |   1 +
 libavcodec/tests/mqc.c      | 422 ++++++++++++++++++++++++++++++++++++
 tests/fate/libavcodec.mak   |   5 +
 7 files changed, 609 insertions(+), 66 deletions(-)
 create mode 100644 libavcodec/tests/mqc.c

diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index c3da8412c60..ab342de8d41 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -1404,6 +1404,7 @@ TESTPROGS-$(CONFIG_ENCODERS)              += 
hw_base_encode
 TESTPROGS-$(CONFIG_GOLOMB)                += golomb
 TESTPROGS-$(CONFIG_IDCTDSP)               += dct
 TESTPROGS-$(CONFIG_DXV_ENCODER)           += hashtable
+TESTPROGS-$(CONFIG_JPEG2000_DECODER)      += mqc
 TESTPROGS-$(CONFIG_MJPEG_ENCODER)         += mjpegenc_huffman
 TESTPROGS-$(CONFIG_MPEGAUDIOHEADER)       += mpegaudiodecheader
 TESTPROGS-$(CONFIG_MPEGVIDEO)             += mpeg12framerate
diff --git a/libavcodec/mqc.c b/libavcodec/mqc.c
index 6f7088ec482..0226001473a 100644
--- a/libavcodec/mqc.c
+++ b/libavcodec/mqc.c
@@ -61,6 +61,37 @@ const uint8_t ff_mqc_nmps[2 * 47] = {
     82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 90, 91, 92, 93
 };
 
+/*
+ * Qe, MPS, next-MPS and next-LPS state of each context state, packed so the
+ * decoder reads all four with one 32-bit load.
+ */
+const uint32_t ff_mqc_packed[2 * 47] = {
+    0x03045601, 0x02075601, 0x0c083401, 0x0d0b3401,
+    0x120c1801, 0x130f1801, 0x18100ac1, 0x19130ac1,
+    0x3a140521, 0x3b170521, 0x42980221, 0x439b0221,
+    0x0d1c5601, 0x0c1f5601, 0x1c205401, 0x1d235401,
+    0x1c244801, 0x1d274801, 0x1c283801, 0x1d2b3801,
+    0x222c3001, 0x232f3001, 0x24302401, 0x25332401,
+    0x28341c01, 0x29371c01, 0x2a741601, 0x2b771601,
+    0x1d3c5601, 0x1c3f5601, 0x1c405401, 0x1d435401,
+    0x1e445101, 0x1f475101, 0x20484801, 0x214b4801,
+    0x224c3801, 0x234f3801, 0x24503401, 0x25533401,
+    0x26543001, 0x27573001, 0x26582801, 0x275b2801,
+    0x285c2401, 0x295f2401, 0x2a602201, 0x2b632201,
+    0x2c641c01, 0x2d671c01, 0x2e681801, 0x2f6b1801,
+    0x306c1601, 0x316f1601, 0x32701401, 0x33731401,
+    0x34741201, 0x35771201, 0x36781101, 0x377b1101,
+    0x387c0ac1, 0x397f0ac1, 0x3a8009c1, 0x3b8309c1,
+    0x3c8408a1, 0x3d8708a1, 0x3e880521, 0x3f8b0521,
+    0x408c0441, 0x418f0441, 0x429002a1, 0x439302a1,
+    0x44940221, 0x45970221, 0x46980141, 0x479b0141,
+    0x489c0111, 0x499f0111, 0x4aa00085, 0x4ba30085,
+    0x4ca40049, 0x4da70049, 0x4ea80025, 0x4fab0025,
+    0x50ac0015, 0x51af0015, 0x52b00009, 0x53b30009,
+    0x54b40005, 0x55b70005, 0x56b40001, 0x57b70001,
+    0x5cb85601, 0x5dbb5601,
+};
+
 void ff_mqc_init_contexts(MqcState *mqc)
 {
     memset(mqc->cx_states, 0, sizeof(mqc->cx_states));
diff --git a/libavcodec/mqc.h b/libavcodec/mqc.h
index 5e782b05f90..a966fc99be2 100644
--- a/libavcodec/mqc.h
+++ b/libavcodec/mqc.h
@@ -30,6 +30,9 @@
 
 #include <stdint.h>
 
+#include "libavutil/attributes.h"
+#include "libavutil/intmath.h"
+
 #define MQC_CX_UNI 17
 #define MQC_CX_RL  18
 
@@ -37,6 +40,13 @@ extern const uint16_t ff_mqc_qe[2 * 47];
 extern const uint8_t  ff_mqc_nlps[2 * 47];
 extern const uint8_t  ff_mqc_nmps[2 * 47];
 
+/*
+ * Probability states packed for the decoder so that one load yields the
+ * value, the MPS and both transitions: Qe in bits 0-15, MPS in bit 16, the
+ * next MPS state in bits 17-23 and the next LPS state in bits 24-30.
+ */
+extern const uint32_t ff_mqc_packed[2 * 47];
+
 typedef struct MqcState {
     uint8_t *bp, *bpstart;
     unsigned int a;
@@ -44,8 +54,135 @@ typedef struct MqcState {
     unsigned int ct;
     uint8_t cx_states[19];
     int raw;
+    uint64_t c64;         ///< code value in bits 48-63, read-ahead below
+    unsigned shift_count; ///< valid read-ahead bits below the code value
 } MqcState;
 
+/*
+ * Decoder. In MQ mode the C-register holds the code value in bits 48-63 and
+ * up to 48 bits of read-ahead below it, so renormalization shifts once for
+ * all the bits it needs instead of once per bit, and the symbol decision is
+ * branchless. This is the form used by T.88 Annex G.
+ *
+ * The tier-1 loops call this millions of times per frame; with the state in
+ * a caller-local MqcState the compiler keeps C, A and the byte pointer in
+ * registers instead of reloading them around a cross-TU call.
+ */
+static av_always_inline void ff_mqc_bytein_inline(MqcState *mqc)
+{
+    /* BYTEIN, repeated while another byte fits below the code value. A byte
+     * after 0xFF may carry into the bits above it, so it is only read once no
+     * read-ahead bits remain; any other byte lands on zero bits and can be
+     * read early without changing what the cell sees. */
+    while (mqc->shift_count <= 40) {
+        if (*mqc->bp == 0xff) {
+            if (mqc->bp[1] > 0x8f) {
+                mqc->shift_count += 8;
+            } else if (!mqc->shift_count) {
+                mqc->bp++;
+                mqc->c64 += (0x7fULL << 41) - ((uint64_t)*mqc->bp << 41);
+                mqc->shift_count = 7;
+            } else
+                break;
+        } else {
+            mqc->bp++;
+            mqc->c64 += (uint64_t)(*mqc->bp ^ 0xff) << (40 - mqc->shift_count);
+            mqc->shift_count += 8;
+        }
+    }
+}
+
+/* RENORMD: shift A back to at least 0x8000, batching the shifts the
+ * read-ahead bits cover. */
+static av_always_inline void ff_mqc_renorm_inline(MqcState *mqc)
+{
+    while (!(mqc->a & 0x8000)) {
+        unsigned shift;
+
+        ff_mqc_bytein_inline(mqc);
+        shift = ff_clz(mqc->a) - 16;
+        if (shift > mqc->shift_count)
+            shift = mqc->shift_count;
+        mqc->a       <<= shift;
+        mqc->c64     <<= shift;
+        mqc->shift_count -= shift;
+    }
+}
+
+/* Byte input of the 32-bit C-register, kept for the raw (bypass) segments. */
+static av_always_inline void ff_mqc_bytein32_inline(MqcState *mqc)
+{
+    if (*mqc->bp == 0xff) {
+        if (*(mqc->bp + 1) > 0x8f)
+            mqc->c++;
+        else {
+            mqc->bp++;
+            mqc->c += 2 + 0xfe00 - (*mqc->bp << 9);
+        }
+    } else {
+        mqc->bp++;
+        mqc->c += 1 + 0xff00 - (*mqc->bp << 8);
+    }
+}
+
+static av_always_inline int ff_mqc_decode_bypass_inline(MqcState *mqc)
+{
+    int bit = !(mqc->c & 0x40000000);
+
+    if (!(mqc->c & 0xff)) {
+        mqc->c -= 0x100;
+        ff_mqc_bytein32_inline(mqc);
+    }
+    mqc->c += mqc->c;
+
+    return bit;
+}
+
+static av_always_inline int ff_mqc_decode_inline(MqcState *mqc,
+                                                 uint8_t *cxstate)
+{
+    uint32_t state, qe, a, is_lps, mask, cond, pick_nlps;
+    uint64_t mask64;
+    unsigned shift;
+    uint8_t *cx = cxstate;
+
+    if (mqc->raw)
+        return ff_mqc_decode_bypass_inline(mqc);
+
+    state = ff_mqc_packed[*cx];
+    qe    = state & 0xffff;
+    a     = mqc->a - qe;
+
+    /* The MPS/LPS decision, MPS_EXCHANGE and LPS_EXCHANGE of C.3.2, without
+     * branches: both exchanges differ only in whether the condition flips
+     * the role of the exchange, so one XOR handles both. */
+    is_lps = (mqc->c64 >> 48) >= a;
+    mask   = 0 - is_lps;
+    mask64 = 0 - (uint64_t)is_lps;
+    mqc->c64 -= ((uint64_t)a << 48) & mask64;
+    mqc->a    = (a & ~mask) | (qe & mask);
+
+    cond      = a < qe;
+    pick_nlps = cond ^ is_lps;
+    /* A probability-state transition happens exactly when A renormalizes:
+     * on every LPS, and on an MPS that leaves A below 0x8000. */
+    *cx = (is_lps | (a < 0x8000))
+        ? (state >> (17 + 7 * pick_nlps)) & 0x7f
+        : *cx;
+
+    /* Zero shifts in the common case, where A >= 0x8000 already. */
+    shift = ff_clz(mqc->a) - 16;
+    if (shift <= mqc->shift_count) {
+        mqc->a       <<= shift;
+        mqc->c64     <<= shift;
+        mqc->shift_count -= shift;
+    } else {
+        ff_mqc_renorm_inline(mqc);
+    }
+
+    return ((state >> 16) & 1) ^ pick_nlps;
+}
+
 /* encoder */
 
 /** initialize the encoder */
diff --git a/libavcodec/mqcdec.c b/libavcodec/mqcdec.c
index 34aa51951eb..126bfb1e4db 100644
--- a/libavcodec/mqcdec.c
+++ b/libavcodec/mqcdec.c
@@ -27,81 +27,27 @@
 
 #include "mqc.h"
 
-static void bytein(MqcState *mqc)
-{
-    if (*mqc->bp == 0xff) {
-        if (*(mqc->bp + 1) > 0x8f)
-            mqc->c++;
-        else {
-            mqc->bp++;
-            mqc->c += 2 + 0xfe00 - (*mqc->bp << 9);
-        }
-    } else {
-        mqc->bp++;
-        mqc->c += 1 + 0xff00 - (*mqc->bp << 8);
-    }
-}
-
-static int exchange(MqcState *mqc, uint8_t *cxstate, int lps)
-{
-    int d;
-    if ((mqc->a < ff_mqc_qe[*cxstate]) ^ (!lps)) {
-        if (lps)
-            mqc->a = ff_mqc_qe[*cxstate];
-        d = *cxstate & 1;
-        *cxstate = ff_mqc_nmps[*cxstate];
-    } else {
-        if (lps)
-            mqc->a = ff_mqc_qe[*cxstate];
-        d = 1 - (*cxstate & 1);
-        *cxstate = ff_mqc_nlps[*cxstate];
-    }
-    // do RENORMD: see ISO/IEC 15444-1:2002 §C.3.3
-    do {
-        if (!(mqc->c & 0xff)) {
-            mqc->c -= 0x100;
-            bytein(mqc);
-        }
-        mqc->a += mqc->a;
-        mqc->c += mqc->c;
-    } while (!(mqc->a & 0x8000));
-    return d;
-}
-
 void ff_mqc_initdec(MqcState *mqc, uint8_t *bp, int raw, int reset)
 {
     mqc->raw = raw;
     if (reset)
         ff_mqc_init_contexts(mqc);
     mqc->bp = bp;
-    mqc->c  = (*mqc->bp ^ 0xff) << 16;
-    bytein(mqc);
-    mqc->c = mqc->c << 7;
-    mqc->a = 0x8000;
-}
-
-static int mqc_decode_bypass(MqcState *mqc) {
-    int bit = !(mqc->c & 0x40000000);
-    if (!(mqc->c & 0xff)) {
-        mqc->c -= 0x100;
-        bytein(mqc);
+    if (raw) {
+        mqc->c  = (*mqc->bp ^ 0xff) << 16;
+        ff_mqc_bytein32_inline(mqc);
+        mqc->c = mqc->c << 7;
+    } else {
+        mqc->c64 = (uint64_t)(*mqc->bp ^ 0xff) << 48;
+        mqc->shift_count = 0;
+        ff_mqc_bytein_inline(mqc);
+        mqc->c64 <<= 7;
+        mqc->shift_count -= 7;
     }
-    mqc->c += mqc->c;
-    return bit;
+    mqc->a = 0x8000;
 }
 
 int ff_mqc_decode(MqcState *mqc, uint8_t *cxstate)
 {
-    if (mqc->raw)
-        return mqc_decode_bypass(mqc);
-    mqc->a -= ff_mqc_qe[*cxstate];
-    if ((mqc->c >> 16) < mqc->a) {
-        if (mqc->a & 0x8000)
-            return *cxstate & 1;
-        else
-            return exchange(mqc, cxstate, 0);
-    } else {
-        mqc->c -= mqc->a << 16;
-        return exchange(mqc, cxstate, 1);
-    }
+    return ff_mqc_decode_inline(mqc, cxstate);
 }
diff --git a/libavcodec/tests/.gitignore b/libavcodec/tests/.gitignore
index f78e17f5882..6c958f9fafb 100644
--- a/libavcodec/tests/.gitignore
+++ b/libavcodec/tests/.gitignore
@@ -20,6 +20,7 @@
 /mjpegenc_huffman
 /mpeg12framerate
 /mpegaudiodecheader
+/mqc
 /packet_side_data_handle
 /qpfile_parser
 /rangecoder
diff --git a/libavcodec/tests/mqc.c b/libavcodec/tests/mqc.c
new file mode 100644
index 00000000000..7e407019907
--- /dev/null
+++ b/libavcodec/tests/mqc.c
@@ -0,0 +1,422 @@
+/*
+ * MQ-coder differential test
+ *
+ * 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 <inttypes.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "libavutil/common.h"
+#include "libavutil/lfg.h"
+
+#include "libavcodec/mqc.h"
+
+#define DATA_SIZE   4096
+#define BUF_SIZE    8192
+#define NUM_TRIALS  1024
+#define NUM_SYMBOLS 4096
+
+/* The packed table is hand-built; check every entry against the scalar
+ * tables, including states the decoder may never reach. */
+static int check_packed_table(void)
+{
+    int i;
+
+    for (i = 0; i < 2 * 47; i++) {
+        uint32_t expected = ff_mqc_qe[i] |
+                            ((uint32_t)(i & 1) << 16) |
+                            ((uint32_t)ff_mqc_nmps[i] << 17) |
+                            ((uint32_t)ff_mqc_nlps[i] << 24);
+
+        if (ff_mqc_packed[i] != expected) {
+            fprintf(stderr,
+                    "packed[%d] mismatch: 0x%08"PRIx32" != 0x%08"PRIx32"\n",
+                    i, ff_mqc_packed[i], expected);
+            return 1;
+        }
+    }
+
+    return 0;
+}
+
+/* Scalar reference decoder copied from the pre-rewrite mqcdec.c. */
+static void bytein_ref(MqcState *mqc)
+{
+    if (*mqc->bp == 0xff) {
+        if (*(mqc->bp + 1) > 0x8f)
+            mqc->c++;
+        else {
+            mqc->bp++;
+            mqc->c += 2 + 0xfe00 - (*mqc->bp << 9);
+        }
+    } else {
+        mqc->bp++;
+        mqc->c += 1 + 0xff00 - (*mqc->bp << 8);
+    }
+}
+
+static int exchange_ref(MqcState *mqc, uint8_t *cxstate, int lps)
+{
+    int d;
+    if ((mqc->a < ff_mqc_qe[*cxstate]) ^ (!lps)) {
+        if (lps)
+            mqc->a = ff_mqc_qe[*cxstate];
+        d = *cxstate & 1;
+        *cxstate = ff_mqc_nmps[*cxstate];
+    } else {
+        if (lps)
+            mqc->a = ff_mqc_qe[*cxstate];
+        d = 1 - (*cxstate & 1);
+        *cxstate = ff_mqc_nlps[*cxstate];
+    }
+    // do RENORMD: see ISO/IEC 15444-1:2002 §C.3.3
+    do {
+        if (!(mqc->c & 0xff)) {
+            mqc->c -= 0x100;
+            bytein_ref(mqc);
+        }
+        mqc->a += mqc->a;
+        mqc->c += mqc->c;
+    } while (!(mqc->a & 0x8000));
+    return d;
+}
+
+static void ff_mqc_initdec_ref(MqcState *mqc, uint8_t *bp, int raw, int reset)
+{
+    mqc->raw = raw;
+    if (reset)
+        ff_mqc_init_contexts(mqc);
+    mqc->bp = bp;
+    mqc->c  = (*mqc->bp ^ 0xff) << 16;
+    bytein_ref(mqc);
+    mqc->c = mqc->c << 7;
+    mqc->a = 0x8000;
+}
+
+static int mqc_decode_bypass_ref(MqcState *mqc)
+{
+    int bit = !(mqc->c & 0x40000000);
+    if (!(mqc->c & 0xff)) {
+        mqc->c -= 0x100;
+        bytein_ref(mqc);
+    }
+    mqc->c += mqc->c;
+    return bit;
+}
+
+static int ff_mqc_decode_ref(MqcState *mqc, uint8_t *cxstate)
+{
+    if (mqc->raw)
+        return mqc_decode_bypass_ref(mqc);
+    mqc->a -= ff_mqc_qe[*cxstate];
+    if ((mqc->c >> 16) < mqc->a) {
+        if (mqc->a & 0x8000)
+            return *cxstate & 1;
+        else
+            return exchange_ref(mqc, cxstate, 0);
+    } else {
+        mqc->c -= mqc->a << 16;
+        return exchange_ref(mqc, cxstate, 1);
+    }
+}
+
+static void fill_buffer(uint8_t *buf, AVLFG *prng, int trial)
+{
+    static const uint8_t stuffed_tails[] = { 0x00, 0x7f, 0x80, 0x8f };
+    static const uint8_t marker_tails[]  = { 0x90, 0xd9, 0xfe, 0xff };
+    int i;
+
+    memset(buf, 0, BUF_SIZE);
+
+    if ((trial & 3) == 0) {
+        /* Sparse/repetitive patterns exercise long MPS and LPS runs. */
+        uint8_t fill = (trial & 4) ? 0xff : 0x00;
+        memset(buf, fill, DATA_SIZE);
+        for (i = 0; i < 32; i++) {
+            int pos = av_lfg_get(prng) % (DATA_SIZE - 4);
+            buf[pos]     = 0xff;
+            buf[pos + 1] = (trial & 8) ? marker_tails[i & 3] : stuffed_tails[i 
& 3];
+        }
+    } else {
+        for (i = 0; i < DATA_SIZE; i++)
+            buf[i] = av_lfg_get(prng) & 0xff;
+
+        /* On half of the random trials, keep 0xFF bytes stuffed so bp crosses
+         * the entire 4 KiB payload into the zero tail. */
+        if ((trial & 3) == 1) {
+            for (i = 0; i < DATA_SIZE - 1; i++) {
+                if (buf[i] == 0xff && buf[i + 1] > 0x8f)
+                    buf[i + 1] &= 0x7f;
+            }
+        }
+
+        for (i = 0; i < 16; i++) {
+            int pos = av_lfg_get(prng) % (DATA_SIZE - 8);
+            int kind = (trial & 3) == 1 ? (i & 3) : (i & 7);
+
+            if (kind < 4) {
+                buf[pos]     = 0xff;
+                buf[pos + 1] = stuffed_tails[kind];
+            } else if (kind < 7) {
+                buf[pos]     = 0xff;
+                buf[pos + 1] = marker_tails[kind - 4];
+            } else {
+                buf[pos]     = 0xff;
+                buf[pos + 1] = 0xff;
+                buf[pos + 2] = 0xff;
+                buf[pos + 3] = stuffed_tails[i & 3];
+            }
+        }
+    }
+
+    /* Exercise deliberate 0xFF pairs right at the stream start and tail 
boundary. */
+    switch (trial) {
+    case 0:
+        buf[0] = 0xff;
+        buf[1] = 0x8f;
+        break;
+    case 1:
+        buf[0] = 0xff;
+        buf[1] = 0x00;
+        break;
+    case 2:
+        buf[0] = 0xff;
+        buf[1] = 0x90;
+        break;
+    case 3:
+        buf[0] = 0xff;
+        buf[1] = 0xff;
+        break;
+    case 4:
+        buf[DATA_SIZE - 1] = 0xff;
+        break;
+    }
+}
+
+static int run_trials(int raw, AVLFG *prng)
+{
+    uint8_t buf[BUF_SIZE];
+    int trial, sym, k;
+
+    for (trial = 0; trial < NUM_TRIALS; trial++) {
+        MqcState dec, ref;
+        int reset = trial & 1;
+
+        fill_buffer(buf, prng, trial);
+
+        memset(&dec, 0, sizeof(dec));
+        memset(&ref, 0, sizeof(ref));
+        ff_mqc_init_contexts(&dec);
+        ff_mqc_init_contexts(&ref);
+
+        ff_mqc_initdec(&dec, buf, raw, reset);
+        ff_mqc_initdec_ref(&ref, buf, raw, reset);
+
+        /* Seed after initdec() so the injected states survive a reset. The
+         * eight-trial groups walk 19 consecutive entries each; over the 128
+         * groups every packed state is used at least once. */
+        if ((trial & 7) >= 6) {
+            for (k = 0; k < 19; k++) {
+                uint8_t st = ((trial >> 3) * 19 + k) % 94;
+                dec.cx_states[k] = st;
+                ref.cx_states[k] = st;
+            }
+        }
+
+        if (memcmp(dec.cx_states, ref.cx_states, sizeof(dec.cx_states))) {
+            fprintf(stderr, "init context mismatch (raw=%d trial=%d 
reset=%d)\n",
+                    raw, trial, reset);
+            return 1;
+        }
+
+        for (sym = 0; sym < NUM_SYMBOLS; sym++) {
+            int cx = ((trial & 3) == 0) ? ((trial >> 2) % 19)
+                                        : (av_lfg_get(prng) % 19);
+            int bit = (trial & 2)
+                ? ff_mqc_decode(&dec, dec.cx_states + cx)
+                : ff_mqc_decode_inline(&dec, dec.cx_states + cx);
+            int bit_ref = ff_mqc_decode_ref(&ref, ref.cx_states + cx);
+
+            if (bit != bit_ref || dec.a != ref.a) {
+                fprintf(stderr,
+                        "mismatch (raw=%d trial=%d sym=%d cx=%d): "
+                        "bit=%d ref_bit=%d a=0x%x ref_a=0x%x\n",
+                        raw, trial, sym, cx, bit, bit_ref, dec.a, ref.a);
+                return 1;
+            }
+
+            if (dec.bp < ref.bp) {
+                fprintf(stderr,
+                        "bp behind reference (raw=%d trial=%d sym=%d): "
+                        "bp=%d ref_bp=%d\n",
+                        raw, trial, sym, (int)(dec.bp - buf),
+                        (int)(ref.bp - buf));
+                return 1;
+            }
+
+            if (raw) {
+                if (dec.c != ref.c) {
+                    fprintf(stderr,
+                            "raw c mismatch (trial=%d sym=%d): c=0x%x 
ref_c=0x%x\n",
+                            trial, sym, dec.c, ref.c);
+                    return 1;
+                }
+            } else {
+                if ((unsigned)(dec.c64 >> 48) != (unsigned)(ref.c >> 16)) {
+                    fprintf(stderr,
+                            "code mismatch (trial=%d sym=%d): c=0x%x 
ref_c=0x%x\n",
+                            trial, sym, (unsigned)(dec.c64 >> 48),
+                            (unsigned)(ref.c >> 16));
+                    return 1;
+                }
+                for (k = 0; k < 19; k++) {
+                    if (dec.cx_states[k] != ref.cx_states[k]) {
+                        fprintf(stderr,
+                                "cx_states[%d] mismatch (trial=%d sym=%d 
cx=%d): "
+                                "%u != %u\n",
+                                k, trial, sym, cx,
+                                dec.cx_states[k], ref.cx_states[k]);
+                        return 1;
+                    }
+                }
+            }
+        }
+    }
+
+    return 0;
+}
+
+static void fill_sentinel_buffer(uint8_t *buf, int len, AVLFG *prng, int trial)
+{
+    int i;
+
+    for (i = 0; i < len; i++) {
+        if ((trial & 3) == 0)
+            buf[i] = 0x00;
+        else if ((trial & 3) == 1)
+            buf[i] = 0xff;
+        else
+            buf[i] = av_lfg_get(prng) & 0xff;
+    }
+
+    if (trial & 4) {
+        for (i = 0; i + 1 < len; i += 5) {
+            buf[i]     = 0xff;
+            buf[i + 1] = 0xff;
+        }
+    }
+
+    /* jpeg2000dec sets data[length] and data[length+1] to 0xff and zeroes
+     * the four bytes of padding after the block payload. */
+    buf[len]     = 0xff;
+    buf[len + 1] = 0xff;
+    buf[len + 2] = 0x00;
+    buf[len + 3] = 0x00;
+}
+
+/* Exact-length buffers ending in the cblk 0xff 0xff sentinel, decoded until
+ * the read-ahead reaches the tail. */
+static int run_sentinel_trials(AVLFG *prng)
+{
+    static const int lens[] = { 1, 2, 3, 7, 8, 15, 16, 31, 32, 63, 64,
+                                127, 128, 1024, 2048, 4096 };
+    uint8_t buf[4096 + 4];
+    size_t li;
+    int trial, sym, k;
+
+    for (li = 0; li < FF_ARRAY_ELEMS(lens); li++) {
+        int len = lens[li];
+        int trials = len <= 128 ? 8 : 2;
+
+        for (trial = 0; trial < trials; trial++) {
+            MqcState dec, ref;
+
+            fill_sentinel_buffer(buf, len, prng, trial);
+
+            memset(&dec, 0, sizeof(dec));
+            memset(&ref, 0, sizeof(ref));
+            ff_mqc_init_contexts(&dec);
+            ff_mqc_init_contexts(&ref);
+            ff_mqc_initdec(&dec, buf, 0, 1);
+            ff_mqc_initdec_ref(&ref, buf, 0, 1);
+
+            for (sym = 0; sym < 8 * len + 64; sym++) {
+                int cx = av_lfg_get(prng) % 19;
+                int bit = (sym & 1)
+                    ? ff_mqc_decode_inline(&dec, dec.cx_states + cx)
+                    : ff_mqc_decode(&dec, dec.cx_states + cx);
+                int bit_ref = ff_mqc_decode_ref(&ref, ref.cx_states + cx);
+
+                if (bit != bit_ref || dec.a != ref.a ||
+                    (unsigned)(dec.c64 >> 48) != (unsigned)(ref.c >> 16)) {
+                    fprintf(stderr,
+                            "sentinel mismatch (len=%d trial=%d sym=%d cx=%d): 
"
+                            "bit=%d ref_bit=%d a=0x%x ref_a=0x%x "
+                            "c=0x%x ref_c=0x%x\n",
+                            len, trial, sym, cx, bit, bit_ref, dec.a, ref.a,
+                            (unsigned)(dec.c64 >> 48),
+                            (unsigned)(ref.c >> 16));
+                    return 1;
+                }
+
+                for (k = 0; k < 19; k++) {
+                    if (dec.cx_states[k] != ref.cx_states[k]) {
+                        fprintf(stderr,
+                                "sentinel cx_states[%d] mismatch "
+                                "(len=%d trial=%d sym=%d cx=%d): %u != %u\n",
+                                k, len, trial, sym, cx,
+                                dec.cx_states[k], ref.cx_states[k]);
+                        return 1;
+                    }
+                }
+            }
+
+            if (dec.bp > buf + len || ref.bp > buf + len) {
+                fprintf(stderr,
+                        "sentinel overrun (len=%d trial=%d): "
+                        "bp=%d ref_bp=%d\n",
+                        len, trial, (int)(dec.bp - buf),
+                        (int)(ref.bp - buf));
+                return 1;
+            }
+        }
+    }
+
+    return 0;
+}
+
+int main(void)
+{
+    AVLFG prng;
+
+    if (check_packed_table())
+        return 1;
+
+    av_lfg_init(&prng, 1);
+
+    if (run_trials(0, &prng))
+        return 1;
+    if (run_trials(1, &prng))
+        return 1;
+    if (run_sentinel_trials(&prng))
+        return 1;
+
+    return 0;
+}
diff --git a/tests/fate/libavcodec.mak b/tests/fate/libavcodec.mak
index 11b02ae77c4..93dab5a4fa3 100644
--- a/tests/fate/libavcodec.mak
+++ b/tests/fate/libavcodec.mak
@@ -121,6 +121,11 @@ FATE_LIBAVCODEC-$(CONFIG_JPEG2000_ENCODER) += fate-j2k-dwt
 fate-j2k-dwt: libavcodec/tests/jpeg2000dwt$(EXESUF)
 fate-j2k-dwt: CMD = run libavcodec/tests/jpeg2000dwt$(EXESUF)
 
+FATE_LIBAVCODEC-$(CONFIG_JPEG2000_DECODER) += fate-j2k-mqc
+fate-j2k-mqc: libavcodec/tests/mqc$(EXESUF)
+fate-j2k-mqc: CMD = run libavcodec/tests/mqc$(EXESUF)
+fate-j2k-mqc: CMP = null
+
 FATE_LIBAVCODEC-yes += fate-libavcodec-avcodec
 fate-libavcodec-avcodec: libavcodec/tests/avcodec$(EXESUF)
 fate-libavcodec-avcodec: CMD = run libavcodec/tests/avcodec$(EXESUF)
-- 
2.54.1


From 54094e812b22c483a8e3790a02a560159c27497e Mon Sep 17 00:00:00 2001
From: Justin Jacob <[email protected]>
Date: Tue, 24 Nov 2026 00:57:52 +0530
Subject: [PATCH 2/5] avcodec/jpeg2000: pack the tier-1 context tables

Index the zero-coding table by band first, so the band index is loop
invariant, and store a sign context with its XOR bit in one entry so a
sign needs a single load. Add the tables the packed tier-1
representation indexes: the 3x3 window of a stripe column, and the
cardinal-neighbour significance and sign key of a sign context.

Move the encoder's significance update inline into j2kenc.c; the inline
update is encoder-only (the decoder keeps the out-of-line helper until
its packed-column rewrite).

Signed-off-by: Justin Jacob <[email protected]>
---
 libavcodec/j2kenc.c   | 29 ++++++++++++++++++++++---
 libavcodec/jpeg2000.c | 49 +++++++++++++++++++++++++++++++++++++------
 libavcodec/jpeg2000.h | 22 ++++++++++++-------
 3 files changed, 83 insertions(+), 17 deletions(-)

diff --git a/libavcodec/j2kenc.c b/libavcodec/j2kenc.c
index da777580a4a..4e0e1fbde1f 100644
--- a/libavcodec/j2kenc.c
+++ b/libavcodec/j2kenc.c
@@ -543,6 +543,29 @@ static int getnmsedec_ref(int x, int bpno)
     return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
 }
 
+/* Update significance of a coefficient at current position (x,y) and
+ * for neighbors. */
+static av_always_inline
+void set_significance(Jpeg2000T1Context *t1, int x, int y, int negative)
+{
+    uint16_t *p = t1->flags + (y + 1) * t1->stride + x + 1;
+    /* The sign bits of the four edge neighbors are updated together; keeping
+     * the update branchless matters because the sign is close to random. */
+    unsigned sgn = (unsigned)-(negative != 0) &
+                   (JPEG2000_T1_SGN_N | JPEG2000_T1_SGN_S |
+                    JPEG2000_T1_SGN_W | JPEG2000_T1_SGN_E);
+
+    p[0]               |= JPEG2000_T1_SIG;
+    p[1]               |= JPEG2000_T1_SIG_W | (sgn & JPEG2000_T1_SGN_W);
+    p[-1]              |= JPEG2000_T1_SIG_E | (sgn & JPEG2000_T1_SGN_E);
+    p[t1->stride]      |= JPEG2000_T1_SIG_N | (sgn & JPEG2000_T1_SGN_N);
+    p[-t1->stride]     |= JPEG2000_T1_SIG_S | (sgn & JPEG2000_T1_SGN_S);
+    p[t1->stride + 1]  |= JPEG2000_T1_SIG_NW;
+    p[t1->stride - 1]  |= JPEG2000_T1_SIG_NE;
+    p[-t1->stride + 1] |= JPEG2000_T1_SIG_SW;
+    p[-t1->stride - 1] |= JPEG2000_T1_SIG_SE;
+}
+
 static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int 
bandno, int *nmsedec, int bpno)
 {
     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
@@ -558,7 +581,7 @@ static void encode_sigpass(Jpeg2000T1Context *t1, int 
width, int height, int ban
                         int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * 
t1->stride + x+1], &xorbit);
                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, 
(t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
                         *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + 
x], bpno + NMSEDEC_FRACBITS);
-                        ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) 
* t1->stride + x+1] >> 15);
+                        set_significance(t1, x, y, t1->flags[(y+1) * 
t1->stride + x+1] >> 15);
                     }
                     t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
                 }
@@ -610,7 +633,7 @@ static void encode_clnpass(Jpeg2000T1Context *t1, int 
width, int height, int ban
                             int ctxno = 
ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
                             *nmsedec += getnmsedec_sig(t1->data[(y) * 
t1->stride + x], bpno + NMSEDEC_FRACBITS);
                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, 
(t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
-                            ff_jpeg2000_set_significance(t1, x, y, 
t1->flags[(y+1) * t1->stride + x+1] >> 15);
+                            set_significance(t1, x, y, t1->flags[(y+1) * 
t1->stride + x+1] >> 15);
                         }
                     }
                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
@@ -625,7 +648,7 @@ static void encode_clnpass(Jpeg2000T1Context *t1, int 
width, int height, int ban
                             int ctxno = 
ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
                             *nmsedec += getnmsedec_sig(t1->data[(y) * 
t1->stride + x], bpno + NMSEDEC_FRACBITS);
                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, 
(t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
-                            ff_jpeg2000_set_significance(t1, x, y, 
t1->flags[(y+1) * t1->stride + x+1] >> 15);
+                            set_significance(t1, x, y, t1->flags[(y+1) * 
t1->stride + x+1] >> 15);
                         }
                     }
                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
diff --git a/libavcodec/jpeg2000.c b/libavcodec/jpeg2000.c
index a21f9c2a82e..c2379437172 100644
--- a/libavcodec/jpeg2000.c
+++ b/libavcodec/jpeg2000.c
@@ -82,7 +82,11 @@ void ff_tag_tree_zero(Jpeg2000TgtNode *t, int w, int h, int 
val)
     }
 }
 
-uint8_t ff_jpeg2000_sigctxno_lut[256][4];
+uint8_t ff_jpeg2000_sigctxno_lut[4][256];
+/* Zero-coding context of a packed stripe column's 3x3 window, and sign
+ * context and XOR bit of its cardinal-neighbour key. */
+uint8_t ff_jpeg2000_sigctxno_window_lut[4][512];
+uint16_t ff_jpeg2000_sgnctxno_packed_lut[256];
 
 static int getsigctxno(int flag, int bandno)
 {
@@ -127,7 +131,7 @@ static int getsigctxno(int flag, int bandno)
     return 0;
 }
 
-uint8_t ff_jpeg2000_sgnctxno_lut[16][16], ff_jpeg2000_xorbit_lut[16][16];
+uint8_t ff_jpeg2000_sgn_lut[16][16];
 
 static const int contribtab[3][3] = { {  0, -1,  1 }, { -1, -1,  0 }, {  1,  
0,  1 } };
 static const int  ctxlbltab[3][3] = { { 13, 12, 11 }, { 10,  9, 10 }, { 11, 
12, 13 } };
@@ -151,11 +155,43 @@ static void av_cold jpeg2000_init_tier1_luts(void)
     int i, j;
     for (i = 0; i < 256; i++)
         for (j = 0; j < 4; j++)
-            ff_jpeg2000_sigctxno_lut[i][j] = getsigctxno(i, j);
+            ff_jpeg2000_sigctxno_lut[j][i] = getsigctxno(i, j);
     for (i = 0; i < 16; i++)
-        for (j = 0; j < 16; j++)
-            ff_jpeg2000_sgnctxno_lut[i][j] =
-                getsgnctxno(i + (j << 8), &ff_jpeg2000_xorbit_lut[i][j]);
+        for (j = 0; j < 16; j++) {
+            uint8_t xorbit;
+            int ctxno = getsgnctxno(i + (j << 8), &xorbit);
+
+            /* Context and XOR bit in one byte: the decoder needs both and
+             * fetching them together saves a dependent load per sign. */
+            ff_jpeg2000_sgn_lut[i][j] = ctxno | (xorbit << 4);
+        }
+    /* The packed tier-1 representation indexes a 3x3 window whose neighbour
+     * order differs from the flag words; translate once here. */
+    for (i = 0; i < 512; i++) {
+        int flag = (((i >> 1) & 1) << 0) | (((i >> 5) & 1) << 1) |
+                   (((i >> 3) & 1) << 2) | (((i >> 7) & 1) << 3) |
+                   (((i >> 2) & 1) << 4) | (((i >> 0) & 1) << 5) |
+                   (((i >> 8) & 1) << 6) | (((i >> 6) & 1) << 7);
+
+        for (j = 0; j < 4; j++)
+            ff_jpeg2000_sigctxno_window_lut[j][i] =
+                ff_jpeg2000_sigctxno_lut[j][flag];
+    }
+    /* Cardinal neighbours: significance in bits 6/4/2/0, sign in 7/5/3/1. */
+    for (i = 0; i < 256; i++) {
+        int flag = ((i & 0x40) ? JPEG2000_T1_SIG_N : 0) |
+                   ((i & 0x10) ? JPEG2000_T1_SIG_W : 0) |
+                   ((i & 0x04) ? JPEG2000_T1_SIG_E : 0) |
+                   ((i & 0x01) ? JPEG2000_T1_SIG_S : 0) |
+                   ((i & 0x80) ? JPEG2000_T1_SGN_N : 0) |
+                   ((i & 0x20) ? JPEG2000_T1_SGN_W : 0) |
+                   ((i & 0x08) ? JPEG2000_T1_SGN_E : 0) |
+                   ((i & 0x02) ? JPEG2000_T1_SGN_S : 0);
+        uint8_t xorbit;
+        int ctxno = getsgnctxno(flag, &xorbit);
+
+        ff_jpeg2000_sgnctxno_packed_lut[i] = ctxno | (xorbit << 8);
+    }
 }
 
 void av_cold ff_jpeg2000_init_tier1_luts(void)
@@ -187,6 +223,7 @@ void ff_jpeg2000_set_significance(Jpeg2000T1Context *t1, 
int x, int y,
     t1->flags[(y - 1) * t1->stride + x - 1] |= JPEG2000_T1_SIG_SE;
 }
 
+
 /* TODO: Implementation of quantization step not finished, see
  * ISO/IEC 15444-1:2002 E.1 and A.6.4. */
 // static const uint8_t lut_gain[2][4] = { { 0, 0, 0, 0 }, { 0, 1, 1, 2 } }; 
(unused)
diff --git a/libavcodec/jpeg2000.h b/libavcodec/jpeg2000.h
index 52c00f4268a..0b2154961cc 100644
--- a/libavcodec/jpeg2000.h
+++ b/libavcodec/jpeg2000.h
@@ -133,7 +133,10 @@ enum Jpeg2000Quantsty { // quantization style
 
 typedef struct Jpeg2000T1Context {
     int data[6144];
-    uint16_t flags[6156];
+    union {
+        uint16_t flags[6156];   ///< a word per coefficient; the encoder
+        uint32_t flags32[3078]; ///< a word per stripe column; the decoder
+    };
     MqcState mqc;
     int stride;
 } Jpeg2000T1Context;
@@ -264,13 +267,15 @@ void ff_jpeg2000_init_tier1_luts(void);
 void ff_jpeg2000_set_significance(Jpeg2000T1Context *t1,
                                   int x, int y, int negative);
 
-extern uint8_t ff_jpeg2000_sigctxno_lut[256][4];
+extern uint8_t ff_jpeg2000_sigctxno_lut[4][256];
+extern uint8_t ff_jpeg2000_sigctxno_window_lut[4][512];
+extern uint16_t ff_jpeg2000_sgnctxno_packed_lut[256];
 
 /* Get context label (number in range[0..8]) of a coefficient for significance
  * propagation and cleanup coding passes. */
 static inline int ff_jpeg2000_getsigctxno(int flag, int bandno)
 {
-    return ff_jpeg2000_sigctxno_lut[flag & 255][bandno];
+    return ff_jpeg2000_sigctxno_lut[bandno][flag & 255];
 }
 
 static const uint8_t refctxno_lut[2][2] = { { 14, 15 }, { 16, 16 } };
@@ -282,14 +287,15 @@ static inline int ff_jpeg2000_getrefctxno(int flag)
     return refctxno_lut[(flag >> 14) & 1][(flag & 255) != 0];
 }
 
-extern uint8_t ff_jpeg2000_sgnctxno_lut[16][16];
-extern uint8_t ff_jpeg2000_xorbit_lut[16][16];
+extern uint8_t ff_jpeg2000_sgn_lut[16][16];
 
-/* Get context label (number in range[9..13]) for sign decoding. */
+/* Context label (9..13) in the low nibble, XOR bit in bit 4. */
 static inline int ff_jpeg2000_getsgnctxno(int flag, int *xorbit)
 {
-    *xorbit = ff_jpeg2000_xorbit_lut[flag & 15][(flag >> 8) & 15];
-    return ff_jpeg2000_sgnctxno_lut[flag & 15][(flag >> 8) & 15];
+    int s = ff_jpeg2000_sgn_lut[flag & 15][(flag >> 8) & 15];
+
+    *xorbit = s >> 4;
+    return s & 15;
 }
 
 /* Node count of the tag-tree pyramid over a (w, h) leaf grid. */
-- 
2.54.1


From ae9de0680a01b3e389328b6a3cca2460862bc510 Mon Sep 17 00:00:00 2001
From: Justin Jacob <[email protected]>
Date: Tue, 24 Nov 2026 00:57:52 +0530
Subject: [PATCH 3/5] avcodec/jpeg2000dec: decode tier-1 over packed flag
 columns

Replace the per-coefficient flag words with one 32-bit word per
four-row stripe column: the 3x6 significance neighbourhood in bits
0-17, then the per-row sign, refinement and visited marks and the two
stripe-edge signs. A new significant coefficient updates three words
instead of nine, and a context is a shift, a mask and one table load.
The visited marks also let the significance and refinement passes skip
whole columns without reading them.

The cleanup pass skips a run of all-zero columns by subtracting the
renormalizations the arithmetic decoder would have performed: while the
run-length context's MPS is zero, each of those columns decodes one
zero and only A changes.

Pass the arithmetic state in from the caller so it stays in registers
across the passes. Drop the now-unused shared
ff_jpeg2000_set_significance() helper.

Measured on a 240-frame 4096x1714 XYZ 12-bit 9/7 corpus (Apple M1 Pro,
8 threads). In a four-round rotating chain, the median of the four
per-round ratios is 1.056x real and 1.058x CPU; the per-metric minima
are 17.87 s -> 16.94 s real (1.055x) and 137.14 s -> 130.47 s CPU
(1.051x).

Signed-off-by: Justin Jacob <[email protected]>
---
 libavcodec/jpeg2000.c    |  23 --
 libavcodec/jpeg2000.h    |   5 -
 libavcodec/jpeg2000dec.c | 504 ++++++++++++++++++++++++++++++---------
 3 files changed, 388 insertions(+), 144 deletions(-)

diff --git a/libavcodec/jpeg2000.c b/libavcodec/jpeg2000.c
index c2379437172..0f33b1efaee 100644
--- a/libavcodec/jpeg2000.c
+++ b/libavcodec/jpeg2000.c
@@ -200,29 +200,6 @@ void av_cold ff_jpeg2000_init_tier1_luts(void)
     ff_thread_once(&init_static_once, jpeg2000_init_tier1_luts);
 }
 
-void ff_jpeg2000_set_significance(Jpeg2000T1Context *t1, int x, int y,
-                                  int negative)
-{
-    x++;
-    y++;
-    t1->flags[(y) * t1->stride + x] |= JPEG2000_T1_SIG;
-    if (negative) {
-        t1->flags[(y) * t1->stride + x + 1] |= JPEG2000_T1_SIG_W | 
JPEG2000_T1_SGN_W;
-        t1->flags[(y) * t1->stride + x - 1] |= JPEG2000_T1_SIG_E | 
JPEG2000_T1_SGN_E;
-        t1->flags[(y + 1) * t1->stride + x] |= JPEG2000_T1_SIG_N | 
JPEG2000_T1_SGN_N;
-        t1->flags[(y - 1) * t1->stride + x] |= JPEG2000_T1_SIG_S | 
JPEG2000_T1_SGN_S;
-    } else {
-        t1->flags[(y) * t1->stride + x + 1] |= JPEG2000_T1_SIG_W;
-        t1->flags[(y) * t1->stride + x - 1] |= JPEG2000_T1_SIG_E;
-        t1->flags[(y + 1) * t1->stride + x] |= JPEG2000_T1_SIG_N;
-        t1->flags[(y - 1) * t1->stride + x] |= JPEG2000_T1_SIG_S;
-    }
-    t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_SIG_NW;
-    t1->flags[(y + 1) * t1->stride + x - 1] |= JPEG2000_T1_SIG_NE;
-    t1->flags[(y - 1) * t1->stride + x + 1] |= JPEG2000_T1_SIG_SW;
-    t1->flags[(y - 1) * t1->stride + x - 1] |= JPEG2000_T1_SIG_SE;
-}
-
 
 /* TODO: Implementation of quantization step not finished, see
  * ISO/IEC 15444-1:2002 E.1 and A.6.4. */
diff --git a/libavcodec/jpeg2000.h b/libavcodec/jpeg2000.h
index 0b2154961cc..f4dd3dad68e 100644
--- a/libavcodec/jpeg2000.h
+++ b/libavcodec/jpeg2000.h
@@ -262,11 +262,6 @@ static inline int ff_jpeg2000_ceildiv(int a, int64_t b)
 /* Set up lookup tables used in TIER-1. */
 void ff_jpeg2000_init_tier1_luts(void);
 
-/* Update significance of a coefficient at current position (x,y) and
- * for neighbors. */
-void ff_jpeg2000_set_significance(Jpeg2000T1Context *t1,
-                                  int x, int y, int negative);
-
 extern uint8_t ff_jpeg2000_sigctxno_lut[4][256];
 extern uint8_t ff_jpeg2000_sigctxno_window_lut[4][512];
 extern uint16_t ff_jpeg2000_sgnctxno_packed_lut[256];
diff --git a/libavcodec/jpeg2000dec.c b/libavcodec/jpeg2000dec.c
index a235edcec3a..c5ce9848514 100644
--- a/libavcodec/jpeg2000dec.c
+++ b/libavcodec/jpeg2000dec.c
@@ -32,6 +32,7 @@
 #include "libavutil/avassert.h"
 #include "libavutil/common.h"
 #include "libavutil/imgutils.h"
+#include "libavutil/intmath.h"
 #include "libavutil/mem.h"
 #include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
@@ -1894,127 +1895,393 @@ static int 
jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile
 }
 
 /* TIER-1 routines */
-static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
+/* Tier-1 passes over packed stripe-column flags.
+ *
+ * One 32-bit word describes a four-row column of the codeblock. Bits 0-17
+ * hold the significances of the 3x6 neighbourhood: bit 3*(row + 1) + (col + 1)
+ * is the significance of neighbour (row, col), row -1 being the last row of
+ * the stripe above and row 4 the first row of the stripe below. Bits 18-31
+ * hold the signs and the per-row marks: bit 18 the sign of the row above the
+ * stripe, bits 19 + 3*row, 20 + 3*row and 21 + 3*row the sign, refinement
+ * mark and visited mark of row `row`, and bit 31 the sign of the row below
+ * the stripe.
+ *
+ * Shifting a word right by 3*row aligns that row's 3x3 window on bits 0-8,
+ * so each context is a shift, a mask and one table load, and a coefficient
+ * that becomes significant updates three words instead of nine.
+ */
+
+#define J2K_T1_SIGMA_THIS       (1u << 4)
+#define J2K_T1_SIGMA_NEIGHBOURS 0x1EFu
+#define J2K_T1_MU_THIS          (1u << 20)
+#define J2K_T1_PI_THIS          (1u << 21)
+#define J2K_T1_PI_ALL           (J2K_T1_PI_THIS | (J2K_T1_PI_THIS << 3) | \
+                                 (J2K_T1_PI_THIS << 6) | (J2K_T1_PI_THIS << 9))
+#define J2K_T1_ROW_BITS         0x249u
+/* The row below the stripe, which a vertically causal context ignores. */
+#define J2K_T1_VSC_NEIGHBOURS   0x38000u
+#define J2K_T1_VSC_MASK         (~(J2K_T1_VSC_NEIGHBOURS | 0x80000000u))
+
+static av_always_inline uint32_t j2k_t1_uncoded_rows(uint32_t own)
+{
+    return ~((own >> 4) | (own >> 21)) & J2K_T1_ROW_BITS;
+}
+
+/* Rows that have a significant neighbour and were not visited yet. Bit 3*row
+ * marks row `row`; the neighbourhood terms are the west/centre/east of the
+ * row itself and of the row two below, plus the west/east of the row below,
+ * which is the eight neighbours without the centre. */
+static av_always_inline uint32_t j2k_t1_propagation_rows(uint32_t own)
+{
+    uint32_t any_in_row = own | (own >> 1) | (own >> 2);
+    uint32_t neighbours = any_in_row | (any_in_row >> 6) |
+                          (own >> 3) | (own >> 5);
+
+    return neighbours & j2k_t1_uncoded_rows(own);
+}
+
+/* Record that the coefficient in row `shift / 3` of the column word at
+ * `index` became significant with `sign`. Setting the row's own bit also
+ * gives the row above its south neighbour and the row below its north
+ * neighbour, so only the two adjacent columns and a stripe edge need
+ * separate writes. */
+static av_always_inline void j2k_t1_set_significant(uint32_t *flags,
+                                                    uint32_t *own, int index,
+                                                    int stride, unsigned shift,
+                                                    unsigned sign)
+{
+    *own |= (J2K_T1_SIGMA_THIS | (sign << 19)) << shift;
+    flags[index - 1] |= (1u << 5) << shift;
+    flags[index + 1] |= (1u << 3) << shift;
+
+    if (!shift) {
+        int north = index - stride;
+
+        flags[north - 1] |= 1u << 17;
+        flags[north]     |= (1u << 16) | (sign << 31);
+        flags[north + 1] |= 1u << 15;
+    } else if (shift == 9) {
+        int south = index + stride;
+
+        flags[south - 1] |= 1u << 2;
+        flags[south]     |= (1u << 1) | (sign << 18);
+        flags[south + 1] |= 1u;
+    }
+}
+
+/* Sign context (9-13) in the low byte and the XOR bit above it, keyed by the
+ * cardinal neighbours' significances and signs. */
+static av_always_inline unsigned j2k_t1_sign_context(uint32_t own,
+                                                     uint32_t left,
+                                                     uint32_t right,
+                                                     unsigned shift, int vsc)
+{
+    uint32_t window = own, sgn_own = own;
+    unsigned significances, signs;
+
+    if (vsc && shift == 9) {
+        window  &= ~J2K_T1_VSC_NEIGHBOURS;
+        sgn_own &= J2K_T1_VSC_MASK;
+    }
+    /* Align the row's window on bits 0-8; the sign offsets below already
+     * carry `shift` because the signs live in the unshifted word. */
+    window >>= shift;
+    significances = (((window >> 1) & 1) << 6) |
+                    (((window >> 3) & 1) << 4) |
+                    (((window >> 5) & 1) << 2) | ((window >> 7) & 1);
+    /* Significances in bits 6/4/2/0 (N/W/E/S) and signs in 7/5/3/1, the key
+     * layout of the packed sign-context table; the north sign of a stripe's
+     * first row and the south sign of its last row are the stripe-edge bits. 
*/
+    signs = (((sgn_own >> (shift ? 16 + shift : 18)) & 1) << 7) |
+            (((left    >> (19 + shift)) & 1) << 5) |
+            (((right   >> (19 + shift)) & 1) << 3) |
+            (((sgn_own >> (22 + shift)) & 1) << 1);
+
+    return ff_jpeg2000_sgnctxno_packed_lut[significances | signs];
+}
+
+static av_always_inline unsigned j2k_t1_zero_context(const uint8_t *lut,
+                                                     uint32_t own,
+                                                     unsigned shift, int vsc)
+{
+    if (vsc && shift == 9)
+        own &= ~J2K_T1_VSC_NEIGHBOURS;
+
+    return lut[(own >> shift) & J2K_T1_SIGMA_NEIGHBOURS];
+}
+
+static av_always_inline void decode_sigpass_core(Jpeg2000T1Context *t1,
+                                                 MqcState *mqc, int width,
+                                                 int height, int bpno,
+                                                 int bandno, int vsc)
+{
+    uint32_t *const flags = t1->flags32;
+    const int stride = t1->stride;
+    const unsigned mask = (3u << bpno) >> 1;
+    const uint32_t vsc_mask = vsc ? J2K_T1_VSC_MASK : ~0u;
+    const uint8_t *const ctxlut = ff_jpeg2000_sigctxno_window_lut[bandno];
+    int y0, x;
+
+    for (y0 = 0; y0 < height; y0 += 4) {
+        const int rows = FFMIN(height - y0, 4);
+        const uint32_t rows_mask = J2K_T1_ROW_BITS &
+                                   ((1u << (3 * rows)) - 1);
+        const int flag_base = ((y0 >> 2) + 1) * stride + 1;
+        int *const data = t1->data + y0 * stride;
+
+        for (x = 0; x < width; x++) {
+            const int fi = flag_base + x;
+            uint32_t own = flags[fi];
+            uint32_t candidates = j2k_t1_propagation_rows(own & vsc_mask) &
+                                  rows_mask;
+
+            if (!candidates)
+                continue;
+
+            do {
+                const unsigned shift = ff_ctz(candidates);
+                const unsigned ctxno = j2k_t1_zero_context(ctxlut, own,
+                                                           shift, vsc);
+
+                own |= J2K_T1_PI_THIS << shift;
+                if (ff_mqc_decode_inline(mqc, mqc->cx_states + ctxno)) {
+                    const unsigned sc = j2k_t1_sign_context(own,
+                                                            flags[fi - 1],
+                                                            flags[fi + 1],
+                                                            shift, vsc);
+                    unsigned sign = ff_mqc_decode_inline(mqc, mqc->cx_states +
+                                                         (sc & 0xff));
+
+                    if (!mqc->raw)
+                        sign ^= sc >> 8;
+                    data[(shift / 3) * stride + x] |= (sign << 31) | mask;
+                    j2k_t1_set_significant(flags, &own, fi, stride, shift,
+                                           sign);
+                    /* The new coefficient is a neighbour of the rows below. */
+                    candidates = j2k_t1_propagation_rows(own & vsc_mask) &
+                                 rows_mask & (~0u << (shift + 1));
+                } else {
+                    candidates &= candidates - 1;
+                }
+            } while (candidates);
+
+            flags[fi] = own;
+        }
+    }
+}
+
+static void decode_sigpass(Jpeg2000T1Context *t1, MqcState *mqc,
+                           int width, int height,
                            int bpno, int bandno,
                            int vert_causal_ctx_csty_symbol)
 {
-    int mask = (3u << bpno)>>1, y0, x, y;
-
-    for (y0 = 0; y0 < height; y0 += 4)
-        for (x = 0; x < width; x++)
-            for (y = y0; y < height && y < y0 + 4; y++) {
-                int flags_mask = -1;
-                if (vert_causal_ctx_csty_symbol && y == y0 + 3)
-                    flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | 
JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
-                if ((t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB 
& flags_mask)
-                && !(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | 
JPEG2000_T1_VIS))) {
-                    if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + 
ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, 
bandno))) {
-                        int xorbit, ctxno = 
ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, 
&xorbit);
-                        if (t1->mqc.raw) {
-                            t1->data[(y) * t1->stride + x] |= 
(uint32_t)(ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno)) << 31;
-                            t1->data[(y) * t1->stride + x] |= mask;
-                        } else {
-                            t1->data[(y) * t1->stride + x] |= 
(uint32_t)(ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) << 31;
-                            t1->data[(y) * t1->stride + x] |= mask;
-                        }
-                        ff_jpeg2000_set_significance(t1, x, y,
-                                                     t1->data[(y) * t1->stride 
+ x] & INT32_MIN);
-                    }
-                    t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_VIS;
-                }
-            }
+    if (vert_causal_ctx_csty_symbol)
+        decode_sigpass_core(t1, mqc, width, height, bpno, bandno, 1);
+    else
+        decode_sigpass_core(t1, mqc, width, height, bpno, bandno, 0);
 }
 
-static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
-                           int bpno, int vert_causal_ctx_csty_symbol)
+static av_always_inline void decode_refpass_core(Jpeg2000T1Context *t1,
+                                                 MqcState *mqc, int width,
+                                                 int height, int bpno,
+                                                 int vsc)
 {
-    int phalf;
-    int y0, x, y;
-
-    phalf = 1 << bpno;
-
-    for (y0 = 0; y0 < height; y0 += 4)
-        for (x = 0; x < width; x++)
-            for (y = y0; y < height && y < y0 + 4; y++)
-                if ((t1->flags[(y + 1) * t1->stride + x + 1] & 
(JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
-                    int flags_mask = (vert_causal_ctx_csty_symbol && y == y0 + 
3) ?
-                        ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | 
JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S) : -1;
-                    int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y + 1) * 
t1->stride + x + 1] & flags_mask);
-                    t1->data[(y) * t1->stride + x] |= phalf >> 1;
-                    if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno))
-                        t1->data[(y) * t1->stride + x] |= phalf;
-                    else {
-                        t1->data[(y) * t1->stride + x] &= ~(phalf);
-
-                    }
-                    t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_REF;
-                }
-}
-
-static void decode_clnpass(const Jpeg2000DecoderContext *s, Jpeg2000T1Context 
*t1,
-                           int width, int height, int bpno, int bandno,
-                           int seg_symbols, int vert_causal_ctx_csty_symbol)
-{
-    int mask = (3u << bpno)>>1, y0, x, y, runlen, dec;
+    uint32_t *const flags = t1->flags32;
+    const int stride = t1->stride;
+    const int phalf = 1 << bpno;
+    const uint32_t vsc_mask = vsc ? J2K_T1_VSC_MASK : ~0u;
+    int y0, x;
 
     for (y0 = 0; y0 < height; y0 += 4) {
-        for (x = 0; x < width; x++) {
-            int flags_mask = -1;
-            if (vert_causal_ctx_csty_symbol)
-                flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | 
JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
-            if (y0 + 3 < height &&
-                !((t1->flags[(y0 + 1) * t1->stride + x + 1] & 
(JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
-                  (t1->flags[(y0 + 2) * t1->stride + x + 1] & 
(JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
-                  (t1->flags[(y0 + 3) * t1->stride + x + 1] & 
(JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
-                  (t1->flags[(y0 + 4) * t1->stride + x + 1] & 
(JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG) & flags_mask))) {
-                if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
-                    continue;
-                runlen = ff_mqc_decode(&t1->mqc,
-                                       t1->mqc.cx_states + MQC_CX_UNI);
-                runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
-                                                       t1->mqc.cx_states +
-                                                       MQC_CX_UNI);
-                dec = 1;
-            } else {
-                runlen = 0;
-                dec    = 0;
-            }
+        const int rows = FFMIN(height - y0, 4);
+        const uint32_t rows_mask = J2K_T1_ROW_BITS &
+                                   ((1u << (3 * rows)) - 1);
+        const int flag_base = ((y0 >> 2) + 1) * stride + 1;
+        int *const data = t1->data + y0 * stride;
 
-            for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
-                int flags_mask = -1;
-                if (vert_causal_ctx_csty_symbol && y == y0 + 3)
-                    flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | 
JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
-                if (!dec) {
-                    if (!(t1->flags[(y+1) * t1->stride + x+1] & 
(JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
-                        dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + 
ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask,
-                                                                               
              bandno));
-                    }
-                }
-                if (dec) {
-                    int xorbit;
-                    int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y + 1) * 
t1->stride + x + 1] & flags_mask,
-                                                        &xorbit);
-                    t1->data[(y) * t1->stride + x] |= 
(uint32_t)(ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) << 31;
-                    t1->data[(y) * t1->stride + x] |= mask;
-                    ff_jpeg2000_set_significance(t1, x, y, t1->data[(y) * 
t1->stride + x] & INT32_MIN);
-                }
-                dec = 0;
-                t1->flags[(y + 1) * t1->stride + x + 1] &= ~JPEG2000_T1_VIS;
-            }
+        for (x = 0; x < width; x++) {
+            const int fi = flag_base + x;
+            uint32_t own = flags[fi];
+            /* Significant before this bitplane's significance pass. */
+            uint32_t candidates = (own >> 4) & ~(own >> 21) & rows_mask;
+
+            if (!candidates)
+                continue;
+
+            do {
+                const unsigned shift = ff_ctz(candidates);
+                const uint32_t window = (own & vsc_mask) >> shift;
+                const unsigned ctxno = (window & J2K_T1_MU_THIS) ? 16 :
+                                       (window & J2K_T1_SIGMA_NEIGHBOURS) ?
+                                       15 : 14;
+                int *const coeff = &data[(shift / 3) * stride + x];
+
+                *coeff |= phalf >> 1;
+                if (ff_mqc_decode_inline(mqc, mqc->cx_states + ctxno))
+                    *coeff |= phalf;
+                else
+                    *coeff &= ~phalf;
+                own |= J2K_T1_MU_THIS << shift;
+                candidates &= candidates - 1;
+            } while (candidates);
+
+            flags[fi] = own;
         }
     }
+}
+
+static void decode_refpass(Jpeg2000T1Context *t1, MqcState *mqc,
+                           int width, int height,
+                           int bpno, int vert_causal_ctx_csty_symbol)
+{
+    if (vert_causal_ctx_csty_symbol)
+        decode_refpass_core(t1, mqc, width, height, bpno, 1);
+    else
+        decode_refpass_core(t1, mqc, width, height, bpno, 0);
+}
+
+static av_always_inline void
+decode_clnpass_core(const Jpeg2000DecoderContext *s,
+                    Jpeg2000T1Context *t1, MqcState *mqc,
+                    int width, int height, int bpno, int bandno,
+                    int seg_symbols, int vsc)
+{
+    uint32_t *const flags = t1->flags32;
+    const int stride = t1->stride;
+    const unsigned mask = (3u << bpno) >> 1;
+    const uint32_t vsc_mask = vsc ? J2K_T1_VSC_MASK : ~0u;
+    const uint8_t *const ctxlut = ff_jpeg2000_sigctxno_window_lut[bandno];
+    int y0, x;
+
+    for (y0 = 0; y0 < height; y0 += 4) {
+        const int rows = FFMIN(height - y0, 4);
+        const uint32_t rows_mask = J2K_T1_ROW_BITS &
+                                   ((1u << (3 * rows)) - 1);
+        const int flag_base = ((y0 >> 2) + 1) * stride + 1;
+        int *const data = t1->data + y0 * stride;
+
+        for (x = 0; x < width; ) {
+            const int fi = flag_base + x;
+            uint32_t own = flags[fi];
+            uint32_t candidates;
+
+            /* A zero word is a full column of insignificant, unvisited
+             * coefficients with zero contexts: the run-length case. */
+            if (rows_mask == J2K_T1_ROW_BITS && !(own & vsc_mask)) {
+                uint32_t run = 0, qe = 0;
+
+                if (!mqc->raw && !(mqc->cx_states[MQC_CX_RL] & 1)) {
+                    uint32_t renorm_floor =
+                        FFMAX((uint32_t)(mqc->c64 >> 48) + 1, 0x8000);
+
+                    qe  = ff_mqc_packed[mqc->cx_states[MQC_CX_RL]] & 0xffff;
+                    run = mqc->a > renorm_floor ?
+                          (mqc->a - renorm_floor) / qe : 0;
+                }
+                /* While the run-length context's MPS is a zero and it
+                 * decodes without renormalizing, every zero word decodes
+                 * that zero and changes nothing but A. */
+                if (run) {
+                    unsigned limit = FFMIN(run, (uint32_t)(width - x));
+                    unsigned cols  = 1;
+
+                    while (cols < limit && !(flags[fi + cols] & vsc_mask))
+                        cols++;
+                    mqc->a -= cols * qe;
+                    x += cols;
+                    continue;
+                }
+                if (!ff_mqc_decode_inline(mqc, mqc->cx_states + MQC_CX_RL)) {
+                    x++;
+                    continue;
+                }
+                {
+                    unsigned first = ff_mqc_decode_inline(mqc,
+                                                          mqc->cx_states +
+                                                          MQC_CX_UNI);
+                    unsigned shift, sc, sign;
+                    int row;
+
+                    first = (first << 1) |
+                            ff_mqc_decode_inline(mqc, mqc->cx_states +
+                                                 MQC_CX_UNI);
+                    shift = 3 * first;
+                    sc    = j2k_t1_sign_context(own, flags[fi - 1],
+                                                flags[fi + 1], shift, vsc);
+                    sign  = ff_mqc_decode_inline(mqc, mqc->cx_states +
+                                                 (sc & 0xff)) ^ (sc >> 8);
+                    data[first * stride + x] |= (sign << 31) | mask;
+                    j2k_t1_set_significant(flags, &own, fi, stride, shift,
+                                           sign);
+                    for (row = first + 1; row < 4; row++) {
+                        shift = 3 * row;
+                        if (!ff_mqc_decode_inline(mqc, mqc->cx_states +
+                                                  j2k_t1_zero_context(ctxlut,
+                                                                      own,
+                                                                      shift,
+                                                                      vsc)))
+                            continue;
+                        sc   = j2k_t1_sign_context(own, flags[fi - 1],
+                                                   flags[fi + 1], shift, vsc);
+                        sign = ff_mqc_decode_inline(mqc, mqc->cx_states +
+                                                    (sc & 0xff)) ^ (sc >> 8);
+                        data[row * stride + x] |= (sign << 31) | mask;
+                        j2k_t1_set_significant(flags, &own, fi, stride, shift,
+                                               sign);
+                    }
+                }
+            } else {
+                candidates = j2k_t1_uncoded_rows(own) & rows_mask;
+                while (candidates) {
+                    const unsigned shift = ff_ctz(candidates);
+                    const unsigned ctxno = j2k_t1_zero_context(ctxlut, own,
+                                                               shift, vsc);
+
+                    if (ff_mqc_decode_inline(mqc, mqc->cx_states + ctxno)) {
+                        const unsigned sc =
+                            j2k_t1_sign_context(own, flags[fi - 1],
+                                                flags[fi + 1], shift, vsc);
+                        const unsigned sign =
+                            ff_mqc_decode_inline(mqc, mqc->cx_states +
+                                                 (sc & 0xff)) ^ (sc >> 8);
+
+                        data[(shift / 3) * stride + x] |= (sign << 31) | mask;
+                        j2k_t1_set_significant(flags, &own, fi, stride, shift,
+                                               sign);
+                    }
+                    candidates &= candidates - 1;
+                }
+            }
+            flags[fi] = own & ~J2K_T1_PI_ALL;
+            x++;
+        }
+    }
+
     if (seg_symbols) {
-        int val;
-        val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
-        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + 
MQC_CX_UNI);
-        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + 
MQC_CX_UNI);
-        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + 
MQC_CX_UNI);
+        int val = 0, i;
+
+        for (i = 0; i < 4; i++)
+            val = (val << 1) | ff_mqc_decode_inline(mqc, mqc->cx_states +
+                                                    MQC_CX_UNI);
         if (val != 0xa)
             av_log(s->avctx, AV_LOG_ERROR,
                    "Segmentation symbol value incorrect\n");
     }
 }
 
+static void decode_clnpass(const Jpeg2000DecoderContext *s,
+                           Jpeg2000T1Context *t1, MqcState *mqc,
+                           int width, int height, int bpno, int bandno,
+                           int seg_symbols, int vert_causal_ctx_csty_symbol)
+{
+    if (vert_causal_ctx_csty_symbol)
+        decode_clnpass_core(s, t1, mqc, width, height, bpno, bandno,
+                            seg_symbols, 1);
+    else
+        decode_clnpass_core(s, t1, mqc, width, height, bpno, bandno,
+                            seg_symbols, 0);
+}
+
 static int decode_cblk(const Jpeg2000DecoderContext *s, Jpeg2000CodingStyle 
*codsty,
                        Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
                        int width, int height, int bandpos, uint8_t roi_shift, 
const int M_b)
@@ -2024,6 +2291,7 @@ static int decode_cblk(const Jpeg2000DecoderContext *s, 
Jpeg2000CodingStyle *cod
     int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
     int term_cnt = 0;
     int coder_type;
+    MqcState mqc;
 
     av_assert0(width <= 1024U && height <= 1024U);
     av_assert0(width*height <= 4096);
@@ -2034,11 +2302,12 @@ static int decode_cblk(const Jpeg2000DecoderContext *s, 
Jpeg2000CodingStyle *cod
     if (!cblk->length || !cblk->nonzerobits)
         return 0;
 
-    memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
+    memset(t1->flags32, 0,
+           t1->stride * ((height + 3) / 4 + 2) * sizeof(*t1->flags32));
 
     cblk->data[cblk->length] = 0xff;
     cblk->data[cblk->length+1] = 0xff;
-    ff_mqc_initdec(&t1->mqc, cblk->data, 0, 1);
+    ff_mqc_initdec(&mqc, cblk->data, 0, 1);
 
     while (passno--) {
         if (bpno < -1 || bpno > 29) {
@@ -2047,34 +2316,37 @@ static int decode_cblk(const Jpeg2000DecoderContext *s, 
Jpeg2000CodingStyle *cod
         }
         switch(pass_t) {
         case 0:
-            decode_sigpass(t1, width, height, bpno + 1, bandpos,
+            decode_sigpass(t1, &mqc, width, height, bpno + 1, bandpos,
                            vert_causal_ctx_csty_symbol);
             break;
         case 1:
-            decode_refpass(t1, width, height, bpno + 1, 
vert_causal_ctx_csty_symbol);
+            decode_refpass(t1, &mqc, width, height, bpno + 1,
+                           vert_causal_ctx_csty_symbol);
             break;
         case 2:
-            av_assert2(!t1->mqc.raw);
-            decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
+            av_assert2(!mqc.raw);
+            decode_clnpass(s, t1, &mqc, width, height, bpno + 1, bandpos,
                            codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
                            vert_causal_ctx_csty_symbol);
             break;
         }
         if (codsty->cblk_style & JPEG2000_CBLK_RESET) // XXX no testcase for 
just this
-            ff_mqc_init_contexts(&t1->mqc);
+            ff_mqc_init_contexts(&mqc);
 
         if (passno && (coder_type = needs_termination(codsty->cblk_style, 
pass_cnt))) {
             if (term_cnt >= cblk->nb_terminations) {
                 av_log(s->avctx, AV_LOG_ERROR, "Missing needed termination 
\n");
                 return AVERROR_INVALIDDATA;
             }
-            if (FFABS(cblk->data + cblk->data_start[term_cnt + 1] - 2 - 
t1->mqc.bp) > 0) {
+            if (FFABS(cblk->data + cblk->data_start[term_cnt + 1] - 2 -
+                      mqc.bp) > 0) {
                 av_log(s->avctx, AV_LOG_WARNING, "Mid mismatch %td in pass %d 
of %d\n",
-                    cblk->data + cblk->data_start[term_cnt + 1] - 2 - 
t1->mqc.bp,
+                    cblk->data + cblk->data_start[term_cnt + 1] - 2 - mqc.bp,
                     pass_cnt, cblk->npasses);
             }
 
-            ff_mqc_initdec(&t1->mqc, cblk->data + 
cblk->data_start[++term_cnt], coder_type == 2, 0);
+            ff_mqc_initdec(&mqc, cblk->data + cblk->data_start[++term_cnt],
+                           coder_type == 2, 0);
         }
 
         pass_t++;
@@ -2085,12 +2357,12 @@ static int decode_cblk(const Jpeg2000DecoderContext *s, 
Jpeg2000CodingStyle *cod
         pass_cnt ++;
     }
 
-    if (cblk->data + cblk->length - 2 > t1->mqc.bp) {
+    if (cblk->data + cblk->length - 2 > mqc.bp) {
         av_log(s->avctx, AV_LOG_WARNING, "End mismatch %td\n",
-               cblk->data + cblk->length - 2 - t1->mqc.bp);
+               cblk->data + cblk->length - 2 - mqc.bp);
     }
 
-    if (cblk->data + cblk->length < t1->mqc.bp) {
+    if (cblk->data + cblk->length < mqc.bp) {
         av_log(s->avctx, AV_LOG_WARNING, "Synthetic End of Stream Marker 
Read.\n");
     }
 
-- 
2.54.1


From d91649a9803a09c621b48bc57a2c98bb867a9336 Mon Sep 17 00:00:00 2001
From: Justin Jacob <[email protected]>
Date: Tue, 24 Nov 2026 00:58:54 +0530
Subject: [PATCH 4/5] avcodec/jpeg2000dec: skip the sample rewrite without ROI

Without an ROI shift the reconstruction loop masks the sign off and
writes it back unchanged. Return before the loop in that case.

Signed-off-by: Justin Jacob <[email protected]>
---
 libavcodec/jpeg2000dec.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/libavcodec/jpeg2000dec.c b/libavcodec/jpeg2000dec.c
index c5ce9848514..69e6b400d26 100644
--- a/libavcodec/jpeg2000dec.c
+++ b/libavcodec/jpeg2000dec.c
@@ -2366,20 +2366,28 @@ static int decode_cblk(const Jpeg2000DecoderContext *s, 
Jpeg2000CodingStyle *cod
         av_log(s->avctx, AV_LOG_WARNING, "Synthetic End of Stream Marker 
Read.\n");
     }
 
+    /* Without ROI the pass below rewrites every coefficient with its own
+     * value; the samples are already in the form the DWT expects. */
+    if (!roi_shift)
+        return 1;
+
     /* Reconstruct the sample values */
+    /* Bit mask for ROI detection */
+    const uint32_t mask = (int64_t)UINT32_MAX >> (M_b + 1);
+
     for (int y = 0; y < height; y++) {
         for (int x = 0; x < width; x++) {
             int32_t sign, n, val;
-            const uint32_t mask  = (int64_t)UINT32_MAX >> (M_b + 1); // bit 
mask for ROI detection
 
             n = x + (y * t1->stride);
             val = t1->data[n];
             sign = val & INT32_MIN;
             val &= INT32_MAX;
             /* ROI shift, if necessary */
-            if (roi_shift && (((uint32_t)val & ~mask) == 0))
+            if (((uint32_t)val & ~mask) == 0)
                 val = (uint32_t)val << roi_shift;
-            t1->data[n] = val | sign; /* NOTE: Binary point for reconstruction 
value is located in 31 - M_b */
+            /* NOTE: binary point of the reconstruction value is at 31 - M_b */
+            t1->data[n] = val | sign;
         }
     }
     return 1;
-- 
2.54.1


From 3e9913669be1de8e90d4922aee8ed6ddf1c47715 Mon Sep 17 00:00:00 2001
From: Justin Jacob <[email protected]>
Date: Tue, 24 Nov 2026 00:58:54 +0530
Subject: [PATCH 5/5] avcodec/jpeg2000dec: write packed output in one pass

With a packed pixel format and three components of the same geometry,
the existing path writes each component with a strided loop. Write all
three in one interleaved pass over the frame instead.

Signed-off-by: Justin Jacob <[email protected]>
---
 libavcodec/jpeg2000dec.c | 73 +++++++++++++++++++++++++++++++++++++++-
 1 file changed, 72 insertions(+), 1 deletion(-)

diff --git a/libavcodec/jpeg2000dec.c b/libavcodec/jpeg2000dec.c
index 69e6b400d26..c4dcad12cae 100644
--- a/libavcodec/jpeg2000dec.c
+++ b/libavcodec/jpeg2000dec.c
@@ -2673,6 +2673,74 @@ WRITE_FRAME(16, uint16_t)
 
 #undef WRITE_FRAME
 
+/* Output for a packed format whose three components share one geometry: a
+ * single interleaved pass over the frame instead of three strided ones. */
+static void write_frame_16_packed(const Jpeg2000DecoderContext *s,
+                                  Jpeg2000Tile *tile, AVFrame *picture,
+                                  int precision)
+{
+    Jpeg2000Component *comp = tile->comp;
+    const int cbps  = s->cbps[0];
+    const int shift = precision - cbps;
+    const int off   = 1 << (cbps - 1);
+    const int max   = (1 << cbps) - 1;
+    const int w = comp[0].coord[0][1] -
+                  ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[0]);
+    const int h = comp[0].coord[1][1] -
+                  ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[0]);
+    /* Component placement of the per-component path. */
+    const int p0 = s->cdef[0] ? s->cdef[0] - 1 : 0;
+    const int p1 = s->cdef[1] ? s->cdef[1] - 1 : 1;
+    const int p2 = s->cdef[2] ? s->cdef[2] - 1 : 2;
+    int x, y;
+
+    for (y = 0; y < h; y++) {
+        const float *d0 = comp[0].f_data + (ptrdiff_t)y * w;
+        const float *d1 = comp[1].f_data + (ptrdiff_t)y * w;
+        const float *d2 = comp[2].f_data + (ptrdiff_t)y * w;
+        uint16_t *dst = (uint16_t *)picture->data[0] +
+                        (ptrdiff_t)y * (picture->linesize[0] / 2);
+
+        for (x = 0; x < w; x++) {
+            dst[p0] = av_clip(lrintf(d0[x]) + off, 0, max) << shift;
+            dst[p1] = av_clip(lrintf(d1[x]) + off, 0, max) << shift;
+            dst[p2] = av_clip(lrintf(d2[x]) + off, 0, max) << shift;
+            dst += 3;
+        }
+    }
+}
+
+static int can_write_packed(const Jpeg2000DecoderContext *s,
+                            const Jpeg2000Tile *tile)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
+    const Jpeg2000Component *c0 = tile->comp;
+    int compno;
+
+    if (s->ncomponents != 3 || s->precision <= 8 || !desc)
+        return 0;
+    if ((desc->flags & AV_PIX_FMT_FLAG_PLANAR) || desc->nb_components != 3)
+        return 0;
+    if (c0->coord[0][0] != ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[0]) ||
+        c0->coord[1][0] != ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[0]))
+        return 0;
+    for (compno = 0; compno < 3; compno++) {
+        const Jpeg2000Component *c = tile->comp + compno;
+        const Jpeg2000CodingStyle *cs = tile->codsty + compno;
+
+        if (cs->transform != FF_DWT97 || s->cbps[compno] != s->cbps[0])
+            return 0;
+        if (c->coord[0][0] != c0->coord[0][0] ||
+            c->coord[0][1] != c0->coord[0][1] ||
+            c->coord[1][0] != c0->coord[1][0] ||
+            c->coord[1][1] != c0->coord[1][1])
+            return 0;
+        if (s->cdx[compno] != s->cdx[0] || s->cdy[compno] != s->cdy[0])
+            return 0;
+    }
+    return 1;
+}
+
 static int jpeg2000_decode_tile(AVCodecContext *avctx, void *td,
                                 int jobnr, int threadnr)
 {
@@ -2696,7 +2764,10 @@ static int jpeg2000_decode_tile(AVCodecContext *avctx, 
void *td,
                         picture->format == AV_PIX_FMT_RGBA64 ||
                         picture->format == AV_PIX_FMT_GRAY16 ? 16 : 
s->precision;
 
-        write_frame_16(s, tile, picture, precision);
+        if (can_write_packed(s, tile))
+            write_frame_16_packed(s, tile, picture, precision);
+        else
+            write_frame_16(s, tile, picture, precision);
     }
 
     return 0;
-- 
2.54.1

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to