jpegxs

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: 8 Imported by: 0

Documentation

Overview

Package jpegxs provides JPEG XS (ISO/IEC 21122) codestream decoding. This file implements the public API for JPEG XS decoding.

JPEG XS is designed for low-latency, visually lossless compression for professional video applications. It features:

  • Sub-line latency for real-time streaming
  • Bounded memory usage for hardware implementation
  • 5/3 reversible wavelet for lossless mode
  • Multiple profiles (Main, High, Light, Light 444.12)

Task Group 2.6: JPEG XS - Integration

Package jpegxs provides JPEG XS (ISO/IEC 21122) decoding and encoding support.

JPEG XS is a visually lossless, low-latency image compression standard designed for applications requiring real-time image transport with minimal processing delay. It achieves sub-line latency through line-based wavelet processing and bounded memory usage, making it ideal for professional video production, virtual reality, and high-bandwidth applications.

Profiles

JPEG XS defines several profiles for different use cases:

  • Main Profile (broadcast): Standard profile for broadcast applications
  • High Profile: Extended capabilities for higher quality requirements
  • Light Profile: Reduced complexity for resource-constrained environments
  • Light 444.12 Subprofile: Light profile variant for 4:4:4 content at 12-bit depth

Low-Latency Architecture

JPEG XS achieves low latency through several design choices:

  • Line-based wavelet transform (5/3 reversible)
  • Bounded memory model (limited line buffers per subband)
  • Simple entropy coding (significance and run-length)
  • Deterministic rate control

The codec is designed for sub-frame latency, typically achieving encoding and decoding delays of less than one video line.

Codestream Structure

A JPEG XS codestream consists of marker segments:

  • SOC (Start of Codestream): Marks the beginning of the codestream
  • CAP (Capabilities): Indicates profile, level, and sublevel
  • PIH (Picture Header): Contains image dimensions and component info
  • CDT (Component Table): Defines component sampling and precision
  • WGT (Weight Table): Contains weighting factors for entropy coding
  • COM (Comment): Optional comment data
  • SLH (Slice Header): Marks the start of each slice
  • EOC (End of Codestream): Marks the end of the codestream

Transport Formats (Part 3)

JPEG XS supports multiple transport formats per ISO/IEC 21122-3:

  • Raw codestream (.jxs files)
  • ISO base media file format (ISOBMFF/MP4)
  • RTP payload format for network streaming

Security Considerations

This package enforces security limits defined in the security package:

  • Maximum wavelet levels (MaxWaveletLevels)
  • Maximum subband size (MaxSubbandSize)
  • Maximum line buffer size (MaxLineBufferSize)
  • Maximum marker segment length (MaxMarkerLength)

All integer conversions use the safeconv package to prevent overflow.

Standards Reference

This implementation follows:

  • ISO/IEC 21122-1: Core coding system
  • ISO/IEC 21122-2: Profiles and levels
  • ISO/IEC 21122-3: Transport and container formats
  • ISO/IEC 21122-4: Conformance testing
  • ISO/IEC 21122-5: Reference software

Usage

To decode a JPEG XS codestream:

decoder, err := jpegxs.NewDecoder(data)
if err != nil {
    // Handle error
}

// Decode the image
img, err := decoder.Decode()
if err != nil {
    // Handle error
}

// Or decode progressively (line-by-line) for minimum latency
for line := range decoder.DecodeProgressive() {
    // Process each line as it becomes available
}

Package jpegxs provides JPEG XS (ISO/IEC 21122) encoding support. This file implements the JPEG XS encoder for low-latency, visually lossless compression suitable for professional video applications.

JPEG XS is designed for:

  • Sub-line latency for real-time streaming
  • Bounded memory usage for hardware implementation
  • 5/3 reversible wavelet for lossless mode
  • Multiple profiles (Main, High, Light, Light 444.12)

Task Group 2.7: JPEG XS - Encoder

Package jpegxs provides JPEG XS (ISO/IEC 21122) entropy coding implementation. This file implements significance coding, run-length coding, and rate control per ISO/IEC 21122-1 and 21122-2. JPEG XS requires bounded complexity with O(1) operations per sample for real-time streaming applications.

Package jpegxs provides JPEG XS (ISO/IEC 21122) codestream parsing and decoding. This file implements the codestream marker parser for JPEG XS.

Package jpegxs provides JPEG XS (ISO/IEC 21122) wavelet transform implementation. This file implements the 5/3 reversible wavelet transform used in JPEG XS for lossless compression mode. JPEG XS uses line-based processing for sub-line latency.

ISO/IEC 21122 (JPEG-XS) specifies the same 5/3 integer lifting transform as ISO/IEC 15444-1 (JPEG 2000), Annex F.4.8.1. To guarantee a single audited implementation of the lifting steps, the 1-D analysis and synthesis filters delegate to internal/jpeg2000/wavelet.Transform53Impl. The 2-D wrappers and multi-level decomposition types defined here implement the JPEG-XS specific subband layout and security/validation requirements (bounded memory, line budget) while keeping the lifting math canonical.

Index

Constants

