htj2k

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package htj2k implements HTJ2K block decoding. This file implements the HTJ2K cleanup pass decoder as specified in ISO/IEC 15444-15.

The HTJ2K cleanup pass is the primary decoding pass that achieves the ~10x speedup over standard JPEG 2000 EBCOT coding. Key innovations include:

  • Quad-based processing: Decodes 4 coefficients at a time (2x2 quads)
  • Simplified context: Uses MEL for significance, VLC for magnitudes
  • Parallel-friendly: Quads can be decoded independently
  • Fixed-rate VLC: Pre-computed lookup tables for fast decoding

Package htj2k implements the High-Throughput JPEG 2000 (HTJ2K) block decoder as specified in ISO/IEC 15444-15.

HTJ2K is a high-throughput variant of JPEG 2000 that provides significantly faster decoding (approximately 10x) compared to the standard JPEG 2000 block coder (EBCOT Tier-1). This is achieved through a simplified block coding algorithm that uses fixed-length coding and parallel-friendly data structures.

Architecture

The HTJ2K block coder uses three main coding components:

  • MEL (Magnitude and Sign Length): Context-adaptive run-length coding for significance information
  • VLC (Variable Length Coding): Fixed-rate coding for coefficient magnitudes
  • MagSgn (Magnitude and Sign): Raw magnitude and sign bit storage

Coding Passes

Unlike standard EBCOT which uses three coding passes (Significance Propagation, Magnitude Refinement, and Cleanup), HTJ2K uses a modified cleanup pass that processes coefficients in 2x2 quads for improved throughput.

Usage

The HTJ2K decoder integrates with the existing JPEG 2000 decoder. When a codestream contains the HTJ2K capability marker (Pcap bit 14), the decoder automatically routes block decoding to this package.

Security

All operations validate input bounds and use safe integer conversions from the internal/safeconv package. The decoder enforces security limits defined in the security package to prevent denial-of-service attacks.

References

  • ISO/IEC 15444-15:2019 - High-Throughput JPEG 2000 (HTJ2K)
  • ITU-T Rec. T.814 (2019)

Package htj2k provides HTJ2K block decoder integration. This file integrates HTJ2K with the existing JPEG 2000 decoder.

Package htj2k implements HTJ2K block decoding. This file implements the MEL (Magnitude-Exponent-Length) decoder as specified in ISO/IEC 15444-15.

MEL coding is a context-adaptive run-length coding scheme used to efficiently encode significance information for coefficient quads. The context state machine adapts based on observed patterns to improve compression efficiency.

Package htj2k implements HTJ2K block decoding. This file implements the VLC (Variable Length Coding) decoder as specified in ISO/IEC 15444-15.

VLC coding provides efficient encoding of coefficient magnitude information using pre-computed lookup tables. The VLC segment in HTJ2K contains the magnitude exponents and additional magnitude bits for significant coefficients.

Index

Constants

View Source
const (
	// CAPMarker is the Capabilities marker (0xFF50).
	CAPMarker uint16 = 0xFF50

	// PcapHTJ2KBit is bit 14 in Pcap indicating HTJ2K capability.
	// When set, the codestream uses High-Throughput block coding.
	PcapHTJ2KBit uint32 = 1 << 14

	// MinCAPLength is the minimum length of a CAP marker segment.
	MinCAPLength = 2
)

HTJ2K detection constants per ISO/IEC 15444-15.

View Source
const (
	// MaxHTBlockWidth is the maximum code-block width for HTJ2K (same as EBCOT).
	MaxHTBlockWidth = 64

	// MaxHTBlockHeight is the maximum code-block height for HTJ2K (same as EBCOT).
	MaxHTBlockHeight = 64

	// MaxHTBitPlanes is the maximum number of bit planes in HTJ2K coding.
	MaxHTBitPlanes = 32

	// MaxQuadsPerBlock is the maximum number of 2x2 quads in a code-block.
	// (64/2) * (64/2) = 32 * 32 = 1024 quads maximum.
	MaxQuadsPerBlock = 1024

	// MaxMELContextState is the maximum MEL context state value.
	MaxMELContextState = 7

	// MaxVLCTableSize is the maximum size of VLC lookup tables.
	MaxVLCTableSize = 256

	// MaxVLCCodeLength is the maximum length of a VLC code in bits.
	MaxVLCCodeLength = 16

	// QuadWidth is the width of a coefficient quad (2 samples).
	QuadWidth = 2

	// QuadHeight is the height of a coefficient quad (2 samples).
	QuadHeight = 2

	// QuadSize is the number of coefficients in a quad (2x2 = 4).
	QuadSize = 4
)

