Skip to content

v0.29.0

Choose a tag to compare

@osamu620 osamu620 released this 23 Nov 05:51
· 15 commits to main since this release

Adds open_htj2k_transcode (experimental), which converts a JPEG 2000 Part 1
codestream to HTJ2K, and HTJ2K to Part 1, in the coefficient domain, and fixes
what fuzzing the decoder, the transcoder, JPIP, the command-line tools and the
image readers found: small inputs that kept the decoder busy for minutes,
made a JPIP server or the transcoder take gigabytes, or crashed a
command-line tool, and one decoding error on valid codestreams. Images in many
small tiles decode several times faster with more than one thread. The fuzz
targets are now part of the repository and of the test suite.

Encoded output is byte-identical to 0.28.1, and so is decoded output, with two
exceptions. A code-block first included in a packet that follows two or more
empty packets is now decoded (it used to decode to nothing). An image in which
a component has no samples is now refused as not supported (the component used
to decode to nothing).

Added

  • openhtj2k_decoder::init(buf, length, reduce_NL) and
    init_borrow(buf, length, reduce_NL) re-initialise a decoder with a new
    codestream and keep its thread count: that of the constructor, or of the last
    init() or init_borrow() that took one. Use them to decode one codestream
    after another with the same decoder; init() with num_threads == 1 decodes
    on the calling thread only.
  • Tests that catch a decoder that silently stops using its threads. Each counts
    the tasks the thread pool's worker threads run around a decode, so neither
    depends on timing.
    • threadpool_check covers the library: the three-argument init() and
      init_borrow() keep the threads, and init(..., 1) runs none.
    • wasm_mt_reinit_keeps_threads, run by the WASM CI job, covers the
      WebAssembly wrapper: frames after reset_decoder_with_bytes() must use
      the pool. It fails on the 0.28.0 wrapper, where those frames ran 0 pool
      tasks.
    • The pool keeps the count and updates it while a worker already holds the
      queue lock. Decoding executes the same number of instructions as before.
  • open_htj2k_transcode -i in.j2k -o out.j2c (or .jph), and
    open_htj2k::transcode_part1_to_htj2k() (transcoder.hpp). The Part 1
    code-blocks are decoded to their quantisation indices and coded again with
    the HT block coder: no wavelet transform, re-quantisation or colour
    transform, so a decoder reconstructs the same image from the output as from
    the input. On a Ryzen 9 9950X a 4096x2160 16-bit lossless frame transcodes
    in 2.0 s on one thread (0.12 s on 32), and the result decodes in 73 ms on
    one thread against 1.9 s for the Part 1 original; the output is 111-126% of
    the input size on 4K frames (63-150% on the 43 test streams). Reference:
    docs/cli_transcoder.md.
    • Input: a raw codestream or a JP2 file, with COC (also with another
      wavelet filter than the COD), POC, PPM, RGN (region of interest), PLT, CRG,
      tile-part header COD/COC/QCD/QCC/RGN/COM, SOP/EPH, tiles, precincts and every
      Part 1 code-block style switch. Refused, with a message: Part 2 DFS/ATK
      marker segments, a codestream of 4 GB or more. An HTJ2K input goes the other
      way (below).
    • Output: a raw HTJ2K codestream, or a JPH file (the boxes of a JP2 input
      are kept; a raw codestream gets the boxes the encoder makes, with
      -jph_color_space RGB|YCC). One quality layer (or those of the input, see
      -layers keep below), Rsiz 0x4000, a CAP marker segment (HTREV only when
      every component is reversible; RGN and HETEROGENEOUS when the output has
      RGN marker segments or coding parameters in tile-part headers), the
      input's CAUSAL code-block switch, PLT and TLM written again for the
      output's packets, and a CPF marker segment with the input's profile (Rsiz
      plus one) for a transcode back; POC and PPM are not written (packets are in
      the COD's progression order, with inline headers), nor PLM.
    • -partial refine|drop|keep for blocks the Part 1 encoder cut part-way
      through a bit-plane (refine, the default, is exact); -num_threads N
      (the output does not depend on N); -copy_input.
    • -layers keep (transcode_layers::keep) keeps the quality layers of the
      input with placeholder passes, as the WG1 guideline on placeholder passes
      (WG1 N101237, section 6) recommends: each packet adds to each code-block
      the passes it added in the input, the passes before the block's last
      Part 1 cleanup pass being placeholder passes without bytes, so the output
      can be transcoded back to Part 1 with the same layers. On the guideline's
      example file the tile-part is byte for byte the one the guideline gives.
      The output decodes to the same image as with merge (the default) and is
      0.5-4% larger. Needs -partial refine; refuses a lossy stream with a region
      of interest. OpenJPEG (2.5.0, 2.5.4) does not read placeholder passes, nor
      the guideline's own example files.
    • Memory: the tiles are transcoded one at a time, so a tiled image needs
      about the input plus the output plus one tile (96 MB for a 43 MB, 36-tile
      codestream); an image of one tile needs three to four times the input.
    • Decoded with OpenJPEG 2.5.4 and compared with the Part 1 decode: 43
      conformance, generated and JP2 streams are pixel-identical. OpenJPEG's HT
      decoder does not support RGN, so streams with a region of interest fail
      there. Lossy RGN streams differ from the Part 1 decode by a few levels of
      4095 (p0_06), reversible ones are exact.
    • ctest -L transcoder (155 tests, both directions): round trips on the Part 1
      and HTJ2K conformance streams and on streams made with open_htj2k_enc
      (every code-block style switch, rates, layers, tiles, 16 bit), marker,
      colour-space and refusal checks, and a fuzzer-found input. The tool was run
      under AddressSanitizer (about 19,000 mutated inputs) and ThreadSanitizer.
  • The other direction, HTJ2K to Part 1: open_htj2k_transcode takes an HTJ2K
    input (a CAP marker segment for Part 15 or an HT code-block style) and writes
    a raw Part 1 codestream; open_htj2k::transcode_htj2k_to_part1() and
    transcode_input_is_htj2k() in transcoder.hpp. Every code-block is decoded
    to its quantisation indices (HT cleanup, SigProp and MagRef passes, or the
    Part 1 passes of a mixed codestream's Part 1 blocks) and coded again with the
    Part 1 block coder, down to the same pass, so a decoder reconstructs the same
    image. Reference: docs/cli_transcoder.md.
    • The quality layers of the input are kept (-layers keep, the default for
      this direction; merge gives one): each packet adds to each block the
      passes it added in the input. Placeholder passes become the Part 1 passes
      they stand for; a block's missing MSBs are those of its indices, and the
      passes above the input's (which an HT encoder signals as missing MSBs) go
      into the block's first packet. A cut inside a codeword segment keeps the
      shortest prefix of the coded data that decodes it, so every layer decodes
      as the input's layers do in a Part 1 decoder.
    • Part 1 -> HTJ2K (-layers keep) -> Part 1 gives every code-block of the 22
      Part 1 conformance streams it accepts back with its passes in each layer
      and its missing MSBs; codestreams of open_htj2k_enc come back byte for
      byte with their code-block style. An HTJ2K lossless 4096x2160 16-bit frame
      becomes the encoder's own Part 1 codestream, byte for byte, in 0.11 s (32
      threads; 2.0 s on one).
    • The code-block style switches of the output: those of the input's style
      (CAUSAL for HT blocks, which changes what a SigProp pass covers and so what
      a layer cut inside a bit-plane decodes to), or -Cmodes BYPASS|RESET|RESTART|CAUSAL|ERTERM|SEGMARK (0 for none).
    • Header: Rsiz from the CPF marker segment (its value less one) or without
      bit 14; no CAP or CPF marker segment; the other marker segments as in the
      other direction.
    • All 40 HTJ2K conformance streams (ds0_ht, ds1_ht, mixed ds0_hm) transcode;
      35 decode to the input's image, pixel for pixel. The other five have a
      region of interest with code-blocks coded above their last bit-plane, which
      this library's HT and Part 1 decoders reconstruct differently from the same
      indices (ds0_ht_03_b11 and ds0_ht_15_b11 by one level; ds0_ht_06 by up to
      590 levels of 4095 in one component, both within the conformance tolerance
      of p0_06). OpenJPEG decodes every output, and the round trips decode as
      their Part 1 sources.
    • Refused, with a message: more than one HT set per code-block (MULTIHT),
      Part 2 DFS/ATK marker segments, CAP capabilities besides Part 15, a Part 1
      code-block of more than 65535 bytes; .jph/.jp2 output for an HTJ2K
      input, and the options of the other direction (-partial,
      -jph_color_space, and -Cmodes for a Part 1 input).
  • Library: the main header writer writes the COC, RGN and CRG marker segments it
    holds; j2k_tile::enc_init() takes the COD, COC, QCD, QCC and RGN of a
    tile-part header; j2k_tile::get_packet_lengths();
    j2k_decode_indices() (a Part 1 block's quantisation indices without the
    inverse quantisation); j2k_codeblock::add_ROIshift();
    j2k_codeblock::ht_phld_passes, the placeholder passes the packet header
    writer signals in front of an HT cleanup pass (ISO/IEC 15444-15, B.3);
    htj2k_decode_indices() (an HT block's samples without the inverse
    quantisation, in every SIMD variant); the main header writer writes a CPF
    marker segment it holds (CPF_marker::set_Pcpf(), write()). None of them
    changes what the encoder or the decoder writes or reads.

Changed

  • The WebAssembly wrapper's reset_decoder_with_bytes() uses the new init()
    in place of the table of thread counts added in 0.28.1. Behaviour and output
    are the same.

Performance

  • Decoder (native builds): images in many small tiles decode several times
    faster with more than one thread (#546). Each tile used to spread its
    decoding over the whole thread pool. A small tile's work is less than what
    the pool's dispatches and waits cost, so a 4K RGB image in 64 x 64 tiles
    decoded 1.5 times slower with 4 threads than with 1. Several tiles now
    decode side by side instead, each on one thread.
    • When: when a tile row (in invoke_line_based_stream()), or the image (in
      invoke_line_based()), has at least as many tiles as there are threads,
      or the tiles are small (up to 65,536 samples over all components at the
      resolution decoded). Otherwise each tile still uses the whole pool. A JPIP
      precinct filter or packet observer keeps the tiles one at a time.

    • Unchanged: tiles are still set up and freed on the calling thread, in tile
      order. Warnings come in the same order, the memory budget decides on each
      tile as before, and a failing decode reports the first failing tile's
      error. Decoded output is byte-identical.

    • At most twice as many tiles as threads are set up at a time, and no more
      than an eighth of the memory budget's worth beyond one tile.

    • 4K RGB (3840 x 2160, 8-bit, default lossy settings) on a Ryzen 9 9950X,
      in milliseconds per decode, before and after:

      Tiles 1 thread 4 threads 8 threads
      64 x 64 195, 196 324, 87 328, 98
      128 x 128 107, 107 124, 39 123, 27
      256 x 256 78, 78 61, 27 49, 20
      512 x 512 74, 73 41, 28 37, 23
      1024 x 1024 73, 72 38, 32 35, 36

      Single-tile images are not affected. Peak memory rose by up to 15 MB
      (512 x 512 tiles, 8 threads: 45 to 60 MB).

    • With several threads, a malformed codestream in small tiles now reports the
      same error as with one thread, not "a strip-pull decode task failed".

    • Not in the WebAssembly builds, which decode as before. There the tiles side
      by side got slower with more threads (64 x 64 tiles, Node.js 24: 470, 650
      and 970 ms on 2, 4 and 8 threads, against 600, 780 and 860 ms one tile at
      a time). The cause is not established.

  • WebAssembly: the multi-threaded builds run the inverse colour transform of
    each strip on the thread pool, as the portable x86-64 and scalar builds do.
    It used to run on the decoding thread alone. This applies to
    invoke_decoder_to_rgba() (the still-image demo), invoke_decoder_stream()
    (the Node.js decoder) and other decodes through invoke_line_based_stream();
    the RTP demo and the WebTransport viewer convert colour on the GPU and are
    not affected.
    • 4K RGB, 16-bit, Qfactor 90 (Node.js 24, Zen 5): 17 to 20% faster on 4 and
      8 threads (27.1 to 22.5 ms and 23.9 to 19.2 ms a decode), no change on 2.
      A 4K 8-bit image at about 5 bits per pixel, where block decoding takes
      most of the time, decodes as fast as before.
    • Output is byte-identical. The new test wasm_mt_colour_matches_one_thread
      checks that 4 threads give the same output as 1 on nine conformance
      codestreams with a colour transform; the WebAssembly conformance tests run
      on one thread and never reached this code.
    • NEON builds still run it on the decoding thread. On an Apple M1 Max the
      pool was no faster: 2 to 4% slower for a 4K 8-bit image, within 2% for the
      16-bit one.

Fixed

Found by fuzzing the decoder, the transcoder, the JPIP parsers, the image
readers and estimate_qfactor under AddressSanitizer and
UndefinedBehaviorSanitizer, and by
reading the code the fuzzers led to. In the decoder, the transcoder and JPIP
none of them reads or writes memory out of bounds: a small input (for the JPIP
server, a few small requests) could take minutes or gigabytes. The reader of the encoder's input images could write out
of bounds.

  • Decoder: a small codestream could keep the decoder busy for minutes. For
    every packet that is not empty, the packet-header parser walked the inclusion
    tag tree of every code-block of the precinct, and went over all of them again
    for the packet's body, whether the packet included them or not. Thousands of
    quality layers over a precinct of thousands of code-blocks, with one byte per
    packet ("not empty, no code-block included"), were enough: 4096 layers over
    1024 x 1024 in 4 x 4 code-blocks (4 KB) took 28 s to decode, and 65535 layers
    (64 KB) more than 5 minutes. Both now take 0.04 s. The parser steps over the
    code-blocks below a tag-tree node that the packet leaves beyond its layer, and
    reads a packet's body for the code-blocks its header included. Decoding
    executes the same number of instructions as before on streams of one layer
    (within 0.1%) and up to 1.4% fewer on the conformance streams with several.
  • Decoder: a code-block first included in a packet that follows two or more
    empty packets of its precinct was not decoded: its area came out flat, with
    no error. An empty packet (a single 0 bit, ISO/IEC 15444-1 B.10.3) leaves the
    inclusion tag tree as it was, so the first packet that is not empty holds a
    bit of the tree for each layer so far (B.10.2). The parser read one bit for
    the first layer and one for the current one, which covers one empty packet.
    Codestreams whose encoder writes "not empty, nothing included" packets,
    as this encoder does, were not affected.
  • Transcoder: the output tile was sized by the input's header, outside the
    memory budget that bounds the decoder's state. A 112-byte HTJ2K codestream
    (1024 x 1024 in 4 x 4 code-blocks, 65535 layers) took 8.4 GB and did not
    finish in two minutes; it is now refused as not supported in 0.06 s, like a
    decode that would pass the budget.
    • The output tile builds every code-block with its passes per layer (the
      input tile builds the code-blocks its packets have data for). That state
      now counts against the budget before it is built.
    • The output tile no longer allocates sample buffers, which it never used:
      one float per sample for an image without a wavelet transform, or with
      tiles at odd origins.
    • The packet writer kept a flag per packet in layers x resolutions x
      components lists, each as long as the largest resolution's precinct count.
      It now keeps one flag per packet.
    • Within the budget, the packet headers of a tile with many layers took
      layers x layers steps per code-block: a 97-byte codestream (180 x 180,
      65535 layers) ran for more than 5 minutes, now 2 s. The encoder writes its
      layers (-rate a,b,c) with the same code; its output is unchanged.
  • JPIP client: reassemble_codestream_client() writes one byte for every
    packet it holds no data for, and takes a step for every layer of every
    resolution of every tile-component. Both counts come from the main header,
    which the server sends: a response of 254 bytes took 1.6 GB and 20 s. An
    image with more than 2^26 of them is now refused as not supported, and the
    list of delivered precincts takes memory by what was delivered rather than
    by tiles x components x resolutions.
  • Decoder: a codestream of 94 bytes kept the decoder busy for 47 s (62 s with
    97 bytes). A component can have no samples: an image one sample wide at an
    odd position has no column of a component subsampled by 2. Its rows hold
    nothing, there are as many of them as the image is high (up to 2^31 - 1),
    and the decoder went through every one, for that component and, when it has
    the finest vertical subsampling, as rows of the image for the others. An
    image in which a component has no samples at the resolution being decoded
    (no columns, or no rows) is now refused as not supported by the four
    invoke_line_based*() entry points; parse() and the size getters still
    read it. A tile in which no component has samples (common in tiles one
    sample wide of components subsampled by 255) is now skipped instead of gone
    through row by row: 65535 such tiles of 16384 rows decode in 1.1 s, from
    11.9 s, to the same output.
  • Decoder: invoke_line_based() did not release three rows of scratch memory
    (12 bytes per column of the image) when a code-block of a reversible image
    with the colour transform failed to decode. It does.
  • Transcoder, HTJ2K to Part 1: when the block decoder refused an HT code-block
    of several layers, the bytes that code-block owned were not released (64 to
    4096 bytes a failed transcode). They are.
  • JPIP server: a client could exhaust the server's memory with a few short
    requests. A statement of the model= request field is a few bytes and names
    a range of data-bins; the server remembered every bin of it (up to 2^22 a
    request, about 200 MB), whether the image has that bin or not, and a
    session's model lives as long as its channel. Eight requests of 70 bytes
    on one channel, each naming the next 2^22 precincts, took
    open_htj2k_jpip_server from 5 MB to 3 GB while serving a 1 KB image.
    CacheModel::apply() and parse() now take the limits of the image
    (CacheModel::Limits: the precinct, tile-header and metadata identifiers it
    has, and how many bins a model may hold), ChannelManager::apply_model()
    passes them on, and the server sets them from its codestream index
    (CodestreamIndex::precinct_id_bound()). Statements about bins the image
    does not have are ignored. Without limits a model stops at 2^22 bins.
    Responses to requests about bins the image has are unchanged.
  • estimate_qfactor:
    • on a valid codestream with 20 decomposition levels it ran for 81 s and
      took 0.8 GB (12 GB with 24 levels): it built the wavelet basis functions of
      every level, which double in length each time. It now builds those of 14
      levels and continues their trend, as the encoder does, and gives the same
      estimate at once;
    • a SIZ marker segment without components crashed it; a COD marker segment
      declaring more than 32 decomposition levels, or a QCC marker segment
      without a body (read one or two bytes past its end), is now refused.
  • Encoder input images. The readers trusted the headers of PGM, PPM and PGX
    files:
    • open_htj2k::image (the library's reader of whole files) looped for ever
      on a header that ends early (P5 alone); wrote past the list of planes
      when a PPM file was one of several input files, and into the first file's
      plane for a text (P2) file later in a list; read a row buffer whose size
      had wrapped for widths past 2^31 / 6; and allocated the planes by the
      header before reading a sample. It now refuses a header that is cut,
      holds something other than numbers, declares a maximum value outside 1 to
      65535 or a PGX bit depth outside 1 to 16, or declares more samples than
      the file holds, and a PPM or TIFF file that is not the only input file.
    • It also skipped every white-space byte after the header of a binary file,
      so an image whose first samples are 10, 13 or 32 lost them and was then
      refused as too short. One white-space character ends the header, as the
      formats say (and as open_htj2k_enc already read them).
    • open_htj2k_enc -i a.pgx,b.pgx with a b.pgx of zero width or height
      divided by zero (SIGFPE). A PGX bit depth above 16 (two bytes per sample
      are read) reached a shift by that depth. A PGM or PGX header declaring
      more samples than the file holds made the reader and the encoder allocate
      row buffers by it: 2 GB for a 30-byte file. All are refused with a
      message.
    • A file without samples (a width or a height of 0) is refused by
      open_htj2k::image and by open_htj2k_enc: the library reader went
      through every row of a header of 0 x 2000000000 (3.4 s), and
      open_htj2k_enc allocated 2 GB for the row of 2000000000 x 0.
    • Valid files read as before: the 90 PGM, PPM and PGX files of the
      repository give the same samples.
  • open_htj2k_dec: an output name without an extension (which discards the
    output) crashed with -ycbcr, or with a JPH file whose colour space is
    YCbCr: the missing extension was compared as a string. An output name of 256
    characters or more overran the buffers the file names were built in.
  • Decoder: a sample of a corrupt codestream outside the range of a 32-bit
    integer was converted to an integer by the scalar code at the end of each
    row, which is undefined behaviour in C++ (the vector code that handles the
    rest of the row is defined). It now gets the value the vector code of the
    build gives. Valid codestreams decode as before.

Documentation

  • docs/wasm.md (new) is the WebAssembly page for users:

    • the modules and which to use;
    • decoding in a web page (an example checked under Node.js);
    • cross-origin isolation, and the thread limit of the threaded modules;
    • the Node.js command-line decoder and the demos.

    It takes over the WebAssembly part of docs/building.md, which keeps the
    build commands under the same heading.

  • The CMake requirement is stated consistently as 3.13 or later, as
    CMakeLists.txt declares; the website said 3.14. The docs now note that
    cmake --install needs 3.15 and ctest --test-dir needs 3.20, and give
    the commands to use with older versions.

  • docs/wt_viewer.md moves its architecture notes and reproduction scripts
    after the troubleshooting section, so the user material comes first.

  • docs/qfactor.md (now 303 lines, was 468) opens with which settings to use.
    It keeps the quick start, flat weights, the precision-scaled Qfactor, the
    CLI and C++ reference, estimate_qfactor and the limitations, and gains a
    short user summary of the experimental CSF options. The step-size formula,
    the guideline's weighting tables, the CSF model internals and their
    calibration moved, unchanged, to docs/dev/qfactor_design.md.

  • docs/jpip.md (now 374 lines, was 505) keeps the server, the demos, the
    benchmark, deployment and the limitations. Its internals moved, unchanged,
    to docs/dev/jpip_internals.md: the core library, data bins, sequence
    numbers, zero-skip IDWT, viewport-region decode, the cache-model field and
    the WASM C API. Two of its links pointed at anchors that did not exist;
    they are fixed.

  • docs/wasm_bench.md and docs/planar_idwt_porting.md moved to docs/dev/.

Build and CI

  • Fuzz targets in the repository (tests/fuzz, docs/dev/fuzzing.md): six
    libFuzzer targets for the decoder API, the transcoder, the JPIP client,
    request and server sides, and the reader of the encoder's input images,
    with dictionaries and a script that makes their seed corpora from the test
    and conformance codestreams.

    • The test suite builds them without a fuzzing engine and runs each over a
      small corpus kept in the repository (ctest -R fuzz_replay, six tests),
      on every platform: the corpus holds the inputs that once made a target
      report something.
    • -DOPENHTJ2K_BUILD_FUZZERS=ON links them with libFuzzer, or with the
      engine in LIB_FUZZING_ENGINE; tests/fuzz/build.sh lays out targets,
      dictionaries and seed corpora as OSS-Fuzz and ClusterFuzzLite take them,
      and tests/fuzz/run.sh runs them all for a given time.
    • The new workflow .github/workflows/fuzz.yml runs every target for five
      minutes under AddressSanitizer and UndefinedBehaviorSanitizer, once for
      the SSE2 code and once for the AVX2 code, on each pull request that
      changes the library, the targets or the build files.
  • AddressSanitizer builds do not use the per-thread cache of large buffers: a
    cached buffer handed out again for a smaller request keeps its first size,
    so the sanitizer saw neither a write past the end of the request nor a use
    after the release.

  • A speed A/B check, tools/bench/ab_speed.py, times two builds on the same
    machine and fails when the second is more than 25% slower in any case.
    Runs alternate between the builds. The cases are:

    • native decode and encode of a 4K image, on 1 and 4 threads;
    • native decode of that image in 64 x 64 tiles, on 4 threads;
    • the WebAssembly decoder on the RTP demo's per-frame path (one decoder,
      reset_decoder_with_bytes() every frame), multi- and single-threaded.

    A case over the limit is measured again before it fails.

  • The new workflow .github/workflows/perf-ab.yml runs that check on every
    pull request that changes the sources or the WebAssembly wrapper, comparing
    the base and head built on the same runner. Pointed at 0.28.0's WebAssembly
    decoder, it fails, reporting it 1.85 times slower on the multi-threaded
    per-frame path. Pointed at two identical builds, every case is within 5%.