View Source
const (
	// MaxQuantizationParameter is the maximum QP value for rate control.
	MaxQuantizationParameter = 31

	// MinQuantizationParameter is the minimum QP value for rate control.
	MinQuantizationParameter = 1
)
View Source
const (
	// MarkerSOC is the Start of Codestream marker (0xFF10).
	// This marker has no parameters and marks the beginning of a JPEG XS codestream.
	MarkerSOC = 0xFF10

	// MarkerEOC is the End of Codestream marker (0xFF11).
	// This marker has no parameters and marks the end of a JPEG XS codestream.
	MarkerEOC = 0xFF11

	// MarkerPIH is the Picture Header marker (0xFF12).
	// Contains image dimensions, component count, and precision information.
	MarkerPIH = 0xFF12

	// MarkerCDT is the Component Table marker (0xFF13).
	// Defines component sampling factors and bit depths.
	MarkerCDT = 0xFF13

	// MarkerWGT is the Weight Table marker (0xFF14).
	// Contains weighting factors for entropy coding bands.
	MarkerWGT = 0xFF14

	// MarkerCOM is the Comment marker (0xFF15).
	// Contains optional comment data.
	MarkerCOM = 0xFF15

	// MarkerNLT is the Nonlinearity marker (0xFF16).
	// Defines nonlinear transfer function parameters.
	MarkerNLT = 0xFF16

	// MarkerCWD is the Component-Dependent Wavelet Decomposition marker (0xFF17).
	// Specifies per-component wavelet decomposition structure.
	MarkerCWD = 0xFF17

	// MarkerCTS is the Colour Transformation Specification marker (0xFF18).
	// Defines color space transformation parameters.
	MarkerCTS = 0xFF18

	// MarkerCRG is the Component Registration marker (0xFF19).
	// Specifies component registration offsets.
	MarkerCRG = 0xFF19

	// MarkerSLH is the Slice Header marker (0xFF20).
	// Marks the beginning of a slice and contains slice parameters.
	MarkerSLH = 0xFF20

	// MarkerCAP is the Capabilities marker (0xFF50).
	// Indicates profile, level, and sublevel of the codestream.
	MarkerCAP = 0xFF50
)

JPEG XS codestream marker codes per ISO/IEC 21122-1.

View Source
const MinCAPDataSize = 4

MinCAPDataSize is the minimum size of CAP marker data (excluding marker and length).

View Source
const MinCDTDataSize = 4

MinCDTDataSize is the minimum size of CDT marker data (excluding marker and length).

View Source
const MinPIHDataSize = 24

MinPIHDataSize is the minimum size of PIH marker data (excluding marker and length). This accounts for: Profile(2) + Level(2) + Width(4) + Height(4) + ComponentInfo(2) + WaveletLevels(2) + QuantStyle(1) + RefineFlag(1) + Fragmentation(2) + SliceHeight(2) + PrecinctWidth(2) = 24 bytes

View Source
const MinWGTDataSize = 3

MinWGTDataSize is the minimum size of WGT marker data (excluding marker and length).

Variables

View Source
var (
	// ErrInvalidCodestream indicates the codestream structure is malformed or invalid.
	ErrInvalidCodestream = errors.New("invalid JPEG XS codestream")

	// ErrMissingSOC indicates the Start of Codestream marker is missing.
	ErrMissingSOC = errors.New("missing SOC marker")

	// ErrMissingPIH indicates the Picture Header is missing.
	ErrMissingPIH = errors.New("missing PIH marker")

	// ErrInvalidProfile indicates the profile indicator is not recognized.
	ErrInvalidProfile = errors.New("invalid JPEG XS profile indicator")

	// ErrUnsupportedProfile indicates the profile is recognized but not supported.
	ErrUnsupportedProfile = errors.New("unsupported JPEG XS profile")

	// ErrInvalidLevel indicates the level indicator is not recognized.
	ErrInvalidLevel = errors.New("invalid JPEG XS level indicator")

	// ErrUnsupportedLevel indicates the level is recognized but not supported.
	ErrUnsupportedLevel = errors.New("unsupported JPEG XS level")

	// ErrTruncatedCodestream indicates the codestream data is incomplete.
	ErrTruncatedCodestream = errors.New("truncated codestream data")

	// ErrInvalidMarker indicates an unrecognized or malformed marker segment.
	ErrInvalidMarker = errors.New("invalid marker segment")

	// ErrMarkerLengthExceeded indicates a marker segment length exceeds limits.
	ErrMarkerLengthExceeded = errors.New("marker segment length exceeds maximum")

	// ErrInvalidCAP indicates the Capabilities marker is malformed.
	ErrInvalidCAP = errors.New("invalid CAP marker")

	// ErrInvalidCDT indicates the Component Table marker is malformed.
	ErrInvalidCDT = errors.New("invalid CDT marker")

	// ErrInvalidWGT indicates the Weight Table marker is malformed.
	ErrInvalidWGT = errors.New("invalid WGT marker")

	// ErrInvalidSlice indicates a slice header or data is malformed.
	ErrInvalidSlice = errors.New("invalid slice data")

	// ErrWaveletLevelExceeded indicates wavelet decomposition levels exceed limits.
	ErrWaveletLevelExceeded = errors.New("wavelet decomposition level exceeds maximum")

	// ErrSubbandSizeExceeded indicates a subband size exceeds maximum limits.
	ErrSubbandSizeExceeded = errors.New("subband size exceeds maximum")

	// ErrLineBufferExceeded indicates line buffer requirements exceed limits.
	ErrLineBufferExceeded = errors.New("line buffer size exceeds maximum")

	// ErrEntropyDecodingFailed indicates entropy decoding encountered an error.
	ErrEntropyDecodingFailed = errors.New("entropy decoding failed")

	// ErrRateControlFailed indicates rate control parameters are invalid.
	ErrRateControlFailed = errors.New("rate control parameters invalid")

	// ErrInvalidPrecinct indicates precinct parameters are invalid.
	ErrInvalidPrecinct = errors.New("invalid precinct parameters")

	// ErrInvalidQuantization indicates quantization parameters are invalid.
	ErrInvalidQuantization = errors.New("invalid quantization parameters")

	// ErrContainerFormatError indicates an error in the container format.
	ErrContainerFormatError = errors.New("container format error")

	// ErrFrameExtractionFailed indicates failure to extract a frame from container.
	ErrFrameExtractionFailed = errors.New("frame extraction failed")

	// ErrTimingInfoMissing indicates required timing information is missing.
	ErrTimingInfoMissing = errors.New("timing information missing")

	// ErrUnsupportedBitDepth indicates the bit depth is not supported.
	ErrUnsupportedBitDepth = errors.New("unsupported bit depth")

	// ErrUnsupportedSampling indicates the chroma sampling is not supported.
	ErrUnsupportedSampling = errors.New("unsupported chroma sampling")

	// ErrBufferModelViolation indicates the buffer model constraints are violated.
	ErrBufferModelViolation = errors.New("buffer model violation")
)