HTJ2K block coding constants per ISO/IEC 15444-15.

View Source
const (
	// HTFlagSig indicates the coefficient is significant (non-zero).
	HTFlagSig uint8 = 1 << iota

	// HTFlagVisited indicates the coefficient was visited in the current pass.
	HTFlagVisited

	// HTFlagRefined indicates the coefficient has been refined (MagRef pass).
	HTFlagRefined

	// HTFlagSign indicates the coefficient is negative (1 = negative).
	HTFlagSign

	// HTFlagFirstMag indicates this is the first magnitude bit for the coefficient.
	HTFlagFirstMag
)

HTBlock state flags for per-coefficient tracking.

Variables

View Source
var (
	// ErrInvalidHTBlock indicates the HT block structure is malformed.
	ErrInvalidHTBlock = errors.New("htj2k: invalid HT block structure")

	// ErrInvalidMELSegment indicates the MEL segment data is corrupted or malformed.
	ErrInvalidMELSegment = errors.New("htj2k: invalid MEL segment")

	// ErrInvalidVLCSegment indicates the VLC segment data is corrupted or malformed.
	ErrInvalidVLCSegment = errors.New("htj2k: invalid VLC segment")

	// ErrInvalidMagSgnSegment indicates the MagSgn segment data is corrupted.
	ErrInvalidMagSgnSegment = errors.New("htj2k: invalid MagSgn segment")

	// ErrTruncatedBlock indicates the block data is incomplete or truncated.
	ErrTruncatedBlock = errors.New("htj2k: truncated block data")

	// ErrInvalidQuad indicates a 2x2 coefficient quad is malformed.
	ErrInvalidQuad = errors.New("htj2k: invalid coefficient quad")

	// ErrMELContextOverflow indicates the MEL context state machine overflowed.
	ErrMELContextOverflow = errors.New("htj2k: MEL context overflow")

	// ErrVLCTableIndexOutOfRange indicates a VLC lookup index exceeded table bounds.
	ErrVLCTableIndexOutOfRange = errors.New("htj2k: VLC table index out of range")

	// ErrInvalidSignificancePattern indicates an invalid significance pattern was decoded.
	ErrInvalidSignificancePattern = errors.New("htj2k: invalid significance pattern")

	// ErrBitplaneOverflow indicates the bitplane value exceeds maximum allowed.
	ErrBitplaneOverflow = errors.New("htj2k: bitplane overflow")

	// ErrBlockSizeExceeded indicates the block dimensions exceed HTJ2K limits.
	ErrBlockSizeExceeded = errors.New("htj2k: block size exceeded")

	// ErrInvalidCodingPassType indicates an unknown coding pass type was encountered.
	ErrInvalidCodingPassType = errors.New("htj2k: invalid coding pass type")

	// ErrSegmentSizeMismatch indicates segment lengths don't match expected values.
	ErrSegmentSizeMismatch = errors.New("htj2k: segment size mismatch")

	// ErrUnsupportedProfile indicates an unsupported HTJ2K profile was detected.
	ErrUnsupportedProfile = errors.New("htj2k: unsupported HTJ2K profile")

	// ErrMaxIterationsExceeded indicates decoding exceeded the maximum iteration limit.
	ErrMaxIterationsExceeded = errors.New("htj2k: maximum iterations exceeded")
)

HTJ2K-specific errors for block decoding operations.

View Source
var ErrInvalidCAPMarker = ErrInvalidHTBlock

ErrInvalidCAPMarker indicates a malformed CAP marker.

Functions

func ApplySign

func ApplySign(magnitude int32, negative bool) int32

ApplySign applies a sign bit to a magnitude value. Returns the signed coefficient value.

Parameters:

  • magnitude: The unsigned magnitude value
  • negative: True if the coefficient should be negative

Returns:

  • The signed coefficient value

func ReconstructCoefficients

func ReconstructCoefficients(magnitudes [QuadSize]int32, signs [QuadSize]bool) [QuadSize]int32

ReconstructCoefficients applies signs to magnitudes and returns final values. This is used to convert decoded magnitude/sign pairs into signed coefficients.

Parameters:

  • magnitudes: Array of magnitude values
  • signs: Array of sign bits (true = negative)

Returns:

  • Array of signed coefficient values

Types

type CAPMarkerData

