Repository navigation
v0.25.0
Release for use as a library inside other software, such as OpenCV's
image codecs, which decode files they did not write. The library prints
nothing: errors are std::runtime_error exceptions and warnings go to a
handler set with open_htj2k::set_message_handler(); its internals are in
namespace open_htj2k; the installed headers are also reachable as
<open_htj2k/interface/...>. The encoder writes JP2 files and takes
Qfactor with an alpha channel.
Most of this release is fixes. The decoder and the encoder were fuzzed and
swept with tens of thousands of parameter combinations under
AddressSanitizer, UndefinedBehaviorSanitizer and ThreadSanitizer, and checked
against two other decoders:
- malformed codestreams that crashed the decoder, hung it, read or wrote out
of bounds, or made it allocate gigabytes are rejected with an error; memory
and set-up work driven by header values are bounded; - valid codestreams that decoded wrong now decode right: subsampled
components through the streaming entry points (which OpenCV and
open_htj2k_decuse), packet headers in PPM/PPT markers with several
tile-parts, the precedence of main and tile-part header markers, POC
markers, COC markers with 32 levels, HT/Part 1 mixing, 31 and 32 DWT
levels; - the encoder no longer crashes, overflows or writes undecodable codestreams
for subsampled components,Qfactor=0, 256 or more layers, very small
step sizes, 31 and 32 DWT levels, thousands of tiles (on Windows) or
out-of-range parameters, and lossless coding of 1-bit samples is lossless.
The library decodes every conformance and test codestream byte-identically
to 0.24.0 (the files open_htj2k_dec writes change only as listed under
Tools). Encoded output differs only where a fix changes it; for HT
codestreams that usually means just the magnitude bound in the CAP marker,
which 0.24.0 could set too low.
Things that now behave differently, besides the fixes:
- the decoder refuses, as "not supported", codestreams whose header values
would need far more memory or set-up work than their data and image size
justify (the rule is under Fixed, Decoder), and samples deeper than 30 bits
unsigned or 31 bits signed; - for components whose vertical subsampling factors are not multiples of
component 0's, the streaming row callback runs once per output row of the
common grid, which can be more rows than component 0 has
(get_stream_row_count(),get_stream_component_row()); - the encoder refuses parameters it used to mishandle: out-of-range values,
the irreversible transform with no guard bits, reversible coding deeper
than 23 bits, samples deeper than 30 bits unsigned or 31 bits signed, and
RPCL or PCRL with subsampling factors that are not powers of two; - the shared thread pool runs at most 1024 threads;
- MSVC release builds define
NDEBUG, so the library's internal checks are
compiled out as with GCC and Clang.
Performance
- The decoder visits only the precincts that hold a strip's rows when it
decodes the strip: codestreams with small precincts decode faster (a 4K HT
codestream with precincts 1 to 4 rows high: 25% fewer cycles; 4 x 4
precincts: 4 times as fast). Codestreams with the default (maximal)
precincts decode as before. - Tiles of fewer than 4096 samples decode without the thread pool, so images
of many small tiles are no longer slower with more threads, and each tile's
state is freed once it is decoded (4K in 16 x 16 tiles: 78 MB instead of
672 MB).
Added
Encoder
Qfactorworks with an alpha channel: gray + alpha (2 components) and
colour + alpha (4 components). It used to stop with "Qfactor is only
available for gray-scale or color images". The alpha channel gets a QCC
marker of its own, quantized like a gray-scale plane of its bit depth; with
4 components the colour transform covers components 0-2 as before. Encodes
with 1 or 3 components are byte-identical.- JP2 files (
.jp2, ISO/IEC 15444-1 Annex I) for Part 1 codestreams:- The file holds the signature box, a file type box with brand
jp2
(MinV 0,jp2as its one compatible brand), the JP2 header box and the
Contiguous Codestream box. The codestream is byte-identical to the one
written to a.j2cfile with the same options. - The JP2 header box is the one of JPH files: an image header box; a Bits
Per Component box when the components differ in bit depth or signedness;
an enumerated colour specification box (greyscale for 1 or 2 components,
sRGB for 3 or 4, sYCC with-jph_color_space YCC); and, for 2 or 4
components, the Channel Definition box that declares the last component
as alpha. open_htj2k_encwrites a JP2 file for an output file ending in.jp2.
Library callers select it with the new
openhtj2k_encoder::set_file_format(open_htj2k::file_format::jp2). The
same call selects JPH (file_format::jph) or the bare codestream
(file_format::codestream) in place of the constructor'sisJPH, which
works as before.- A JP2 file carries only a Part 1 codestream, so the encoder refuses to
write one with the HT block coder (the defaultCmodes=HT, for which a
JPH file is the container), with the Part 2 progression order PRCL, or
with the Part 2 or CAP capability bit inRsiz. - OpenJPEG 2.5.4 reads these files as GRAY, SRGB or SYCC as declared, with
the last of 2 or 4 components flagged as alpha, and decodes lossless ones
exactly.
- The file holds the signature box, a file type box with brand
Tools
open_htj2k_decreads.jp2files. The library already found the
codestream in a JP2 file as in a JPH file; the command-line decoder refused
the extension.
Decoder
openhtj2k_decoder::get_stream_row_count()and
get_stream_component_row(c, y)give the row layout of the streaming entry
points (valid afterparse()): how many times the row callback is called,
and which row of componentcitsrow_ptrs[c]holds for output rowy,
orUINT32_MAXwhere no row of the component covers it. A caller that
writes each component's rows once (planar output) writesrow_ptrs[c]
when that row changes. The layout is documented with
invoke_line_based_stream()indecoder.hpp.
Changed
Library
- The library writes nothing to stdout or stderr. Errors are thrown as
exceptions derived fromstd::exceptionwhosewhat()describes the
problem; many used to be a barestd::exceptionwith the description
printed to stdout. An error while decoding a tile is passed on as it was
thrown, instead of being replaced by "Abort Decoding!". - Warnings and informational messages go to a handler installed with the new
open_htj2k::set_message_handler()(headeropenhtj2k_message.hpp,
included bydecoder.hppandencoder.hpp). Without a handler they are
discarded. The handler can be called from the library's worker threads. - The command-line tools install a handler that prints warnings as before
(WARNING: ...). They print an error asERROR: <description>, without
the extraERROR: std::exceptionline. - These changes leave encoded and decoded output unchanged.
- All of the library's internal classes, functions and variables are now in
theopen_htj2knamespace. About 550 of them (ThreadPool,j2k_tile,
SIZ_marker, the DWT and block coder functions, ...) used to be global,
where they could collide with a program's own names: with the static
library at link time, and with the shared library through symbol
interposition. The shared library now exports no global symbols of its
own. Programs that use only the public API need no change.
Build and packaging
- MSVC release builds (
Release,RelWithDebInfo) defineNDEBUG, as the
GCC and Clang ones do. The release flags this project sets replaced the
ones CMake and vcpkg pass, which carryNDEBUG, so the library's internal
assert()s stayed active in Windows release builds and could abort the
calling process (as one did on a valid reversible codestream) instead of
being compiled out.RelWithDebInfoalso uses/Ziinstead of/ZI
(edit and continue), which goes with optimised code and with
/fsanitize=address. - The installed package no longer defines the library's build configuration
macros (OPENHTJ2K_THREAD,OPENHTJ2K_TRY_AVX2,
OPENHTJ2K_ENABLE_ARM_NEON,OPENHTJ2K_DISABLE_SSE2,
OPENHTJ2K_TIFF_SUPPORT,OPENHTJ2K_ENABLE_QUIC) in the code that uses
it. The public headers do not depend on them, but the CMake target passed
them to every consumer. OnlyOHTJ2K_STATICremains, for a static library.
The MsQuic and nghttp3 include directories and libraries of an
OPENHTJ2K_QUIC=ONbuild are private to the library as well. - The headers can be included as
<open_htj2k/interface/decoder.hpp>and
<open_htj2k/interface/encoder.hpp>, which cannot collide with another
library'sdecoder.hpp: the CMake package andopen_htj2k.pcalso put
<prefix>/includeon the include path.#include "decoder.hpp"still
works. image::read_tiff()is declared whether or not the library was built with
libtiff; without libtiff it returnsEXIT_FAILURE. Its declaration used to
depend onOPENHTJ2K_TIFF_SUPPORT, so the header only matched the library
when the consumer defined the macro the same way.image::get_Ssiz_value()inencoder.hppmakes aninttouint8_t
conversion explicit.- Configuring for a big-endian target stops with an error, and so does
compiling the library's sources for one. The block coders assume
little-endian byte order, so such a build compiled and then wrote and read
wrong codestreams. - The
install_consumertest builds its programs with warnings as errors
(-Wall -Wextra -Wpedantic -Wshadow -Wundef -Wconversion -Wsign-conversion -Wold-style-cast -Wcast-qual -Wmissing-declarations, MSVC/W4), compiles
every installed header on its own, includes the headers by both paths, and
fails if a build configuration macro reaches the consumer or if the package
of a static build does not defineOHTJ2K_STATIC. - The
install_consumertest builds its programs with the build's own
CMAKE_CXX_FLAGSandCMAKE_EXE_LINKER_FLAGS(not on MSVC). In a build
with-fsanitize=address,undefinedthe consumer failed to link, because a
program that uses an instrumented library needs the sanitizer runtime too.
With these flags and the test tools fixed, the whole test suite passes
under AddressSanitizer, UndefinedBehaviorSanitizer and LeakSanitizer.
Fixed
Library
- Decoders running at the same time in several threads could deadlock. A
worker of the shared thread pool took up to four tasks at a time and kept
the ones it had not started where no other thread could see them; a decode
task that waited for another decoder's tasks (and ran other queued tasks
while it waited) could end up waiting for a task held back by its own
worker. Workers now take one task at a time. Reproduced with 8 to 16
application threads decoding at once, within seconds to minutes; gone in
the same tests after the change. - Several large in-memory encodes running at the same time could crash. The
pool's task queue had a fixed capacity of 32768 tasks; a push beyond it
threw part-way through a batch of code-block tasks, whose state was then
freed while queued tasks still used it. The queue now grows instead.
Reproduced with 4 concurrent 8192x8192 encodes (4 crashes in 4 runs) and
16 concurrent 4096x4096 encodes; both now complete with correct output. - A thread that decoded many images kept more and more memory until it
exited: the per-thread cache of large buffers existed once per source file,
so a buffer freed in a file other than the one that allocated it was never
reused. On one thread, decoding a 19.6 MB codestream 80 times left 1.5 GB
allocated; now 33 MB, however many decodes. The cache is shared by the whole
library and keeps at most 512 MB per thread. - A decoder or encoder created with
num_threads= 1 used the shared pool
anyway when another instance had created it. It now runs on the calling
thread only. The meaning ofnum_threadsis documented indecoder.hpp
andencoder.hpp. image::get_component_width()andget_component_height()accepted the
index one past the last component and read past the end of their arrays;
they now throwstd::out_of_range.- Reading a byte or a 16-bit word from an empty or one-byte codestream
buffer is now rejected; the bounds check used to wrap around. num_threadshad no upper bound: a library caller passing 100000 made the
shared pool start 100000 threads. The pool now runs at most 1024 threads
(also for 0 = one per hardware thread); a larger count gets 1024. Documented
withnum_threadsindecoder.hppandencoder.hpp.
Encoder
- Lossless encoding of components with different bit depths was not lossless
when a later component was deeper than component 0: the QCD marker follows
component 0's bit depth, and no QCC marker gave the other components their
own quantization parameters, so a deeper component lost its top
bit-planes (an 8-bit component 0 with a 12-bit component 1 came back with
errors of several thousand). The encoder now writes a QCC marker for each
component whose bit depth differs from component 0's, and the CAP marker's
magnitude bit count covers them. Lossy encodes keep their quality and gain
the QCC markers. Images whose components have the same bit depth are
byte-identical. - With three components that differ in bit depth or signedness, the colour
transform (Cycc, on by default) is now turned off with a warning, as it
already was for components of different sizes; it mixes the components'
samples, and no component decoded losslessly. - With four or more components, the colour transform (which covers
components 0-2) was not turned off when those components differed in size,
bit depth or signedness: the checks only looked at images of exactly three
components. With components of different sizes the transform ran across
buffers of different sizes, out of bounds. It is now turned off with a
warning for any image of three or more components. - The image header box of a JPH file gave one bit depth and sign for all
components (component 0's) when the components had the same bit depth but
differed in signedness. It now writes 255 and a Bits Per Component box, as
it already did for components of different bit depths. Other JPH files are
byte-identical. - JPH and JP2 files with a codestream of 4294967288 bytes (4 GiB less 8) or
more got a wrong Contiguous Codestream box length: the 32-bit box length
field (LBox), which counts the 8-byte box header too, wrapped around, and
the encoder returned a file size off by the same amount. Such a box now
has LBox = 1 followed by the 64-bit box length (XLBox, ISO/IEC 15444-1
I.4), which gives the length of the box exactly; LBox = 0 ("to the end of
the file") would be allowed for the last box only and would not tell a
reader where the codestream ends. Smaller files are byte-identical. - Memory for the quantization step sizes doubled with every DWT level: the
encoder built each level's wavelet basis function, which doubles in length
per level, to measure its gain. A 61x47 image took 486 MB at 20 levels and
1.75 GB at 22; at 32 levels (Clevels=32) the encoder used all 91 GB of a
machine's memory before it was killed. The gains have converged by level 14,
so deeper levels now continue their trend (constant for 5/3, doubling per
level for 9/7) instead, in a few MB at any number of levels. The step sizes
are identical to the old ones at every level the old encoder could reach
(checked up to 22 levels: lossless, lossy,Qfactorand derived
quantization, gray and colour). - Lossy codestreams with a very small step size could not be decoded: the
step-size exponent was capped at 31 without regard to the guard bits, so a
subband could get 31 or more magnitude bit-planes, beyond the 30 that the
block coders hold. This happened with a tinyQstep(e.g.Qstep=1e-9at
the default 5 levels, with either block coder) and, at the default step,
with 22 or more DWT levels on an 8-bit image. The exponent is now capped at
31 minus the guard bits, which leaves those subbands at the smallest step
they can take; the codestreams decode. Codestreams that decoded before are
byte-identical. - An encode that failed with an exception could crash while cleaning up: the
tile-component destructor flushed the half-built wavelet transform instead
of only freeing it, and with 32 DWT levels the flush divided by zero
(SIGFPE) in place of reporting the error. The destructor now only frees
memory. - Encoding with 32 DWT levels (
Clevels=32) stopped with "streaming encoder:
tile-component 0 does not fit the strip pipeline", and with 31 levels it
read past the end of an array on the stack: the encoder shares the decoder's
set-up of the resolution levels (see Decoder). Both now encode, and the
codestreams decode to the input exactly (reversible) or as at fewer levels
(irreversible). - The HT cleanup magnitude bound B of the CAP marker (bits 0-4 of Ccap15,
ISO/IEC 15444-15, A.3.7 and 8.7.3) could be smaller than the coded
magnitudes, which makes the codestream non-conforming: reversible encodes
left out the guard bits, irreversible ones took the smallest exponent of
the sub-bands, and a bound of 28 to 30 was signalled as 27 (32 to 34 as
31). B now comes from the HT code-blocks as coded: the magnitude bit-planes
each cleanup pass carries, which leaves out the plane thatCht_refine
refines and the planes that-ratedrops, less n_b - 1 for an irreversible
sub-band at decomposition level n_b; it is rounded up to a value that
Ccap15 can signal. B grows with the guard bits (8-bit lossless with
Qguard=4: 11, was 8) and shrinks with-rate(an 8-bit image at 1 bit per
pixel: 8, was 13). Only the two Ccap15 bytes change. Another decoder decodes
the codestreams as before. - Codestreams of more than 10921 tiles got a corrupt TLM marker: its 16-bit
length wrapped, and no decoder could read them. The tile-part lengths now
go into as many TLM marker segments as they need. - Encoding with thousands of tiles and several threads crashed on Windows.
Every tile kept a 2 MB block of memory for each thread that coded part of
it, until the codestream was written: a 768x512 image in 6x6 tiles (11008
tiles) with 4 threads reserved about 88 GB. Linux only counts the pages
touched, but Windows ran out of commit and the unchecked allocation was
used anyway. These blocks now start at 16 KB and double up to 2 MB as a
tile needs them (959 MB reserved in that example), and a failed allocation
throwsstd::bad_alloc. Codestreams and encoding speed are unchanged. - Subsampled components (
XRsiz/YRsizabove 1) were read from the wrong
place.invoke_line_based()took a component's width asXsiz / XRsiz - XOsizinstead ofceil(Xsiz / XRsiz) - ceil(XOsiz / XRsiz)and offset its
plane by the image origin on the reference grid instead of the component's
own: with an odd width, or any image origin, the samples came out shifted or
garbled, and an origin read before the start of the plane (a crash).
invoke_line_based_stream()guessed which of component 0's rows belong to a
subsampled component from the tile's height, which went wrong with odd
heights, origins and tiles, and could write past a component's rows. A
component now takes a row where component 0's row lies on its sampling
grid. The streaming entry point therefore needs each component'sYRsizto
be a multiple of component 0's (as the command line's readers give it) and
refuses others with an exception;invoke_line_based()takes any. Images
without subsampling are byte-identical. Qfactor=0, documented as valid, divided by zero: every step size was
infinite and converted to an integer (undefined behaviour). It is now taken
asQfactor=1, as the IJG quality scaling does, and gives the same
codestream.- With 256 or more quality layers the codestream could not be decoded: the
packet headers counted a code-block's inclusion in 8 bits. Up to 65535
layers now decode. - The rate control (
-rate,set_target_size(s)) doubled its memory with
every DWT level, as the step sizes did (fixed above): 160 MB at 20 levels,
2.3 GB at 24, more than a machine has towards 32. Its wavelet energies now
continue their limit from level 14; codestreams with up to 14 levels are
byte-identical. - Lossless coding of 1-bit samples was not lossless at 6 or more DWT levels:
the coarsest subbands needed one more magnitude bit-plane than they were
given. 1-bit components now get one more. Other bit depths are
byte-identical. - Reversible coding with more guard bits than a low bit depth leaves room for
(e.g. 2-bit samples withQguard=4) stopped with "A subband ... has 258
magnitude bit-planes": the step-size exponent went below zero and wrapped
around. It now stays at zero, which gives such subbands more bit-planes than
they need. - Derived quantization (
Qderived=yes) at many DWT levels gave subbands a
negative exponent, which no decoder accepts. The LL exponent is now at least
the number of levels less one (a finer step if need be), and an encode that
cannot meet that within the guard bits (31 levels with one guard bit, fewer
with more) is refused. - The HT block coder could write past its cleanup-segment buffer when samples
have close to 30 magnitude bit-planes (a tiny step size on noisy content):
the buffer held 16384 bytes, the segment can take about 21 KB. The buffer
now has room for the largest segment. Output is byte-identical. - With the irreversible transform and no guard bits (
Qguard=0), quantized
coefficients at the edge of the nominal range need one more magnitude
bit-plane than the codestream gives them. The HT block coder wrote them
anyway, which other decoders reject or decode differently, and the Part 1
coder dropped their top bit-planes (or failed with none at all). The
encoder now refuses the irreversible transform without a guard bit; the
reversible step sizes do not depend on the guard bits and are unaffected.
The Part 1 coder also saturates magnitudes that do not fit instead of
wrapping them around. - Reversible coding is lossless for at most 23 bits per sample (22 for the
components the colour transform widens); deeper samples came back with
errors. They are now refused with an exception. With either transform, so
are components of more than 30 bits unsigned or 31 bits signed: the
decoder's DC offset and clamp to the sample range cannot hold them (it
refuses them as well), and the encoder used to write 31-bit unsigned
codestreams. - With the progression order PRCL the encoder wrote a CAP marker without
settingRsizbit 14 (CAP marker present) or bit 15 (ISO/IEC 15444-2
capabilities), so other decoders ignored the marker. Both are now set. - The progression orders RPCL and PCRL are now refused, with an exception,
when a component'sXRsizorYRsizis not a power of two: ISO/IEC 15444-1
(B.12.1.3 and B.12.1.4) allows them only with such factors, and other
decoders refuse those codestreams. CPRL, LRCP and RLCP take any factors. invoke_line_based_stream()wrote past a row buffer when component 0 was
subsampled horizontally more than another component (e.g.XRsiz4 for
component 0 and 1 for component 1): every component's rows were kept in
component 0's width. Each component now has rows of its own width. A tile
in which a component has no samples also no longer passes a null row to
memcpy.- With tile size 0 (one tile) and an image origin, the encoder sized the tile
from the image origin but placed it at the tile origin: with the tile origin
left at 0, the tile did not reach the image's far edge, which gave extra
tiles or "tile size plus tile origin shall be greater than the image
origin". The tile now reaches from the tile origin to the far edge. The
command line sets the tile origin to the image origin and is unaffected. - Out-of-range parameters are refused with an exception from both entry
points instead of giving invalid codestreams, wrong samples, hangs or
crashes: no components or mismatchedSsiz/XRsiz/YRsizvectors, a zero
subsampling factor, an empty image, an image extent beyond 2147483647 (which
the decoder refuses too), more than 32 DWT levels, code-block exponents
beyond 1024 samples or 4096 in all, progression order above 5, no quality
layers,use_color_trafoortransformationabove 1, more than 7 guard
bits, a base step size that is not a positive finite number (zero or a
negative one looped forever), precinct exponents above 15 or of 0 above the
lowest resolution, and user-defined precincts without any size. The step
size encoding no longer overflows for huge steps either. - Writing a JPH or JP2 file of more than 4 components stopped with "invalid
color space specification". The message now says that the file writer takes
1 to 4 components (greyscale or colour, each optionally followed by an alpha
channel) and how many the image has.
Decoder
- A truncated tile-part followed by a tile-part without a body crashed the
decoder (SIGSEGV): the packet reader stepped from the exhausted tile-part
onto the empty one and read through its null buffer. Empty tile-parts are
now skipped, and the truncation is reported as malformed input. Found by
fuzzing the decode path OpenCV uses; a 165-byte file reproduced it. - A JPH or JP2 file that starts with the signature box but has no valid
Contiguous Codestream box, for example one whose 64-bit box length (XLBox)
is smaller than the box header or reaches past the end of the file, is
rejected with "JPH/JP2 file without a valid Contiguous Codestream box". It
used to be read as a bare codestream, which failed with an unrelated error.
Contiguous Codestream boxes with LBox = 1 and an XLBox, or with LBox = 0
(to the end of the file), are read as before. - Malformed codestreams that crashed the decoder, hung it, made it read or
write out of bounds or made it allocate gigabytes are now rejected with an
error message. They were found by fuzzing the decoder the way OpenCV calls
it (read the main header, then decode row by row). The decoder now rejects:- an empty input, a codestream that does not begin with an SOC marker, and
a main header without a SIZ, COD or QCD marker; - a SIZ marker that breaks the tiling rules of ISO/IEC 15444-1 (A.5.1): a
tile size of zero, an image origin outside the image, a tile origin after
the image origin or a first tile that ends before the image starts; and a
SIZ marker with more than 65535 tiles or a bit depth above 38; - a COD marker shorter than 12 bytes, a COC marker too short for its coding
style, and any marker field read past the length of its segment; - a QCD or QCC marker with an undefined quantization style, without a step
size, or with fewer step sizes than the decomposition levels of a
component need (also when a COC marker gives the component more levels); - an RGN marker with a region-of-interest style other than 0 or a shift
above 31; - PPM markers without a complete packet-header record, or with fewer
records than tiles; - a tile that declares more packets (layers times precincts) than the
codestream has bytes, since every packet takes at least one byte. A
908-byte codestream declaring 588 million packets made the decoder
allocate 28 GB. Truncated codestreams with up to about a million packets
in all are decoded as before; - the colour transform with component 1 or 2 subsampled differently from
component 0, which wrote past the rows of the smaller components.
- an empty input, a codestream that does not begin with an SOC marker, and
- Valid codestreams that the decoder cannot represent are rejected as "not
supported" instead of crashing: a reference grid wider or taller than
2147483647 (sample coordinates are held in 32-bit signed integers), or a
tile grid that ends past 4294967295; quantization style 0 (no quantization)
with a wavelet transform other than the reversible 5/3; and a
region-of-interest shift that, added to the magnitude bit-planes of a
component, exceeds the 31 bits of a sample. - The row callback of
invoke_line_based_stream()never gets a row shorter
than the width the decoder reports: the decoder checks that every tile lies
within the image rows it fills, and with several tile columns a subsampled
component without rows in a tile row now gets a row of zeros, not a row
read from an empty buffer. - A failed memory allocation inside the library throws
std::bad_alloc; the
decoder used to go on with a null buffer.invoke_line_based()checks that
its output buffers fit in memory before allocating them, and the tile count
no longer overflows for tile sizes near 2^32. - Decoding no longer reads one precinct past the end of a resolution when a
packet's precinct index equals the resolution's precinct count. - After
init()fails,parse()no longer reads the previous input. - Codestreams with 31 or 32 DWT levels, the most the standard allows, wrote
past the end of arrays on the stack while the decoder set up the resolution
levels, and with 32 levels the sizes of the lowest resolution and its
subbands came from a 32-bit shift by 32, which is undefined: a valid
32-level file decoded to a wrong image. Both now decode correctly.
Reducing by all 32 levels is not supported:get_max_safe_reduce_NL()
returns at most 31. - An HT code-block whose coding passes are all placeholder passes decodes to
zeros, but nothing wrote them: its samples kept whatever the decoder's
reused buffer held before, so the decoded image could change from run to
run. They are now zeroed. - A tiled codestream that ends before some of its tiles, such as a truncated
download, crashed the decoder. The missing tiles now decode as tiles
without coded data (mid-grey for unsigned samples), with a warning for
each, as the decoder already did for packets missing from a tile that is
cut short. A tile with more than 255 tile-parts crashed too (the count
wrapped to 0) and now decodes; a tile whose tile-parts do not include the
first one (TPsot 0), which holds the tile header, crashed and is now
rejected. - Malformed codestreams that reached undefined behaviour (out-of-range
shifts and integer overflows, which gave wrong output or crashed) are now
rejected with an error:- quantization parameters that give a subband more than 30 magnitude
bit-planes, the most the decoder supports, or, with derived
quantization, a negative exponent; - a Part 1 code-block with more missing bit-planes than its subband has,
or with more coding passes than fit below them; - a code-block segment length signalled in more than 32 bits.
- quantization parameters that give a subband more than 30 magnitude
- Decoding no longer reaches undefined behaviour on a quantization step too
large for the integer step of the ROI dequantization (it saturates), on
corrupt MQ-coded data (the code register is now unsigned), or on image
rows at negative coordinates, which a malformed image size produced and
which the streaming DWT used to place outside its row buffer. The scalar
code of the ROI dequantization and of the reversible 5/3 inverse lifting
now computes in wrapping 32-bit arithmetic, as their SIMD code already
did, instead of overflowing on out-of-range values from a malformed
codestream; the ROI upshift of a background sample is an unsigned shift. - When building a tile's resolution levels failed part-way, they were freed
while thread-pool tasks could still be setting up their precincts. The
decoder now waits for those tasks first. - Valid codestreams with fewer than 31 DWT levels decode exactly as before.
- Packet headers in PPM markers (ISO/IEC 15444-1, A.7.4) were looked up by
tile, but the PPM markers hold one record per tile-part, in the order the
tile-parts appear in the codestream. Codestreams with PPM markers and more
than one tile-part per tile, or with the tiles in another order, decoded
wrongly or failed ("Expected EPH marker", "codeblock layer length ...
exceeds ... byte(s) left in tile-part"). Each tile now takes the records of
its own tile-parts. A codestream with fewer records than tile-parts is
rejected with "PPM markers hold N packet-header records, none for
tile-part K" (it named a tile before). - With the packet headers in PPM or PPT markers and a tile in several
tile-parts, the first packet body of each later tile-part was read as empty,
with the warning "codeblock layer length ... exceeds 0 byte(s) left in
tile-part", and the tile decoded wrongly. PPT markers were also ignored when
the first tile-part of a tile had none, as a tile-part without packets may
(A.7.5). - PPM and PPT markers are now joined in increasing Zppm and Zppt, the order
their index gives, and not in the order they appear in. - SOP marker segments are allowed but not required once Scod enables them:
each packet may or may not have one (A.8.1). A packet without one failed
with "Expected SOP marker". - Coding and quantization parameters did not follow the order of precedence
of ISO/IEC 15444-1, A.6.1 to A.6.5 (tile-part COC > tile-part COD > main
COC > main COD, and tile-part QCC > tile-part QCD > main QCC > main QCD):- a main-header COC or QCC marker for a component also applied in tiles
whose tile-part header has a COD or QCD marker, which overrides it; - a main-header COC, QCC or RGN marker for a component was ignored in a
tile whose tile-part header has a marker of the same kind for another
component.
Such tiles decoded wrongly or failed (for example with "component 0 needs
10 quantization step sizes for 3 decomposition levels").
- a main-header COC or QCC marker for a component also applied in tiles
- A POC marker whose CEpoc is 0, which stands for 256 components (16384 with
more than 256 components; Table A.32), described no component, so its
packets were read in the order of the COD marker. The progressions of POC
markers in tile-part headers after the first of a tile (A.6.6) were
ignored. - A COC marker with 32 decomposition levels was read as having none: the
level count was masked to 5 bits. A COC marker with more than 32 levels is
now rejected, as a COD marker already was. - HT code-blocks were decoded with the rules that tell an HT code-block from
a Part 1 one in a mixed tile-component whenever bit 14 or bit 15 of Ccap15
(CAP marker) was set, also in tile-components whose SPcod or SPcoc does not
allow mixing (bit 7 clear), as in every HTDECLARED codestream. Many decoded
wrongly without an error (a lossless HTDECLARED codestream with 8x8
code-blocks came back with errors of up to 121). Those rules now apply only
to a tile-component whose SPcod or SPcoc has bits 6 and 7 set in a
codestream with bits 14 and 15 of Ccap15 set (ISO/IEC 15444-15, A.3.2 and
A.4). Codestreams with neither bit set decode as before. - The decoder allocated memory sized by header values that the codestream's
data does not back, so a codestream of about 100 bytes could make it
allocate from hundreds of megabytes to more than 8 GB. Decoded images are
unchanged; the memory it takes now follows the data:- The code-blocks of a precinct are set up when the first packet of the
precinct that is not empty is read, so precincts without coded data take
no code-block memory. A 112-byte codestream of a 16384 x 16384 image with
4 x 4 code-blocks and empty packets decodes with 15 MB instead of 5.7 GB. - The decoder keeps no per-layer state for each code-block. It took 2 bytes
per layer per code-block: with 65535 layers, a 112-byte codestream of a
1024 x 1024 image made it allocate more than 8 GB. Reading the packets
also no longer takes time growing with the square of the layer count. - A code-block whose data comes in several layers is copied into a buffer
sized by that data instead of one of at least 8 KB. - A tile's resolutions, precincts and code-blocks are freed once the tile
is decoded, so a codestream of many tiles holds one tile's at a time
(a 4K image in 16 x 16 tiles: 78 MB instead of 670 MB). - The line buffers of a subband are as high as its code-blocks or the
subband, whichever is lower, instead of always as high as the
code-blocks, and a subband without columns gets none. The code-block
scratch of each subband (37 KB) is allocated when the subband decodes a
code-block, at the size its code-blocks need.
- The code-blocks of a precinct are set up when the first packet of the
- The decoder now refuses, as "not supported", a codestream whose tile,
precinct and code-block state would exceed a budget: the larger of
256 MiB, 512 bytes per byte of codestream, and 2 bytes per image sample
(all components at full resolution). It counts the state it holds at a
time (each tile's is given back once the tile is decoded) and checks the
line buffers of each tile against the same budget, before allocating
either. The conformance codestreams need under 8% of it. Valid codestreams
it can refuse are of three kinds:- very large images with code-blocks smaller than about 16 x 16 at very
low bit rates (each code-block takes about 300 bytes once its precinct
has data, more than such a codestream spends on it); - headers that declare huge precinct counts, or tile times component
counts, with little data; - images only a few rows high and about a million or more columns wide,
whose line buffers (an eight-row ring per decomposition level) grow with
the width and not with the height: 1048576 x 2 in RGB needs 516 MB.
Codestreams it now refuses include ones that made the decoder allocate
1 GB (650 thousand 2 x 2 precincts in 112 bytes), 7 GB (9361 progression
order changes copied to each of 65535 tiles) and more than 8 GB (16384
components with 32 decomposition levels).
- very large images with code-blocks smaller than about 16 x 16 at very
- On the single-tile reuse path (
invoke_line_based_stream_reuse()and
invoke_line_based_direct()afterenable_single_tile_reuse(true)), a
frame after the first decoded the wrong precincts, or failed, when a
resolution had more than 65535 precincts or the tile more than 255
components: the cached packet order held their indices in 16 and 8 bits.
A frame whose tile-part header gives a component another number of
decomposition levels than the first frame is now rejected; it made the
decoder index past the levels built for the first frame. - A Part 2 codestream whose DFS marker declares a decomposition level without
a transform crashed the decoder: such a level has no subbands, but it was
set up with three, read from a null array. It now has none. - Header values could also make the decoder work for minutes on a codestream
of a few kilobytes. It now refuses, as "not supported":- packet progressions taking more than the larger of 2^28 steps and 64
steps per codestream byte. 9361 progression order changes in the main
header, each replayed over every packet of each of 65535 tiles, took 30 s
for a 65 KB codestream; - more tile-components (tiles times components) than the larger of 2^20
and one per codestream byte. 16384 components in 65535 tiles without
data, from 49 KB, took minutes.
Decoding a strip of a subband no longer visits every precinct of its
resolution, only those holding the strip's rows: codestreams with small
precincts decode faster (4K with precincts 1 to 4 rows high: 25% fewer
cycles; 4 x 4 precincts: 4 times as fast).
- packet progressions taking more than the larger of 2^28 steps and 64
- Tiles of fewer than 4096 samples (all components) are set up and decoded
without the thread pool, whose dispatches cost more than their work: a
2048 x 2048 colour image in 16 x 16 tiles decoded twice as slowly with 4
threads as with 1 (0.91 s against 0.45 s) and now takes 0.25 s with either. - The streaming entry points (
invoke_line_based_stream(), its single-tile
reuse variant,invoke_line_based_direct(), and theopen_htj2k_dec
command, which uses them) returned wrong rows for vertically subsampled
components outside the simple cases: a factor that does not divide the
strip height (YRsiz 3), tiles whose height is not a multiple of a
component's factor (a component row spanning two tiles), several tile
columns, an image origin that is not a multiple of the factor, a component
with a smaller factor than component 0 (its rows beyond component 0's
height were never decoded), or factors that are not multiples of
component 0's. The rows were paired with the callback's rows from the
ratio of the component heights. They now follow the sampling grid: row k
of a component with factor YRsiz covers reference-grid rows
[k * YRsiz, (k + 1) * YRsiz), and the callback is called once per run of g
reference rows (g being the greatest common divisor of the YRsiz), with
each component's covering row (zeros above a component's first row). When
every component's factor is a multiple of component 0's (4:4:4, 4:2:2,
4:2:0, all factors equal) the callback rows are component 0's rows, as
before, and the output is byte-identical; otherwise there can be more
callback rows than component 0 has (get_stream_row_count()).
set_row_range()andset_row_limit()now also work with several tile
rows (each tile row applied the window as if it were the first), and
decoding stops at the end of the window instead of decoding the remaining
tiles. Checked against two other decoders for vertical factors 1 to 255
(including 3, 5, 7, 2 with 3, 4 with 6, ...), horizontal factors 1 to 5,
image and tile origins, tiles of odd heights in one or several columns,
1 to 12 components, the colour transform with an extra component, reduced
resolutions, all progression orders, and 1 and 4 threads. invoke_line_based()did not decode the rows of a component with more rows
than component 0 (a smaller vertical factor) beyond component 0's height.- Samples of 31 bits and more: the DC offset and clamping range were computed
with 32-bit shifts that overflowed (undefined behaviour) for 31-bit unsigned
and 32-bit signed samples and shifted by more than 31 for deeper ones (the
SIZ marker allows 38 bits). The decoder computes samples, their DC offset
and the clamp in 32-bit integers, which leaves room for the overshoot of
lossy decoding up to 30-bit unsigned and 31-bit signed samples, so it now
decodes those and refuses deeper components with "component N has B-bit
... samples: not supported" (open_htj2k_decwrites at most 16 bits in
any case). - On x86-64 builds without AVX2 (and other builds without NEON or WASM SIMD)
a malformed HT code-block whose quad needs 128 or more MagSgn bits was
decoded into garbage, where the AVX2, NEON and WASM readers refuse it; the
SSE2 and scalar readers now refuse it the same way. Quads with fewer such
bits than that but more magnitude bits than the code-block holds are
decoded with the magnitude clamped (with a warning, as before), which
removes a shift past 31 bits in the scalar reader and makes the SSE2 and
scalar readers agree. Valid codestreams decode exactly as before. invoke_line_based_direct()wrotedescs[c].widthsamples of each row even
where the component has fewer, reading past the end of the row. It now
writes at most the component's width (documented indecoder.hpp).
Tools
open_htj2k_decguessed each component's vertical subsampling factor from
the ratio of the component heights to pick the rows it wrote, which is
wrong for some factors and origins (see Decoder). It now writes each
component row as the decoder's row map gives it.open_htj2k_rtp_recvgave component 2 the plane size of component 1 in the
direct-to-planar decode (and, in the GPU upload path, its own size against
planes of component 1's): a stream whose components 1 and 2 differ in size
wrote past a plane or read past a row. Each component now writes what fits
both. The WASM decoder's interleaved streaming output kept the DC offsets of
at most 16 components on the stack and wrote past them for more.open_htj2k_decexited with status 0 when decoding failed: it printed the
error and carried on. It now exits with a non-zero status.open_htj2k_encwrote a JPH file, not a bare codestream, for an output
file ending in.jphc, and refused.jhc, the extension its help text
recommends for a codestream. Both now get the bare codestream. The output
file extension is now matched in any letter case.open_htj2k_decwrote the PGX, PGM and RAW files of an image whose
components differ in bit depth or signedness with component 0's bytes per
sample, and the PGM files with component 0's offset for signed samples. The
other components came out wrong: for a 12-bit component 0 and an 8-bit
component 1, the second file held 2 bytes per sample under a header that
says 8 bits. Every file now takes its own component's bit depth and sign.
A PPM file has one maximum value for its three components: the decoder now
stops with an error when their bit depths differ, instead of writing them
with component 0's. It also stops for a component of more than 16 bits,
which none of the output formats holds; only 2 bytes of each such sample
used to be written. Images whose components share bit depth and sign
decode as before.open_htj2k_encended with an uncaught exception (SIGABRT) on numbers it
could not parse or that overflowed, e.g.Clevels=abc,
Sorigin={0,4294967234},Cprecincts={x,y},Qzoom=abc,
-num_threads abc. Every number is now checked whole and against its range,
with an error message and exit code 1.Qstep=nanwas accepted; negative
coordinates (Stiles={-1,-1}) wrapped around;Corder=LRCPXwas taken as
LRCP;-num_threadsup to 2^32-1 created that many threads (100000 used
more than 4 GB) and is now at most 1024; an image origin that puts the image
beyond 2147483647 is refused.open_htj2k_enc -i a.pgm,b.pgmread the first file only. A list of PGM, PPM
or TIFF files now gives the components of each file in turn, as a list of
PGX files does; a file smaller than the first by whole factors gives
subsampled components.
Encoder and decoder
- Small images, or images with a nonzero origin, no longer make the
line-based DWT request zero-byte aligned allocations (posix_memalign()
with size 0, which Valgrind reports, for example for 1x1, 3x2 or 1x300
images). A resolution or band without columns now gets non-empty scratch
buffers. - The line-based forward DWT read up to 12 bytes before a buffer for a
resolution without columns (which a nonzero image origin can produce). It
now skips the horizontal filter for such rows; the values read never
reached the codestream. - The position-driven progression orders (RPCL, PCRL, CPRL and the Part 2
PRCL) failed from 16 DWT levels on. The encoder and the decoder find where
a precinct starts from the multiple XRsiz * 2^(PPx + NL - r) (ISO/IEC
15444-1 B.12.1.3), which they formed with a 32-bit shift: with maximal
precincts (PPx = 15) the shift reached 47 at 32 levels. With a sub-sampled
component (XRsiz = 2) both crashed with an integer division by zero
(SIGFPE) from 16 levels on; an image wider than 32768 columns (more than
one maximal precinct) was rejected from 17 levels on with "attempt to
access precinct whose index is out of the valid range", also when the
codestream came from another encoder. The multiple is now formed in 64
bits. OpenJPEG 2.5.4 decodes the new codestreams (Part 1, 16 to 32 levels)
to the input exactly. Codestreams that encoded and decoded before are
unchanged. - With those progression orders, every tile scanned the reference grid from
0 to its own end for precinct positions, not from its start. A tile far
from the grid origin with small precincts took up to 2^31 steps: with the
image origin at 2147418112 and 2x2 precincts, 192 tiles of a 61x47 image
took 52 s to encode and 69 s to decode, and a 1 KB codestream of 65535
such tiles would have kept the decoder busy for about 15 hours. The scan
now covers the tile only; the codestreams and decoded images are the same.
JPIP
- The precinct index and the view-window resolver work with 31 and 32 DWT
levels. They divided coordinates by 2^(NL - r) and by 2^r (r the discard
level) with a 32-bit shift, which is undefined when the exponent is 32; a
build that divided by 1 there answered a frame-size request with the wrong
resolution (fsiz=2,2 with round-up returned only the lowest resolution of a
32-level image instead of the 28 it needs). - A view-window offset or size large enough that offset * 2^r passed 2^32
wrapped around and selected the precincts of a region inside the image; it
now selects nothing, as for any region past the image. - The precinct index rejects a tile-component with more than 4294967295
precincts, which its 32-bit precinct numbers cannot count, instead of
wrapping the numbers around. - The precinct index sets up every tile-component of the codestream at once,
about 450 bytes each, so a small main header could make a JPIP server or
client run out of memory: a 144-byte header with 65535 tiles of 17
components took 465 MB, and one with a few thousand components (6 KB)
asked for tens of GB. A codestream with more than 1048576 tile-components
(65535 tiles of 16 components) is now rejected with an error.