JPEG XS specific errors. These errors correspond to translation keys in locales/en-US.json under jpeg.jpegxs.error.*

Functions

func DetectJPEGXS

func DetectJPEGXS(data []byte) bool

DetectJPEGXS checks if the data starts with JPEG XS SOC marker.

func GetMarkerName

func GetMarkerName(marker uint16) string

GetMarkerName returns a human-readable name for a JPEG XS marker.

Types

type BandWeight

type BandWeight struct {
	// Weight is the weighting factor for this band.
	Weight uint8

	// Band identifies which wavelet subband this weight applies to.
	Band uint8
}

BandWeight defines the weight for a single band in entropy coding.

type BoundedWaveletAllocator

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

BoundedWaveletAllocator manages memory allocation with security limits.

func NewBoundedWaveletAllocator

func NewBoundedWaveletAllocator(width, height, levels int) (*BoundedWaveletAllocator, error)

NewBoundedWaveletAllocator creates a new bounded memory allocator.

func (*BoundedWaveletAllocator) AllocateLineBuffer

func (a *BoundedWaveletAllocator) AllocateLineBuffer() ([]int32, error)

AllocateLineBuffer allocates a line buffer with security validation.

func (*BoundedWaveletAllocator) AllocateSubbandBuffer

func (a *BoundedWaveletAllocator) AllocateSubbandBuffer(level int) ([]int32, error)

AllocateSubbandBuffer allocates a subband buffer for the given level.

func (*BoundedWaveletAllocator) EstimatedMemory

func (a *BoundedWaveletAllocator) EstimatedMemory() int64

EstimatedMemory returns the estimated memory usage in bytes.

func (*BoundedWaveletAllocator) Release

func (a *BoundedWaveletAllocator) Release()

Release releases all allocated buffers.

type BufferModel

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

BufferModel implements the bounded buffer model per ISO/IEC 21122-2. This ensures bounded latency and memory for real-time streaming.

func NewBufferModel

func NewBufferModel(bufferSize int, targetBitrate int64) *BufferModel

NewBufferModel creates a new buffer model.

func (*BufferModel) AddSlice

func (b *BufferModel) AddSlice(bits int) error

AddSlice adds bits from an encoded slice to the buffer. Returns an error if buffer overflow would occur.

func (*BufferModel) DrainBits

func (b *BufferModel) DrainBits(bits int)

DrainBits removes bits from the buffer (simulating transmission).

func (*BufferModel) Fullness

func (b *BufferModel) Fullness() float64

Fullness returns the current buffer fullness as a ratio [0, 1].

func (*BufferModel) Size

func (b *BufferModel) Size() int

Size returns the buffer size in bits.

type CAP

type CAP struct {
	// Length is the total length of the CAP marker segment (excluding marker bytes).
	Length uint16

	// Profile indicates the JPEG XS profile.
	Profile Profile

	// Level indicates the JPEG XS level (maximum dimensions).
	Level Level

	// Sublevel indicates additional constraints.
	Sublevel Sublevel

	// RawBytes contains the raw capability bytes for extended parsing.
	RawBytes []byte
}

CAP represents the Capabilities marker segment. This marker indicates the profile, level, and sublevel of the codestream.

func (*CAP) Validate

func (c *CAP) Validate() error

Validate checks that the CAP marker values are valid.

type CDT

type CDT struct {
	// Length is the total length of the CDT marker segment.
	Length uint16

	// Components contains the definition for each component.
	Components []ComponentDefinition
}

CDT represents the Component Table marker segment. This marker defines the sampling factors and bit depths for each component.

func (*CDT) Validate

func (c *CDT) Validate() error

Validate checks that CDT values are within acceptable ranges.

type COM

type COM struct {
	// Length is the total length of the COM marker segment.
	Length uint16

	// RegistrationType indicates the type of comment (Tcom).
	// 0 = general purpose ISO 8859-15 (Latin)
	// 1 = general purpose UTF-8
	RegistrationType uint16

	// Data contains the comment text or binary data.
	Data []byte
}

COM represents the Comment marker segment. This marker contains optional comment data.

func (*COM) Validate

func (c *COM) Validate() error

Validate checks that COM values are within acceptable ranges.

type ChromaSampling

type ChromaSampling uint8

ChromaSampling defines the chroma subsampling mode.

const (
	// ChromaSamplingUnknown indicates unknown chroma sampling.
	ChromaSamplingUnknown ChromaSampling = 0

	// ChromaSampling444 indicates no chroma subsampling (4:4:4).
	ChromaSampling444 ChromaSampling = 1

	// ChromaSampling422 indicates horizontal subsampling (4:2:2).
	ChromaSampling422 ChromaSampling = 2

	// ChromaSampling420 indicates horizontal and vertical subsampling (4:2:0).
	ChromaSampling420 ChromaSampling = 3
)

func (ChromaSampling) String

func (c ChromaSampling) String() string

String returns a human-readable name for the chroma sampling.

type ComponentDefinition

type ComponentDefinition struct {
	// BitDepth is the bit depth of this component (Bc).
	BitDepth uint8

	// SamplingX is the horizontal sampling factor (Sx).
	SamplingX uint8

	// SamplingY is the vertical sampling factor (Sy).
	SamplingY uint8

	// Signed indicates if the component values are signed.
	Signed bool
}

ComponentDefinition defines the properties of a single image component.

type Decoder

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

Decoder handles decoding of JPEG XS codestreams. It implements low-latency, line-based decoding per ISO/IEC 21122.

func NewDecoder

func NewDecoder(data []byte) (*Decoder, error)

NewDecoder creates a new JPEG XS decoder for the given codestream data. The data must start with the SOC marker (0xFF10).

func NewDecoderWithOptions

func NewDecoderWithOptions(data []byte, options *DecoderOptions) (*Decoder, error)

NewDecoderWithOptions creates a new JPEG XS decoder with custom options.

func (*Decoder) Decode

func (d *Decoder) Decode() ([]byte, error)