type CAPMarkerData struct {
	// Pcap contains the capabilities bitmap.
	// Bit 14 indicates HTJ2K (High-Throughput) block coding.
	Pcap uint32

	// Ccap contains extended capabilities for each set Pcap bit.
	// This is optional and may be nil.
	Ccap []uint16

	// IsHTJ2K is true if bit 14 of Pcap is set.
	IsHTJ2K bool
}

CAPMarkerData represents a parsed CAP (Capabilities) marker.

func ParseCAPMarker

func ParseCAPMarker(data []byte) (*CAPMarkerData, error)

ParseCAPMarker parses a CAP marker from raw data. The data should start after the marker and length bytes.

Parameters:

  • data: The CAP marker segment data (after marker and length)

Returns:

  • Parsed CAPMarkerData
  • An error if the data is malformed

type CleanupPassDecoder

type CleanupPassDecoder struct {
	// contains filtered or unexported fields
}

CleanupPassDecoder decodes an HTJ2K code-block using the cleanup pass algorithm. The cleanup pass processes coefficients in 2x2 quads for improved parallelism and throughput compared to standard EBCOT stripe-based processing.

func NewCleanupPassDecoder

func NewCleanupPassDecoder(block *HTBlock, melData, vlcData, magSgnData []byte) (*CleanupPassDecoder, error)

NewCleanupPassDecoder creates a new cleanup pass decoder for an HTJ2K code-block.

Parameters:

  • block: The HTBlock to decode into (must be pre-allocated)
  • melData: MEL-encoded significance data
  • vlcData: VLC-encoded magnitude data
  • magSgnData: Raw magnitude and sign bits (optional, can be nil)

Returns:

  • A configured CleanupPassDecoder ready for decoding
  • An error if the block or data is invalid

func (*CleanupPassDecoder) DecodeBlock

func (d *CleanupPassDecoder) DecodeBlock() error

DecodeBlock decodes the entire HTJ2K code-block. This processes all quads in raster scan order (left-to-right, top-to-bottom).

Returns an error if decoding fails completely. Partial decoding may still leave valid coefficients in the block.

func (*CleanupPassDecoder) DecodeBlockWithBitPlane

func (d *CleanupPassDecoder) DecodeBlockWithBitPlane(bitPlane int) error

DecodeBlockWithBitPlane decodes the block at a specific bit plane. This allows for progressive decoding of HTJ2K data.

Parameters:

  • bitPlane: The bit plane to decode (0 = MSB)

Returns an error if decoding fails.

func (*CleanupPassDecoder) DecodeQuad

func (d *CleanupPassDecoder) DecodeQuad(quadIndex int) (QuadData, error)

DecodeQuad decodes a single 2x2 quad of coefficients.

The quad decoding process:

  1. Use MEL to determine if the quad has any significant coefficients
  2. If significant, use VLC to decode the significance pattern
  3. For each significant coefficient, decode magnitude and sign
  4. Apply coefficients to the block

Parameters:

  • quadIndex: The index of the quad (0 to NumQuads-1)

Returns:

  • QuadData containing the decoded coefficients
  • An error if decoding fails

func (*CleanupPassDecoder) GetBlock

func (d *CleanupPassDecoder) GetBlock() *HTBlock

GetBlock returns the decoded HTBlock.

func (*CleanupPassDecoder) GetDecodedCoefficients

func (d *CleanupPassDecoder) GetDecodedCoefficients() []int32

GetDecodedCoefficients returns the decoded coefficient values. These can be passed to the wavelet inverse transform.

func (*CleanupPassDecoder) LastError

func (d *CleanupPassDecoder) LastError() error

LastError returns the last error encountered during decoding.

func (*CleanupPassDecoder) QuadsDecoded

func (d *CleanupPassDecoder) QuadsDecoded() int

QuadsDecoded returns the number of successfully decoded quads.

func (*CleanupPassDecoder) Reset

func (d *CleanupPassDecoder) Reset()

Reset resets the decoder state for decoding a new block.

func (*CleanupPassDecoder) SignificantQuads

func (d *CleanupPassDecoder) SignificantQuads() int

SignificantQuads returns the count of quads with significant coefficients.

type CodingPassType

type CodingPassType int

CodingPassType represents the type of coding pass in HTJ2K. HTJ2K uses a modified pass structure compared to standard EBCOT.

const (
	// PassHTSigProp is the HT Significance Propagation pass.
	// In HTJ2K, this pass is simplified compared to standard EBCOT
	// and processes significance information using the MEL coder.
	PassHTSigProp CodingPassType = iota

	// PassHTMagRef is the HT Magnitude Refinement pass.
	// This pass refines the magnitudes of already-significant coefficients
	// using simple binary coding rather than context-dependent MQ coding.
	PassHTMagRef

	// PassHTCleanup is the HT Cleanup pass.
	// The HTJ2K cleanup pass is significantly different from standard EBCOT:
	// - Processes coefficients in 2x2 quads rather than stripes
	// - Uses MEL for significance patterns
	// - Uses VLC for magnitude information
	// - Uses MagSgn for magnitude/sign bits
	// This redesign enables the ~10x speedup of HTJ2K.
	PassHTCleanup
)

func (CodingPassType) IsValid

func (p CodingPassType) IsValid() bool

IsValid returns true if the pass type is a valid HTJ2K pass.

func (CodingPassType) String

func (p CodingPassType) String() string

String returns a human-readable name for the coding pass type.

type HTBlock

type HTBlock struct {
	// Width is the block width in samples (1-64).
	Width int

	// Height is the block height in samples (1-64).
	Height int

	// Data holds the reconstructed coefficient values.
	// Stored in row-major order: Data[y*Width + x].
	Data []int32

	// State holds per-coefficient state flags.
	// Used during decoding to track significance and other properties.
	State []uint8

	// NumBitPlanes is the number of significant bit planes.
	NumBitPlanes int

	// SubbandType indicates the wavelet subband (LL, HL, LH, HH).
	SubbandType SubbandType

	// ZeroBitPlanes is the number of leading zero bit planes
	// (from the packet header, not coded).
	ZeroBitPlanes int
}

HTBlock represents an HTJ2K code-block. This is the fundamental unit for HTJ2K block decoding.

func NewHTBlock

func NewHTBlock(width, height int, subbandType SubbandType) (*HTBlock, error)

NewHTBlock creates a new HTJ2K code-block with validated dimensions.

func (*HTBlock) ClearVisited

func (b *HTBlock) ClearVisited()

ClearVisited clears the visited flag for all coefficients.

func (*HTBlock) GetQuadCoord

func (b *HTBlock) GetQuadCoord(i int) QuadCoord

GetQuadCoord returns the top-left coordinate for quad index i. Quads are ordered in raster scan order (left-to-right, top-to-bottom).

func (*HTBlock) GetSign

func (b *HTBlock) GetSign(x, y int) bool

GetSign returns true if the coefficient at (x, y) is negative.

func (*HTBlock) InBounds

func (b *HTBlock) InBounds(x, y int) bool

InBounds checks if coordinate (x, y) is within block bounds.

func (*HTBlock) Index

func (b *HTBlock) Index(x, y int) int

Index returns the linear array index for coordinate (x, y).

func (*HTBlock) IsSignificant

func (b *HTBlock) IsSignificant(x, y int) bool

IsSignificant returns true if the coefficient at (x, y) is significant.

func (*HTBlock) NumQuads

func (b *HTBlock) NumQuads() int

NumQuads returns the total number of 2x2 quads in the block.

func (*HTBlock) NumQuadsX

func (b *HTBlock) NumQuadsX() int

NumQuadsX returns the number of 2x2 quads horizontally.

func (*HTBlock) NumQuadsY

func (b *HTBlock) NumQuadsY() int

NumQuadsY returns the number of 2x2 quads vertically.

func (*HTBlock) Reset

func (b *HTBlock) Reset()

Reset clears all data and state flags in the block.

func (*HTBlock) SetSign

func (b *HTBlock) SetSign(x, y int, negative bool)

SetSign sets the sign of the coefficient at (x, y). If negative is true, the coefficient is marked as negative.

func (*HTBlock) SetSignificant

func (b *HTBlock) SetSignificant(x, y int)

SetSignificant marks the coefficient at (x, y) as significant.

type HTBlockData

type HTBlockData struct {
	// MEL contains the MEL-encoded significance data.
	MEL *MELSegment

	// VLC contains the VLC-encoded magnitude data.
	VLC *VLCSegment

	// MagSgn contains the raw magnitude and sign bits.
	MagSgn *MagSgnSegment

	// NumPasses is the number of coding passes included.
	NumPasses int

	// Passes contains metadata for each coding pass.
	Passes []HTCodingPass
}

HTBlockData represents the complete encoded data for an HTJ2K code-block. The data is organized into three segments: MEL, VLC, and MagSgn.

func NewHTBlockData

func NewHTBlockData(data []byte, numPasses int) (*HTBlockData, error)

NewHTBlockData creates a new HTBlockData structure from raw encoded data. The data is parsed to extract the three segments based on the HTJ2K format.

type HTBlockDecoder

type HTBlockDecoder struct {
	// contains filtered or unexported fields
}