Decode decodes the JPEG XS codestream and returns the decoded pixel data. The output is a flat slice of samples in component-interleaved order. For 8-bit images, use []uint8; for 10-12 bit, values are in []uint16.

func (*Decoder) DecodeProgressive

func (d *Decoder) DecodeProgressive(callback func(lineNumber int, data []byte) error) error

DecodeProgressive decodes the JPEG XS codestream progressively, calling the callback for each decoded line. This enables low-latency streaming applications.

func (*Decoder) DecodeToImage

func (d *Decoder) DecodeToImage() (image.Image, error)

DecodeToImage decodes the JPEG XS codestream and returns a Go image.Image.

func (*Decoder) GetInfo

func (d *Decoder) GetInfo() *ImageInfo

GetInfo returns information about the decoded image.

func (*Decoder) GetLatencyLines

func (d *Decoder) GetLatencyLines() int

GetLatencyLines returns the latency in lines for progressive decoding. JPEG XS is designed for sub-line latency.

func (*Decoder) GetLevel

func (d *Decoder) GetLevel() Level

GetLevel returns the JPEG XS level.

func (*Decoder) GetMemoryBound

func (d *Decoder) GetMemoryBound() int64

GetMemoryBound returns the maximum memory usage in bytes. JPEG XS has bounded memory requirements for real-time applications.

func (*Decoder) GetProfile

func (d *Decoder) GetProfile() Profile

GetProfile returns the JPEG XS profile.

func (*Decoder) IsLossless

func (d *Decoder) IsLossless() bool

IsLossless returns true if the codestream uses lossless compression.

func (*Decoder) IsLowLatency

func (d *Decoder) IsLowLatency() bool

IsLowLatency returns true if the decoder is configured for low-latency mode.

type DecoderOptions

type DecoderOptions struct {
	// IgnoreWarnings if true, continues decoding despite non-fatal warnings.
	IgnoreWarnings bool

	// ValidateChecksums if true, validates any embedded checksums.
	ValidateChecksums bool

	// LowLatencyMode if true, prioritizes latency over memory efficiency.
	LowLatencyMode bool

	// MaxLineBuffers limits the number of line buffers (0 = default).
	MaxLineBuffers int

	// TargetBitDepth specifies the output bit depth (0 = native).
	TargetBitDepth int
}

DecoderOptions configures the JPEG XS decoder behavior.

func DefaultDecoderOptions

func DefaultDecoderOptions() *DecoderOptions

DefaultDecoderOptions returns the default decoder options.

type Encoder

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

Encoder handles encoding of image data to JPEG XS codestreams. It supports 8/10/12-bit input with configurable target bitrate.

func NewEncoder

func NewEncoder(opts ...EncoderOption) *Encoder

NewEncoder creates a new JPEG XS encoder with the given options.

func (*Encoder) Configure

func (e *Encoder) Configure(width, height, componentCount int) error

Configure sets the image dimensions and validates parameters. Must be called before encoding.

func (*Encoder) CountEntropyOperations

func (e *Encoder) CountEntropyOperations(coeffs []int32) int

CountEntropyOperations returns the operation count for encoding coefficients. Used for verifying O(1) complexity per sample.

func (*Encoder) Encode

func (e *Encoder) Encode(w io.Writer, input []byte) error

Encode encodes the input image to JPEG XS format.

func (*Encoder) EncodeCoefficients

func (e *Encoder) EncodeCoefficients(coeffs []int32) ([]byte, error)

EncodeCoefficients encodes wavelet coefficients to a bounded bitstream.

func (*Encoder) ForwardWaveletTransform

func (e *Encoder) ForwardWaveletTransform(input []byte) (*SubbandData, error)

ForwardWaveletTransform performs the forward 5/3 wavelet transform. Uses line-based processing for low latency.

func (*Encoder) GetBitsPerPixel

func (e *Encoder) GetBitsPerPixel(encodedSize int) float64

GetBitsPerPixel returns the actual bits per pixel after encoding.

func (*Encoder) GetLatencyLines

func (e *Encoder) GetLatencyLines() int

GetLatencyLines returns the latency in lines for encoding.

func (*Encoder) GetMemoryBound

func (e *Encoder) GetMemoryBound() int64

GetMemoryBound returns the maximum memory usage in bytes.

func (*Encoder) GetSliceBitBudget

func (e *Encoder) GetSliceBitBudget() int

GetSliceBitBudget returns the target bits for the next slice.

func (*Encoder) GetSubbands

func (e *Encoder) GetSubbands() (*SubbandData, error)

GetSubbands returns the wavelet subbands after all lines are processed.

func (*Encoder) ProcessLine

func (e *Encoder) ProcessLine(lineNum int, data []byte) error

ProcessLine processes a single line for line-based encoding. Lines must be provided in order from top to bottom.

func (*Encoder) ReportSliceBits

func (e *Encoder) ReportSliceBits(bits int)

ReportSliceBits reports actual bits used for rate control adaptation.

func (*Encoder) ResetLineState

func (e *Encoder) ResetLineState()

ResetLineState resets the line processing state for new encoding.

type EncoderOption

type EncoderOption func(*Encoder)

EncoderOption is a functional option for configuring the encoder.

func WithBitDepth

func WithBitDepth(depth int) EncoderOption

WithBitDepth sets the input bit depth (8, 10, 12).

func WithLowLatencyMode

func WithLowLatencyMode(enabled bool) EncoderOption

WithLowLatencyMode enables low-latency encoding mode.

func WithProfile

func WithProfile(profile Profile) EncoderOption

WithProfile sets the JPEG XS profile.

func WithTargetBitrate

func WithTargetBitrate(bitrate int64) EncoderOption

WithTargetBitrate sets the target bitrate in bits per second.

type EntropyDecoder

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

EntropyDecoder combines significance decoding, run-length decoding, and magnitude decoding for complete entropy decoding.

func NewEntropyDecoder

func NewEntropyDecoder() *EntropyDecoder

NewEntropyDecoder creates a new entropy decoder.

func (*EntropyDecoder) DecodeCoefficients