HTBlockDecoder provides a high-level interface for HTJ2K block decoding. It combines MEL, VLC, and cleanup pass decoding into a single operation.

func NewHTBlockDecoder

func NewHTBlockDecoder(width, height int, subbandType SubbandType, numBitPlanes, zeroBitPlanes int) (*HTBlockDecoder, error)

NewHTBlockDecoder creates a new HTJ2K block decoder.

Parameters:

  • width: Block width in samples (1-64)
  • height: Block height in samples (1-64)
  • subbandType: The wavelet subband type
  • numBitPlanes: Number of significant bit planes
  • zeroBitPlanes: Number of leading zero bit planes

func (*HTBlockDecoder) DecodeBlock

func (d *HTBlockDecoder) DecodeBlock(data []byte) ([]int32, error)

DecodeBlock decodes an HTJ2K code-block from encoded data.

Parameters:

  • data: The encoded block data (contains MEL, VLC, and MagSgn segments)

Returns:

  • Decoded coefficient values as a slice
  • An error if decoding fails

type HTCodingPass

type HTCodingPass struct {
	// Type is the coding pass type (SigProp, MagRef, or Cleanup).
	Type CodingPassType

	// BitPlane is the bit plane being coded in this pass (MSB = highest value).
	BitPlane int

	// NumBytes is the number of bytes used for this pass.
	NumBytes int

	// Truncated indicates if this pass was truncated for rate control.
	Truncated bool
}

HTCodingPass represents a single HTJ2K coding pass with associated metadata.

type HTJ2KDecoder

type HTJ2KDecoder struct {
	// contains filtered or unexported fields
}

HTJ2KDecoder provides HTJ2K block decoding as a drop-in replacement for standard EBCOT Tier-1 decoding.

func NewHTJ2KDecoder

func NewHTJ2KDecoder() *HTJ2KDecoder

NewHTJ2KDecoder creates a new HTJ2K decoder. It analyzes the codestream markers to determine if HTJ2K mode should be used.

func (*HTJ2KDecoder) DecodeBlock

func (d *HTJ2KDecoder) DecodeBlock(data []byte, width, height int, subbandType SubbandType, numBitPlanes, zeroBitPlanes int) ([]int32, error)

DecodeBlock decodes a code-block using HTJ2K or standard EBCOT. If HTJ2K mode is detected, it uses the high-throughput decoder. Otherwise, it returns nil to indicate standard EBCOT should be used.

Parameters:

  • data: The encoded code-block data
  • width: Block width in samples
  • height: Block height in samples
  • subbandType: The wavelet subband type
  • numBitPlanes: Number of significant bit planes
  • zeroBitPlanes: Number of leading zero bit planes

Returns:

  • Decoded coefficients if HTJ2K mode, nil otherwise
  • An error if decoding fails

func (*HTJ2KDecoder) DetectHTJ2K

func (d *HTJ2KDecoder) DetectHTJ2K(data []byte) bool

DetectHTJ2K scans marker data to detect if HTJ2K mode is used. This searches for a CAP marker and checks for bit 14 in Pcap.

Parameters:

  • data: The codestream header data to scan

Returns:

  • true if HTJ2K is detected

func (*HTJ2KDecoder) IsHTJ2KEnabled

func (d *HTJ2KDecoder) IsHTJ2KEnabled() bool

IsHTJ2KEnabled returns true if HTJ2K mode is detected and enabled.

func (*HTJ2KDecoder) SetCAPMarker

func (d *HTJ2KDecoder) SetCAPMarker(cap *CAPMarkerData)

SetCAPMarker sets the CAP marker data to enable HTJ2K detection.

type HTJ2KMetrics

type HTJ2KMetrics struct {
	// BlocksDecoded is the total number of blocks decoded
	BlocksDecoded int

	// CoefficientsDecoded is the total number of coefficients
	CoefficientsDecoded int64

	// SignificantQuads is the total number of significant quads
	SignificantQuads int

	// TotalQuads is the total number of quads processed
	TotalQuads int

	// BytesProcessed is the total bytes of encoded data processed
	BytesProcessed int64
}

HTJ2KMetrics tracks performance metrics for HTJ2K decoding.

func NewHTJ2KMetrics

func NewHTJ2KMetrics() *HTJ2KMetrics

NewHTJ2KMetrics creates a new metrics tracker.

func (*HTJ2KMetrics) BytesPerCoefficient

func (m *HTJ2KMetrics) BytesPerCoefficient() float64

BytesPerCoefficient returns the average encoded bytes per coefficient.

func (*HTJ2KMetrics) RecordBlock

func (m *HTJ2KMetrics) RecordBlock(width, height int, dataLen int, significantQuads, totalQuads int)

RecordBlock records metrics for a decoded block.

func (*HTJ2KMetrics) SparsityRatio

func (m *HTJ2KMetrics) SparsityRatio() float64

SparsityRatio returns the ratio of non-significant to total quads. A higher ratio indicates more compressible data.

type MELBlockDecoder

type MELBlockDecoder struct {
	*MELDecoder
	// contains filtered or unexported fields
}

MELBlockDecoder extends MELDecoder with block-level functionality. It maintains state for decoding an entire HTJ2K code-block.

func NewMELBlockDecoder

func NewMELBlockDecoder(data []byte, numQuadsX, numQuadsY int) (*MELBlockDecoder, error)

NewMELBlockDecoder creates a MEL decoder for an entire HTJ2K block.

Parameters:

  • data: The MEL-encoded segment data
  • numQuadsX: Number of quads horizontally
  • numQuadsY: Number of quads vertically

func (*MELBlockDecoder) CountSignificant

func (d *MELBlockDecoder) CountSignificant() int

CountSignificant returns the number of significant quads in the block.

func (*MELBlockDecoder) DecodeBlock

func (d *MELBlockDecoder) DecodeBlock() ([]bool, error)

DecodeBlock decodes significance for all quads in the block. Returns the significance map indexed by quad position (y*numQuadsX + x).

func (*MELBlockDecoder) IsSignificant

func (d *MELBlockDecoder) IsSignificant(quadX, quadY int) bool

IsSignificant checks if a specific quad is significant. Coordinates are in quad units (not pixel units).

type MELDecoder

type MELDecoder struct {
	// contains filtered or unexported fields
}

MELDecoder handles decoding of MEL-encoded significance data. MEL (Magnitude-Exponent-Length) uses context-adaptive run-length coding to encode whether each 2x2 quad contains any significant coefficients.

func NewMELDecoder

func NewMELDecoder(data []byte) *MELDecoder

NewMELDecoder creates a new MEL decoder for the given encoded data. The data should contain MEL-encoded significance information extracted from an HTJ2K code-block.

func (*MELDecoder) BitsRemaining

func (d *MELDecoder) BitsRemaining() int

BitsRemaining returns the number of unread bits remaining in the data.

func (*MELDecoder) DecodeMultipleSignificance

func (d *MELDecoder) DecodeMultipleSignificance(count int) ([]bool, error)

DecodeMultipleSignificance decodes significance for multiple quads. This is a convenience method for batch decoding.

Parameters:

  • count: Number of quads to decode

Returns:

  • A slice of boolean values indicating significance for each quad
  • An error if decoding fails

func (*MELDecoder) DecodeSignificance

func (d *MELDecoder) DecodeSignificance() (bool, error)

DecodeSignificance decodes the significance of the next 2x2 quad. Returns true if the quad contains any significant coefficients, false if all coefficients in the quad are zero.

This is the main interface for MEL decoding in the HTJ2K cleanup pass. It manages run-length state and context adaptation internally.

func (*MELDecoder) GetContext

func (d *MELDecoder) GetContext() int

GetContext returns the current MEL context state. This is useful for debugging and testing.

func (*MELDecoder) Reset

func (d *MELDecoder) Reset()

Reset resets the MEL decoder state for re-decoding. This clears the context, bit position, and run counter.

func (*MELDecoder) SetContext

func (d *MELDecoder) SetContext(ctx int) error

SetContext sets the MEL context state. This should only be used for testing or special cases.

type MELSegment

type MELSegment struct {
	// Data contains the MEL encoded bitstream.
	Data []byte

	// Length is the number of valid bytes in Data.
	Length int

	// Context is the current MEL context state (0-7).
	Context int

	// RunLength is the current run length being decoded.
	RunLength int

	// BitPosition is the current bit position within the byte stream.
	BitPosition int

	// BytePosition is the current byte position in Data.
	BytePosition int
}

MELSegment represents a MEL (Magnitude and Sign Length) encoded segment. MEL coding uses context-adaptive run-length coding to efficiently encode the significance information for coefficients.

func NewMELSegment

func NewMELSegment(data []byte) *MELSegment

NewMELSegment creates a new MEL segment from encoded data.

func (*MELSegment) Reset

func (m *MELSegment) Reset()

Reset resets the MEL segment state for re-decoding.

type MagSgnSegment