func (d *EntropyDecoder) DecodeCoefficients(data []byte, numCoeffs int, bitDepth int) ([]int32, error)

DecodeCoefficients decodes a byte stream to wavelet coefficients.

type EntropyEncoder

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

EntropyEncoder combines significance coding, run-length coding, and magnitude coding for complete entropy encoding of wavelet coefficients.

func NewEntropyEncoder

func NewEntropyEncoder() *EntropyEncoder

NewEntropyEncoder creates a new entropy encoder.

func (*EntropyEncoder) CountOperations

func (e *EntropyEncoder) CountOperations(coeffs []int32) int

CountOperations returns the operation count for the last encode call. Used for verifying O(1) complexity per sample.

func (*EntropyEncoder) EncodeCoefficients

func (e *EntropyEncoder) EncodeCoefficients(coeffs []int32, bitDepth int) ([]byte, error)

EncodeCoefficients encodes wavelet coefficients to a byte stream. Uses bounded complexity O(1) operations per coefficient.

type ImageInfo

type ImageInfo struct {
	// Width is the image width in pixels.
	Width int

	// Height is the image height in pixels.
	Height int

	// ComponentCount is the number of color components.
	ComponentCount int

	// BitDepth is the maximum bit depth per component.
	BitDepth int

	// Profile is the detected JPEG XS profile.
	Profile Profile

	// Level is the detected JPEG XS level.
	Level Level

	// Sublevel is the detected sublevel.
	Sublevel Sublevel

	// ChromaSampling indicates the chroma subsampling mode.
	ChromaSampling ChromaSampling

	// WaveletLevelsX is the number of horizontal wavelet levels.
	WaveletLevelsX int

	// WaveletLevelsY is the number of vertical wavelet levels.
	WaveletLevelsY int

	// SliceCount is the number of slices in the image.
	SliceCount int

	// IsLossless indicates if lossless compression was used.
	IsLossless bool

	// CompressedSize is the size of the compressed codestream in bytes.
	CompressedSize int64

	// CompressionRatio is the compression ratio (uncompressed/compressed).
	CompressionRatio float64
}

ImageInfo contains decoded image information.

func (*ImageInfo) GetOutputSize

func (i *ImageInfo) GetOutputSize(bytesPerSample int) (int, error)

GetOutputSize calculates the output buffer size needed for decoding. Uses safe integer arithmetic to prevent overflow.

func (*ImageInfo) Validate

func (i *ImageInfo) Validate() error

Validate checks that image info is valid and within security limits.

type Level

type Level uint8

Level constants define JPEG XS levels per ISO/IEC 21122-2. Levels specify maximum image dimensions and complexity constraints.

const (
	// LevelUnknown indicates an unrecognized or invalid level.
	LevelUnknown Level = 0x00

	// Level1K supports images up to 1280x720 (720p).
	Level1K Level = 0x10

	// Level2K supports images up to 2048x1080 (2K/1080p).
	Level2K Level = 0x20

	// Level4K supports images up to 4096x2160 (4K/UHD).
	Level4K Level = 0x40

	// Level8K supports images up to 8192x4320 (8K).
	Level8K Level = 0x80

	// Level10K supports images up to 10240x4320 (10K).
	Level10K Level = 0xA0
)

func (Level) IsValid

func (l Level) IsValid() bool

IsValid returns true if the level is recognized.

func (Level) MaxHeight

func (l Level) MaxHeight() int

MaxHeight returns the maximum image height for this level.

func (Level) MaxWidth

func (l Level) MaxWidth() int

MaxWidth returns the maximum image width for this level.

func (Level) String

func (l Level) String() string

String returns a human-readable name for the level.

type LineBasedWaveletReconstructor

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

LineBasedWaveletReconstructor provides line-by-line wavelet reconstruction.

func NewLineBasedWaveletReconstructor

func NewLineBasedWaveletReconstructor(width, height, levels int) (*LineBasedWaveletReconstructor, error)

NewLineBasedWaveletReconstructor creates a new line-based reconstructor.

func (*LineBasedWaveletReconstructor) ReconstructLine

func (r *LineBasedWaveletReconstructor) ReconstructLine(lineNum int) ([]int32, error)

ReconstructLine reconstructs a single output line.

func (*LineBasedWaveletReconstructor) SetSubbands

func (r *LineBasedWaveletReconstructor) SetSubbands(subbands *SubbandData) error

SetSubbands sets the subband data for reconstruction.

type LineBuffer

type LineBuffer struct {
	// Width is the width of the buffer in samples.
	Width int

	// Height is the number of lines in the buffer.
	Height int

	// ComponentIndex indicates which component this buffer is for.
	ComponentIndex int

	// SubbandIndex indicates which wavelet subband.
	SubbandIndex int

	// Data contains the buffered sample values.
	Data []int32
}

LineBuffer represents a buffer for line-based wavelet processing. JPEG XS uses bounded memory for low-latency operation.

func (*LineBuffer) Validate

func (lb *LineBuffer) Validate() error

Validate checks that the line buffer is within security limits.

type LinedBasedWaveletProcessor

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

LinedBasedWaveletProcessor provides line-by-line wavelet processing. This enables sub-line latency required by JPEG XS for real-time streaming. Internally, it accumulates lines and uses the standard 2D transform for correct coefficient computation.

func NewLinedBasedWaveletProcessor

func NewLinedBasedWaveletProcessor(width, height, levels int) (*LinedBasedWaveletProcessor, error)

NewLinedBasedWaveletProcessor creates a new line-based wavelet processor. This processor enables sub-line latency by processing image data line by line.

func (*LinedBasedWaveletProcessor) GetSubbands

func (p *LinedBasedWaveletProcessor) GetSubbands() (*SubbandData, error)

GetSubbands returns the completed subband data. Should be called after all lines have been processed.

func (*LinedBasedWaveletProcessor) ProcessLine

func (p *LinedBasedWaveletProcessor) ProcessLine(line []int32) error

ProcessLine processes a single line of input data. Lines must be provided in order from top to bottom.

type PIH

type PIH struct {
	// Length is the total length of the PIH marker segment (excluding marker bytes).
	Length uint16

	// Profile indicates the JPEG XS profile (Ppih field).
	Profile Profile

	// Width is the image width in pixels.
	Width int

	// Height is the image height in pixels.
	Height int

	// ComponentCount is the number of components (Nc).
	ComponentCount uint8

	// BitDepth is the maximum bit depth per component (Bw).
	BitDepth uint8

	// WaveletLevels is the number of wavelet decomposition levels (Nlx, Nly).
	WaveletLevelsX uint8
	WaveletLevelsY uint8

	// QuantizationStyle indicates the quantization method (Cq).
	QuantizationStyle uint8

	// RefineFlag indicates if refinement passes are used (Br).
	RefineFlag bool

	// FragmentationFlag indicates if fragmentation is used (Fslc).
	FragmentationFlag bool

	// SliceHeight is the height of each slice in lines (Ppoc).
	SliceHeight int

	// PrecinctWidth is the precinct width (Cpx).
	PrecinctWidth int

	// RawBytes contains the raw header bytes for extended parsing.
	RawBytes []byte
}

PIH represents the Picture Header marker segment. This marker contains the image dimensions and component information.

func (*PIH) Validate

func (p *PIH) Validate() error

Validate checks that PIH values are within acceptable ranges.

type Parser

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

Parser handles parsing of JPEG XS codestream marker segments. It validates marker structure and extracts codestream metadata.

func NewParser

func NewParser(data []byte) *Parser

NewParser creates a new JPEG XS parser for the given data.

func NewParserWithOffset

func NewParserWithOffset(data []byte, offset int64) *Parser

NewParserWithOffset creates a new parser with a specified file offset for logging.

func (*Parser) ParseCAP

func (p *Parser) ParseCAP() (*CAP, error)

ParseCAP parses the Capabilities marker segment. Returns the parsed CAP structure or an error if parsing fails.

func (*Parser) ParseCDT

func (p *Parser) ParseCDT() (*CDT, error)

ParseCDT parses the Component Table marker segment. Returns the parsed CDT structure or an error if parsing fails.

func (*Parser) ParseMarker

func (p *Parser) ParseMarker() (uint16, error)

ParseMarker reads the next marker and returns its type. Returns the 2-byte marker code or an error if data is truncated.

func (*Parser) ParsePIH

func (p *Parser) ParsePIH() (*PIH, error)

ParsePIH parses the Picture Header marker segment. Returns the parsed PIH structure or an error if parsing fails.

func (*Parser) ParseSOC

func (p *Parser) ParseSOC() error

ParseSOC parses and validates the Start of Codestream marker. Returns nil if valid SOC is found, or an error if missing or invalid.

func (*Parser) ParseWGT

func (p *Parser) ParseWGT() (*WGT, error)

ParseWGT parses the Weight Table marker segment. Returns the parsed WGT structure or an error if parsing fails.

func (*Parser) Position

func (p *Parser) Position() int

Position returns the current parser position.

func (*Parser) Remaining

func (p *Parser) Remaining() int

Remaining returns the number of bytes remaining to parse.

func (*Parser) RouteMarker

func (p *Parser) RouteMarker() (uint16, interface{}, error)

RouteMarker reads the next marker and routes to the appropriate parser. Returns the marker type and parsed structure, or an error.

func (*Parser) SetPosition

func (p *Parser) SetPosition(pos int)

SetPosition sets the parser position.

type Precinct

type Precinct struct {
	// Index is the precinct index within the slice.
	Index int

	// Width is the precinct width in samples.
	Width int

	// BudgetBytes is the byte budget for this precinct.
	BudgetBytes int

	// Data contains the encoded precinct data.
	Data []byte
}

Precinct represents a coding precinct in JPEG XS. Precincts are the basic unit of entropy coding.

type Profile

type Profile uint16

Profile constants define JPEG XS coding profiles per ISO/IEC 21122-2.

const (
	// ProfileUnknown indicates an unrecognized or invalid profile.
	ProfileUnknown Profile = 0x0000

	// ProfileMain is the Main Profile for broadcast applications.
	// This profile is designed for professional video production with
	// compression ratios typically between 5:1 and 10:1.
	// Supports 4:2:2 and 4:4:4 chroma sampling.
	// Defined in ISO/IEC 21122-2 Annex A.
	ProfileMain Profile = 0x1500 // Ppih value for Main Profile

	// ProfileHigh is the High Profile for extended capabilities.
	// This profile provides additional features for higher quality
	// requirements including more wavelet decomposition levels.
	// Supports 4:2:0, 4:2:2, and 4:4:4 chroma sampling.
	// Defined in ISO/IEC 21122-2 Annex A.
	ProfileHigh Profile = 0x1A00 // Ppih value for High Profile

	// ProfileLight is the Light Profile for reduced complexity.
	// This profile targets resource-constrained environments with
	// lower computational requirements.
	// Supports 4:2:0 and 4:2:2 chroma sampling.
	// Defined in ISO/IEC 21122-2 Annex A.
	ProfileLight Profile = 0x2500 // Ppih value for Light Profile

	// ProfileLight44412 is the Light 444.12 subprofile.
	// A variant of the Light Profile optimized for 4:4:4 content
	// at 12-bit precision, commonly used for RAW camera output.
	// Defined in ISO/IEC 21122-2 Annex A.
	ProfileLight44412 Profile = 0x2540 // Ppih value for Light 444.12 subprofile

	// ProfileMLS is the Main-Lossless (MLS) subprofile.
	// Provides mathematically lossless compression.
	// Defined in ISO/IEC 21122-2 Annex A.
	ProfileMLS Profile = 0x1580 // Main profile with lossless sublevel

	// ProfileHLS is the High-Lossless (HLS) subprofile.
	// High profile variant with lossless compression.
	// Defined in ISO/IEC 21122-2 Annex A.
	ProfileHLS Profile = 0x1A80 // High profile with lossless sublevel
)

func (Profile) IsLossless

func (p Profile) IsLossless() bool

IsLossless returns true if the profile supports lossless compression.

func (Profile) IsValid

func (p Profile) IsValid() bool

IsValid returns true if the profile is a recognized JPEG XS profile.

func (Profile) String

func (p Profile) String() string

String returns a human-readable name for the profile.

type RateControl

type RateControl struct {
	// TargetBitrate is the target bitrate in bits per second.
	TargetBitrate int64

	// BufferSize is the decoder buffer size in bits.
	BufferSize int

	// BitsPerPixel is the target bits per pixel.
	BitsPerPixel float64

	// MaxQuantization is the maximum quantization step.
	MaxQuantization int

	// MinQuantization is the minimum quantization step.
	MinQuantization int
}

RateControl contains rate control parameters.

func (*RateControl) Validate

func (rc *RateControl) Validate() error

Validate checks that rate control parameters are valid.

type RateController

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

RateController implements dynamic quantization adjustment for target bitrate. Per ISO/IEC 21122-2, rate control maintains target bits per pixel (BPP).

func NewRateController

func NewRateController(targetBPP float64, imageWidth, imageHeight, sliceHeight int) *RateController

NewRateController creates a new rate controller.

func (*RateController) GetQuantizationParameter

func (rc *RateController) GetQuantizationParameter() int

GetQuantizationParameter returns the current QP for encoding.

func (*RateController) GetSliceBitBudget

func (rc *RateController) GetSliceBitBudget() int

GetSliceBitBudget returns the target bits for the next slice.

func (*RateController) ReportSliceBits

func (rc *RateController) ReportSliceBits(actualBits int)

ReportSliceBits reports the actual bits used for a slice. This allows the rate controller to adapt QP for subsequent slices.

type RunLengthDecoder

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

RunLengthDecoder decodes run-length encoded data.

func NewRunLengthDecoder

func NewRunLengthDecoder() *RunLengthDecoder

NewRunLengthDecoder creates a new run-length decoder.

func (*RunLengthDecoder) Decode

func (d *RunLengthDecoder) Decode(entries []RunLengthEntry, expectedLength int) []int32

Decode performs run-length decoding. Returns the reconstructed coefficient sequence.

type RunLengthEncoder

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

RunLengthEncoder encodes sequences of zeros efficiently. Uses bounded lookup tables for O(1) operations per sample.

func NewRunLengthEncoder

func NewRunLengthEncoder() *RunLengthEncoder

NewRunLengthEncoder creates a new run-length encoder.

func (*RunLengthEncoder) Encode

func (e *RunLengthEncoder) Encode(coeffs []int32) []RunLengthEntry

Encode performs run-length encoding on coefficients. Returns a slice of RunLengthEntry representing the compressed data.

type RunLengthEntry

type RunLengthEntry struct {
	// RunLength is the number of preceding zeros.
	RunLength int

	// Value is the non-zero coefficient value (or 0 for trailing zeros).
	Value int32
}

RunLengthEntry represents a run-length coded entry.

type SLH

type SLH struct {
	// Length is the total length of the SLH marker segment.
	Length uint16

	// SliceIndex is the index of this slice (0-based).
	SliceIndex uint16

	// DataOffset is the byte offset to the slice data following this header.
	DataOffset int
}

SLH represents the Slice Header marker segment. This marker marks the beginning of a slice and contains slice parameters.

func (*SLH) Validate

func (s *SLH) Validate() error

Validate checks that SLH values are within acceptable ranges.

type SignificanceDecoder

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

SignificanceDecoder decodes coefficient significance.

func NewSignificanceDecoder

func NewSignificanceDecoder() *SignificanceDecoder

NewSignificanceDecoder creates a new significance decoder.

func (*SignificanceDecoder) DecodeBlock

func (d *SignificanceDecoder) DecodeBlock(bitmap []byte, numCoeffs int) []bool

DecodeBlock decodes a significance bitmap to a slice of booleans.

func (*SignificanceDecoder) Reset

func (d *SignificanceDecoder) Reset()

Reset resets the decoder state for a new block.

type SignificanceEncoder

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

SignificanceEncoder encodes coefficient significance with context-based probabilities. Per ISO/IEC 21122-1, significance coding uses bounded complexity per sample.

func NewSignificanceEncoder

func NewSignificanceEncoder() *SignificanceEncoder

NewSignificanceEncoder creates a new significance encoder.

func (*SignificanceEncoder) EncodeBlock

func (e *SignificanceEncoder) EncodeBlock(coeffs []int32) []byte

EncodeBlock encodes a block of coefficients and returns significance bitmap.

func (*SignificanceEncoder) EncodeSignificance

func (e *SignificanceEncoder) EncodeSignificance(coeff int32) (significant bool, context int)

EncodeSignificance encodes the significance of a coefficient. Returns whether the coefficient is significant and the context used.

func (*SignificanceEncoder) Reset

func (e *SignificanceEncoder) Reset()

Reset resets the encoder state for a new block.

type Subband

type Subband struct {
	// Orientation indicates the subband type (LL, LH, HL, HH).
	Orientation SubbandOrientation

	// Level is the wavelet decomposition level (0 = finest).
	Level int

	// Width is the subband width in coefficients.
	Width int

	// Height is the subband height in coefficients.
	Height int

	// BitDepth is the bit depth of coefficients.
	BitDepth int
}

Subband represents a wavelet subband.

func (*Subband) Validate

func (s *Subband) Validate() error

Validate checks that the subband is within security limits.

type SubbandData

type SubbandData struct {
	LL       []int32
	LH       []int32
	HL       []int32
	HH       []int32
	LLWidth  int
	LLHeight int
	LHWidth  int
	LHHeight int
	HLWidth  int
	HLHeight int
	HHWidth  int
	HHHeight int
}

SubbandData holds the output subbands from line-based processing.

type SubbandOrientation

type SubbandOrientation uint8

SubbandOrientation indicates the orientation of a wavelet subband.

const (
	// SubbandLL is the low-low subband (approximation).
	SubbandLL SubbandOrientation = 0

	// SubbandLH is the low-high subband (horizontal detail).
	SubbandLH SubbandOrientation = 1

	// SubbandHL is the high-low subband (vertical detail).
	SubbandHL SubbandOrientation = 2

	// SubbandHH is the high-high subband (diagonal detail).
	SubbandHH SubbandOrientation = 3
)

func (SubbandOrientation) String

func (o SubbandOrientation) String() string

String returns a human-readable name for the subband orientation.

type Sublevel

type Sublevel uint8

Sublevel constants define JPEG XS sublevels per ISO/IEC 21122-2. Sublevels specify additional constraints on bitrate and buffer size.

const (
	// SublevelUnknown indicates an unrecognized or invalid sublevel.
	SublevelUnknown Sublevel = 0x00

	// SublevelFull is the Full sublevel (no additional constraints).
	SublevelFull Sublevel = 0x80

	// SublevelBayer is the Bayer sublevel for raw sensor data.
	SublevelBayer Sublevel = 0x40

	// Sublevel420 is the 4:2:0 sublevel.
	Sublevel420 Sublevel = 0x10

	// Sublevel422 is the 4:2:2 sublevel.
	Sublevel422 Sublevel = 0x20

	// Sublevel444 is the 4:4:4 sublevel.
	Sublevel444 Sublevel = 0x30
)

func (Sublevel) String

func (s Sublevel) String() string

String returns a human-readable name for the sublevel.

type WGT

type WGT struct {
	// Length is the total length of the WGT marker segment.
	Length uint16

	// Weights contains the weight values for each band.
	Weights []BandWeight
}

WGT represents the Weight Table marker segment. This marker contains weighting factors used for entropy coding.

func (*WGT) Validate

func (w *WGT) Validate() error

Validate checks that WGT values are within acceptable ranges.

type WaveletCoeffs2D

type WaveletCoeffs2D struct {
	// Data holds the coefficient values in subband-organized layout.
	Data []int32

	// Width is the original image width.
	Width int

	// Height is the original image height.
	Height int

	// LL, LH, HL, HH are the subband dimensions and offsets.
	LLWidth, LLHeight int
	LHWidth, LHHeight int
	HLWidth, HLHeight int
	HHWidth, HHHeight int
}

WaveletCoeffs2D holds 2D wavelet coefficients after decomposition.

type WaveletDecomposition

type WaveletDecomposition struct {
	// Levels contains the subbands for each decomposition level.
	Levels []WaveletLevel

	// NumLevels is the number of decomposition levels.
	NumLevels int

	// Width is the original image width.
	Width int

	// Height is the original image height.
	Height int
}

WaveletDecomposition holds multi-level wavelet decomposition results.

type WaveletLevel

type WaveletLevel struct {
	// LL is the low-low (approximation) subband.
	LL []int32

	// LH is the low-high (horizontal detail) subband.
	LH []int32

	// HL is the high-low (vertical detail) subband.
	HL []int32

	// HH is the high-high (diagonal detail) subband.
	HH []int32

	// Dimensions for each subband.
	LLWidth, LLHeight int
	LHWidth, LHHeight int
	HLWidth, HLHeight int
	HHWidth, HHHeight int
}

WaveletLevel holds the subbands for one level of decomposition.

type WaveletTransform53

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

WaveletTransform53 implements the 5/3 reversible (lossless) wavelet transform. This is the lifting-based implementation used in JPEG XS per ISO/IEC 21122. The 1-D lifting steps are delegated to the JPEG 2000 implementation because ISO 21122's 5/3 filter is identical to ISO 15444-1 F.4.8.1.

func NewWaveletTransform53

func NewWaveletTransform53() *WaveletTransform53

NewWaveletTransform53 creates a new 5/3 wavelet transform instance.

func (*WaveletTransform53) Forward1D

func (t *WaveletTransform53) Forward1D(input []int32) (lo, hi []int32)

Forward1D performs 1D forward 5/3 wavelet transform using the lifting scheme. Input: signal of length N Output: (N+1)/2 low-pass coefficients, N/2 high-pass coefficients

Delegates to internal/jpeg2000/wavelet.Transform53Impl; ISO 21122 requires the same lifting steps as ISO 15444-1 F.4.8.1:

  1. Predict: d[n] = x[2n+1] - floor((x[2n] + x[2n+2]) / 2)
  2. Update: s[n] = x[2n] + floor((d[n-1] + d[n] + 2) / 4)

func (*WaveletTransform53) Forward2D

func (t *WaveletTransform53) Forward2D(data []int32, width, height int) (*WaveletCoeffs2D, error)

Forward2D performs 2D forward 5/3 wavelet transform. Applies row transform then column transform (separable implementation).

func (*WaveletTransform53) ForwardMultiLevel

func (t *WaveletTransform53) ForwardMultiLevel(data []int32, width, height, levels int) (*WaveletDecomposition, error)

ForwardMultiLevel performs multi-level 2D wavelet decomposition.

func (*WaveletTransform53) Inverse1D

func (t *WaveletTransform53) Inverse1D(lo, hi []int32) []int32

Inverse1D performs 1D inverse 5/3 wavelet transform using the lifting scheme. This reverses the Forward1D operation for perfect reconstruction. Delegates to internal/jpeg2000/wavelet.Transform53Impl (ISO 15444-1 F.4.8.1).

func (*WaveletTransform53) Inverse2D

func (t *WaveletTransform53) Inverse2D(coeffs *WaveletCoeffs2D) ([]int32, error)

Inverse2D performs 2D inverse 5/3 wavelet transform.

func (*WaveletTransform53) InverseMultiLevel

func (t *WaveletTransform53) InverseMultiLevel(decomp *WaveletDecomposition) ([]int32, error)

InverseMultiLevel performs multi-level 2D wavelet reconstruction.

Directories

Path Synopsis
Package container provides JPEG XS (ISO/IEC 21122-3) transport format parsing.
Package container provides JPEG XS (ISO/IEC 21122-3) transport format parsing.

Jump to

Keyboard shortcuts

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