type MagSgnSegment struct {
	// Data contains the raw magnitude and sign bits.
	Data []byte

	// Length is the number of valid bytes in Data.
	Length int

	// BitPosition is the current bit position for reading.
	BitPosition int

	// BytePosition is the current byte position in Data.
	BytePosition int

	// BitsRemaining tracks remaining bits for bounds checking.
	BitsRemaining int
}

MagSgnSegment represents a MagSgn (Magnitude and Sign) raw data segment. This segment contains the raw magnitude and sign bits for coefficients after VLC decoding provides the base magnitude information.

func NewMagSgnSegment

func NewMagSgnSegment(data []byte) *MagSgnSegment

NewMagSgnSegment creates a new MagSgn segment from raw data.

func (*MagSgnSegment) Reset

func (m *MagSgnSegment) Reset()

Reset resets the MagSgn segment state for re-reading.

type QuadCoord

type QuadCoord struct {
	X int
	Y int
}

QuadCoord represents the top-left coordinate of a 2x2 quad.

type QuadData

type QuadData struct {
	// Significance is the 4-bit significance pattern.
	Significance SignificancePattern

	// Magnitudes holds the magnitude values for each coefficient (0-3).
	Magnitudes [QuadSize]int32

	// Signs holds the sign bits for each coefficient (true = negative).
	Signs [QuadSize]bool
}

QuadData holds the decoded data for a single 2x2 quad.

func ReconstructQuad

func ReconstructQuad(significance SignificancePattern, magnitudes [QuadSize]int32, signs [QuadSize]bool) QuadData

ReconstructQuad combines significance, magnitudes, and signs into QuadData.

Parameters:

  • significance: The significance pattern
  • magnitudes: Decoded magnitude values
  • signs: Decoded sign bits

Returns:

  • Complete QuadData structure

func (*QuadData) ApplyToBlock

func (q *QuadData) ApplyToBlock(block *HTBlock, x, y int)

ApplyToBlock writes the quad data to the HTBlock at the specified position.

func (*QuadData) IsEmpty

func (q *QuadData) IsEmpty() bool

IsEmpty returns true if no coefficients in the quad are significant.

type SignificancePattern

type SignificancePattern uint8

SignificancePattern represents the significance pattern for a 2x2 quad. The pattern is a 4-bit value where each bit indicates if the corresponding coefficient in the quad is significant.

const (
	// SigPatternBit0 is the significance bit for position (0,0) in the quad.
	SigPatternBit0 SignificancePattern = 1 << 0
	// SigPatternBit1 is the significance bit for position (1,0) in the quad.
	SigPatternBit1 SignificancePattern = 1 << 1
	// SigPatternBit2 is the significance bit for position (0,1) in the quad.
	SigPatternBit2 SignificancePattern = 1 << 2
	// SigPatternBit3 is the significance bit for position (1,1) in the quad.
	SigPatternBit3 SignificancePattern = 1 << 3
)

Quad coefficient positions in the significance pattern:

+---+---+
| 0 | 1 |
+---+---+
| 2 | 3 |
+---+---+

func (SignificancePattern) Count

func (p SignificancePattern) Count() int

Count returns the number of significant coefficients in the pattern.

func (SignificancePattern) IsSet

func (p SignificancePattern) IsSet(i int) bool

IsSet returns true if the bit at position i is set.

type SubbandType

type SubbandType int

SubbandType represents the wavelet subband orientation.

const (
	// SubbandLL is the low-low frequency subband (approximation).
	SubbandLL SubbandType = iota
	// SubbandHL is the high-low frequency subband (horizontal detail).
	SubbandHL
	// SubbandLH is the low-high frequency subband (vertical detail).
	SubbandLH
	// SubbandHH is the high-high frequency subband (diagonal detail).
	SubbandHH
)

func (SubbandType) String

func (s SubbandType) String() string

String returns the subband name.

type VLCBlockDecoder

type VLCBlockDecoder struct {
	*VLCDecoder
	// contains filtered or unexported fields
}

VLCBlockDecoder extends VLCDecoder with block-level functionality. It maintains state for decoding an entire HTJ2K code-block's VLC segment.

func NewVLCBlockDecoder

func NewVLCBlockDecoder(data []byte, numQuadsX, numQuadsY int) (*VLCBlockDecoder, error)

NewVLCBlockDecoder creates a VLC decoder for an entire HTJ2K block.

Parameters:

  • data: The VLC-encoded segment data
  • numQuadsX: Number of quads horizontally
  • numQuadsY: Number of quads vertically

func (*VLCBlockDecoder) DecodeQuadMagnitudes

func (d *VLCBlockDecoder) DecodeQuadMagnitudes(significance SignificancePattern, magnitudeBits int) (
	[QuadSize]int32, [QuadSize]bool, error)

DecodeQuadMagnitudes decodes magnitudes for all coefficients in a quad. Takes the significance pattern and returns magnitudes for significant coefficients.

Parameters:

  • significance: The 4-bit significance pattern from MEL decoder
  • magnitudeBits: Number of bits per magnitude

Returns:

  • Array of 4 magnitudes (0 for non-significant coefficients)
  • Array of 4 sign bits (false for non-significant coefficients)
  • An error if decoding fails

func (*VLCBlockDecoder) Stats

func (d *VLCBlockDecoder) Stats() (symbols, magnitudes, signs int)

Stats returns decoding statistics for debugging.

type VLCDecoder

type VLCDecoder struct {
	// contains filtered or unexported fields
}

VLCDecoder handles decoding of VLC-encoded magnitude data in HTJ2K. VLC (Variable Length Coding) uses pre-computed lookup tables for efficient O(1) decoding of coefficient magnitudes.

func NewVLCDecoder

func NewVLCDecoder(data []byte) *VLCDecoder

NewVLCDecoder creates a new VLC decoder for the given encoded data. The data should contain VLC-encoded magnitude information extracted from an HTJ2K code-block.

func (*VLCDecoder) BitsRemaining

func (d *VLCDecoder) BitsRemaining() int

BitsRemaining returns the number of unread bits remaining in the data.

func (*VLCDecoder) ConsumeBits

func (d *VLCDecoder) ConsumeBits(n int)

ConsumeBits advances the bit position by n bits without returning the value. This is used after a successful lookup to move past the consumed code.

func (*VLCDecoder) DecodeMagnitude

func (d *VLCDecoder) DecodeMagnitude(numBits int) (int32, error)

DecodeMagnitude reads the specified number of magnitude bits. Returns the magnitude value as int32.

Parameters:

  • numBits: Number of magnitude bits to read (0 to MaxVLCCodeLength)

Returns:

  • The magnitude value
  • An error if reading fails or numBits is invalid

func (*VLCDecoder) DecodeSignBit

func (d *VLCDecoder) DecodeSignBit() (bool, error)

DecodeSignBit reads a single sign bit. Returns true if the coefficient is negative.

func (*VLCDecoder) DecodeSignBits

func (d *VLCDecoder) DecodeSignBits(numCoeffs int) ([]bool, error)

DecodeSignBits reads sign bits for multiple coefficients. Returns a slice of boolean values where true = negative.

Parameters:

  • numCoeffs: Number of coefficients needing sign bits (0 to QuadSize)

Returns:

  • Slice of sign values (true = negative, false = positive)
  • An error if reading fails or numCoeffs is invalid

func (*VLCDecoder) LookupSymbol

func (d *VLCDecoder) LookupSymbol() (symbol int, codeLength int, err error)

LookupSymbol performs a VLC table lookup to decode the next symbol. Returns the decoded symbol, the code length, and any error.

The symbol represents a 4-bit significance pattern for a 2x2 quad:

  • Bit 0: coefficient at (0,0)
  • Bit 1: coefficient at (1,0)
  • Bit 2: coefficient at (0,1)
  • Bit 3: coefficient at (1,1)

func (*VLCDecoder) Reset

func (d *VLCDecoder) Reset()

Reset resets the VLC decoder state for re-decoding.

type VLCEntry

type VLCEntry struct {
	// Symbol is the decoded value (0-15 for significance patterns).
	Symbol int
	// Length is the number of bits consumed by this code.
	Length int
}

VLCEntry represents a single entry in the VLC lookup table. Each entry contains the decoded symbol and the code length.

type VLCSegment

type VLCSegment struct {
	// Data contains the VLC encoded bitstream.
	Data []byte

	// Length is the number of valid bytes in Data.
	Length int

	// BitPosition is the current bit position for reading.
	BitPosition int

	// BytePosition is the current byte position in Data.
	BytePosition int

	// BitsRemaining tracks remaining bits for bounds checking.
	BitsRemaining int
}

VLCSegment represents a VLC (Variable Length Coding) encoded segment. VLC coding provides fixed-rate coding for coefficient magnitude information.

func NewVLCSegment

func NewVLCSegment(data []byte) *VLCSegment

NewVLCSegment creates a new VLC segment from encoded data.

func (*VLCSegment) Reset

func (v *VLCSegment) Reset()

Reset resets the VLC segment state for re-decoding.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL