jpegxt

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

Documentation

Overview

Package jpegxt provides JPEG XT (ISO/IEC 18477) HDR extension support. This file implements the HDR decoder for JPEG XT profiles.

Package jpegxt provides JPEG XT (ISO/IEC 18477) decoding and encoding support.

JPEG XT is an HDR (High Dynamic Range) extension to the baseline JPEG standard that maintains backward compatibility with legacy JPEG decoders. HDR extension data is stored in APP11 marker segments, which legacy decoders simply ignore, allowing them to display the SDR (Standard Dynamic Range) base layer.

Profiles

JPEG XT defines four main profiles:

  • Profile A (refinement coding): Adds precision to the base layer DCT coefficients
  • Profile B (residual coding): Encodes HDR residual data separately from base layer
  • Profile C (HDR floating-point): Uses floating-point representation for HDR pixels
  • Profile D (16-bit integer): Uses 16-bit integer representation for extended range

HDR Extension Architecture

The JPEG XT format embeds HDR extension data in APP11 marker segments (0xFFEB). The extension data includes:

  • Profile indicator and version information
  • Tone mapping operator (TMO) parameters for SDR preview
  • Refinement scans or residual image data depending on profile
  • Color space and dynamic range metadata

Backward Compatibility

A JPEG XT file can be decoded by any standard JPEG decoder, which will display only the SDR base layer. HDR-aware decoders can combine the base layer with extension data to reconstruct the full dynamic range.

Security Considerations

This package enforces security limits defined in the security package:

  • Maximum HDR dynamic range (MaxHDRDynamicRange)
  • Maximum float exponent (MaxFloatExponent)
  • Maximum tone mapping iterations (MaxToneMapIterations)
  • Maximum marker segment length (MaxMarkerLength)

All integer conversions use the safeconv package to prevent overflow.

Standards Reference

This implementation follows:

  • ISO/IEC 18477-1: Core coding system
  • ISO/IEC 18477-2: Extensions (HDR)
  • ISO/IEC 18477-6: 16-bit Integer Coding (Profile D, IDR)
  • ISO/IEC 18477-7: HDR floating-point coding (Profile C)
  • ISO/IEC 18477-8: Near-lossless coding

Usage

To decode a JPEG XT file:

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

// Decode to HDR output (float32)
hdrData, err := decoder.DecodeHDR()
if err != nil {
    // Handle error
}

// Or decode to SDR output (uint8) using tone mapping
sdrData, err := decoder.Decode()
if err != nil {
    // Handle error
}

Package jpegxt provides JPEG XT (ISO/IEC 18477) HDR extension support. This file implements the JPEG XT HDR encoder for creating backward-compatible HDR images that can be decoded by standard JPEG decoders (base layer only) or JPEG XT decoders (full HDR reconstruction).

Package jpegxt provides JPEG XT (ISO/IEC 18477) HDR extension support. This file implements Part 8 near-lossless and lossless mode decoding, including alpha channel support.

Package jpegxt provides JPEG XT (ISO/IEC 18477) HDR extension support. This file implements the APP11 marker parser for JPEG XT extension data.

Package jpegxt provides JPEG XT (ISO/IEC 18477) HDR extension support. This file implements tone mapping operators for converting HDR to SDR.

Index

Constants

View Source
const (
	// ExtTypeLossless indicates lossless/near-lossless extension data.
	ExtTypeLossless ExtensionType = 13

	// FlagLossless indicates lossless mode in header flags.
	FlagLossless uint8 = 0x01

	// FlagAlphaChannel indicates alpha channel present.
	FlagAlphaChannel uint8 = 0x02

	// FlagPremultipliedAlpha indicates premultiplied alpha.
	FlagPremultipliedAlpha uint8 = 0x04

	// MaxErrorBound is the maximum allowed near-lossless error bound.
	MaxErrorBound = 255
)

Additional extension types for Part 8

View Source
const (
	// MarkerAPP11 is the APP11 marker (0xFFEB) used for JPEG XT extension data.
	MarkerAPP11 = 0xFFEB

	// MarkerSOI is the Start of Image marker.
	MarkerSOI = 0xFFD8

	// MarkerEOI is the End of Image marker.
	MarkerEOI = 0xFFD9
)

JPEG XT marker codes

View Source
const APP11HeaderDataSize = 9

APP11HeaderDataSize is the size of the header data after the length field. This is: 3 (namespace) + 1 (version) + 1 (profile) + 1 (flags) + 1 (ext type) + 2 (reserved) = 9 bytes

View Source
const MinAPP11HeaderSize = 13

MinAPP11HeaderSize is the minimum size of an APP11 header in bytes. This includes: 2 (marker) + 2 (length) + 3 (namespace) + 1 (version) + 1 (profile) + 1 (flags) + 1 (ext type) + 2 (reserved) = 13 bytes

Variables

View Source
var (
	// ErrInvalidAPP11 indicates the APP11 marker segment is malformed or invalid.
	ErrInvalidAPP11 = errors.New("invalid APP11 marker")

	// ErrMissingExtension indicates the required HDR extension data is missing.
	ErrMissingExtension = errors.New("missing HDR extension data")

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

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

	// ErrTruncatedExtension indicates the extension data is incomplete or truncated.
	ErrTruncatedExtension = errors.New("truncated extension data")

	// ErrInvalidRefinement indicates the refinement scan data is malformed.
	ErrInvalidRefinement = errors.New("invalid refinement scan data")

	// ErrInvalidResidual indicates the residual coding data is malformed.
	ErrInvalidResidual = errors.New("invalid residual coding data")

	// ErrHDRRangeExceeded indicates the HDR value exceeds maximum allowed dynamic range.
	ErrHDRRangeExceeded = errors.New("HDR dynamic range exceeded")

	// ErrFloatExponentOverflow indicates a floating-point exponent exceeds limits.
	ErrFloatExponentOverflow = errors.New("floating-point exponent overflow")

	// ErrToneMapIterationLimit indicates the tone mapping operator exceeded iteration limit.
	ErrToneMapIterationLimit = errors.New("tone mapping iteration limit exceeded")

	// ErrInvalidToneMapOperator indicates an unknown or invalid tone mapping operator type.
	ErrInvalidToneMapOperator = errors.New("invalid tone mapping operator")

	// ErrInvalidColorSpace indicates an unsupported or invalid color space identifier.
	ErrInvalidColorSpace = errors.New("invalid color space")

	// ErrMissingBaseLayer indicates the base JPEG layer is missing or undecodable.
	ErrMissingBaseLayer = errors.New("missing or invalid base layer")

	// ErrVersionMismatch indicates a version mismatch between decoder and data.
	ErrVersionMismatch = errors.New("JPEG XT version mismatch")

	// ErrInvalidHeader indicates the APP11 header structure is malformed.
	ErrInvalidHeader = errors.New("invalid APP11 header structure")

	// ErrAlphaChannelError indicates an error in alpha channel extension data.
	ErrAlphaChannelError = errors.New("alpha channel decoding error")

	// ErrInvalidMergeOperation indicates base layer and extension cannot be merged.
	ErrInvalidMergeOperation = errors.New("invalid HDR merge operation")
)

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

View Source
var JPEGXTNamespace = []byte("XT\x00")

JPEG XT namespace identifier. This identifier appears at the start of APP11 segments to identify JPEG XT data.

Functions

func HDRToSDR

func HDRToSDR(hdr []float32, toneMapper ToneMapper) ([]uint8, error)

HDRToSDR converts HDR float data to 8-bit SDR using the specified tone mapper. If toneMapper is nil, a default Reinhard mapper is used.

func HDRToSDR16

func HDRToSDR16(hdr []float32, toneMapper ToneMapper) ([]uint16, error)

HDRToSDR16 converts HDR float data to 16-bit SDR using the specified tone mapper.

Types

type APP11Header

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

	// Namespace identifies the type of APP11 data (e.g., "XT\x00" for JPEG XT).
	Namespace [3]byte

	// Version indicates the JPEG XT specification version.
	Version uint8

	// Profile indicates which JPEG XT profile is used.
	Profile Profile

	// Flags contains various header flags.
	Flags uint8

	// ExtensionType indicates the type of extension data that follows.
	ExtensionType ExtensionType

	// Reserved bytes for future use.
	Reserved [2]byte
}

APP11Header represents the header of an APP11 marker segment. This structure is parsed from the beginning of APP11 segments to identify JPEG XT extension data.

func (*APP11Header) IsJPEGXT

func (h *APP11Header) IsJPEGXT() bool

IsJPEGXT returns true if this APP11 segment contains JPEG XT data.

func (*APP11Header) Validate

func (h *APP11Header) Validate() error

Validate checks that the header values are within acceptable ranges.

type AlphaChannelData

type AlphaChannelData struct {
	// Width of the alpha plane.
	Width int

	// Height of the alpha plane.
	Height int

	// BitDepth is 8 or 16.
	BitDepth int

	// Premultiplied indicates if RGB values are premultiplied by alpha.
	Premultiplied bool

	// AlphaPlane contains 8-bit alpha values.
	AlphaPlane []uint8

	// AlphaPlane16 contains 16-bit alpha values (when BitDepth == 16).
	AlphaPlane16 []uint16
}

AlphaChannelData represents alpha channel extension data.

func (*AlphaChannelData) Encode

func (a *AlphaChannelData) Encode() []byte

Encode encodes alpha channel data to bytes.

type ColorSpace

type ColorSpace uint8

ColorSpace defines the color space of HDR data.

const (
	// ColorSpaceUnknown indicates an unspecified color space.
	ColorSpaceUnknown ColorSpace = 0

	// ColorSpaceRGB indicates linear RGB color space.
	ColorSpaceRGB ColorSpace = 1

	// ColorSpaceBT2020 indicates ITU-R BT.2020 color space (HDR).
	ColorSpaceBT2020 ColorSpace = 2

	// ColorSpaceDisplayP3 indicates Display P3 color space.
	ColorSpaceDisplayP3 ColorSpace = 3

	// ColorSpaceXYZ indicates CIE XYZ color space.
	ColorSpaceXYZ ColorSpace = 4
)

func (ColorSpace) String

func (c ColorSpace) String() string

String returns a human-readable name for the color space.

type ExposureToneMapper

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

ExposureToneMapper implements a simple exposure-based tone mapping operator. This applies linear scaling based on the exposure value in stops.

func NewExposureToneMapper

func NewExposureToneMapper(params *ToneMapParams) *ExposureToneMapper

NewExposureToneMapper creates a new exposure-based tone mapper with the given parameters.

func (*ExposureToneMapper) GetParams

func (e *ExposureToneMapper) GetParams() *ToneMapParams

GetParams returns the current tone mapping parameters.

func (*ExposureToneMapper) GetType

GetType returns the tone mapping operator type.

func (*ExposureToneMapper) ToneMap

func (e *ExposureToneMapper) ToneMap(hdr []float32) ([]float32, error)

ToneMap applies exposure-based tone mapping to HDR data. The algorithm:

  1. Apply exposure: scaled = input * 2^exposure
  2. Apply gamma correction
  3. Clamp to [0, 1]

type ExtensionData

type ExtensionData struct {
	// Header contains the parsed APP11 header.
	Header APP11Header

	// Type indicates the specific extension type.
	Type ExtensionType

	// RawData contains the raw extension data bytes (excluding header).
	RawData []byte

	// Offset is the byte offset of this extension in the original file.
	Offset int64
}

ExtensionData represents generic JPEG XT extension data extracted from APP11.

func (*ExtensionData) Validate

func (e *ExtensionData) Validate() error

Validate checks that the extension data is within security limits.

type ExtensionType

type ExtensionType uint8

ExtensionType indicates the type of extension data in an APP11 segment.

const (
	// ExtTypeRefinement indicates refinement scan data (Profile A).
	ExtTypeRefinement ExtensionType = 1

	// ExtTypeResidual indicates residual coding data (Profile B).
	ExtTypeResidual ExtensionType = 2

	// ExtTypeFloat indicates floating-point HDR data (Profile C).
	ExtTypeFloat ExtensionType = 3

	// ExtTypeInteger16 indicates 16-bit integer HDR data (Profile D).
	ExtTypeInteger16 ExtensionType = 4

	// ExtTypeToneMap indicates tone mapping operator parameters.
	ExtTypeToneMap ExtensionType = 10

	// ExtTypeColorInfo indicates color space and gamut information.
	ExtTypeColorInfo ExtensionType = 11

	// ExtTypeAlpha indicates alpha channel extension data.
	ExtTypeAlpha ExtensionType = 12

	// ExtTypeMetadata indicates HDR metadata (e.g., mastering display info).
	ExtTypeMetadata ExtensionType = 20
)

func (ExtensionType) String

func (e ExtensionType) String() string

String returns a human-readable name for the extension type.

type FilmicToneMapper

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

FilmicToneMapper implements a filmic S-curve tone mapping operator. This approximates the response curve of photographic film.

func NewFilmicToneMapper

func NewFilmicToneMapper(params *ToneMapParams) *FilmicToneMapper

NewFilmicToneMapper creates a new filmic tone mapper.

func (*FilmicToneMapper) GetParams

func (f *FilmicToneMapper) GetParams() *ToneMapParams

GetParams returns the current tone mapping parameters.

func (*FilmicToneMapper) GetType

GetType returns the tone mapping operator type.

func (*FilmicToneMapper) ToneMap

func (f *FilmicToneMapper) ToneMap(hdr []float32) ([]float32, error)

ToneMap applies filmic tone mapping using an S-curve.

type FloatHDRData

type FloatHDRData struct {
	// Width is the width of the HDR image.
	Width int

	// Height is the height of the HDR image.
	Height int

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

	// Exponent contains the common exponent for each block.
	Exponent []int8

	// Mantissa contains the mantissa values for each pixel/component.
	Mantissa []uint16

	// DynamicRange is the HDR dynamic range in stops.
	DynamicRange float32

	// MinLuminance is the minimum luminance (in cd/m^2).
	MinLuminance float32

	// MaxLuminance is the maximum luminance (in cd/m^2).
	MaxLuminance float32
}

FloatHDRData represents floating-point HDR data for Profile C. Profile C uses IEEE 754 single-precision floating-point values.

func (*FloatHDRData) Validate

func (f *FloatHDRData) Validate() error

Validate checks that floating-point HDR data parameters are valid.

type HDRDecoder

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

HDRDecoder handles decoding of JPEG XT HDR extension data. It supports all four JPEG XT profiles:

  • Profile A: Refinement coding (additional precision bits)
  • Profile B: Residual coding (HDR = base + residual)
  • Profile C: Floating-point HDR (IEEE 754 float32)
  • Profile D: 16-bit integer HDR (uint16)

func NewHDRDecoder

func NewHDRDecoder() *HDRDecoder

NewHDRDecoder creates a new HDR decoder instance.

func (*HDRDecoder) ApplyInverseToneMap

func (d *HDRDecoder) ApplyInverseToneMap(sdrData []float32) ([]float32, error)

ApplyInverseToneMap applies inverse tone mapping to convert SDR to HDR. This is used when reconstructing HDR from tone-mapped base layer.

func (*HDRDecoder) DecodeSDR

func (d *HDRDecoder) DecodeSDR(baseLayer []int) ([]uint8, error)

DecodeSDR decodes the base layer only, producing SDR 8-bit output. This provides backward compatibility for legacy JPEG decoders.

func (*HDRDecoder) DecodeToFloat32

func (d *HDRDecoder) DecodeToFloat32(baseLayer []int, extensionData []byte) ([]float32, error)

DecodeToFloat32 decodes HDR data to floating-point output. This is used for Profile C.

func (*HDRDecoder) DecodeToUint16

func (d *HDRDecoder) DecodeToUint16(baseLayer []int, extensionData []byte) ([]uint16, error)

DecodeToUint16 decodes HDR data to 16-bit integer output. This is used for Profile D.

func (*HDRDecoder) GetImageInfo

func (d *HDRDecoder) GetImageInfo() *ImageInfo

GetImageInfo returns information about the decoded image.

func (*HDRDecoder) MergeBaseAndExtension

func (d *HDRDecoder) MergeBaseAndExtension(baseLayer []int, extensionData []byte) ([]int, error)

MergeBaseAndExtension merges base layer coefficients with HDR extension data. This is the core merging function used by all profiles.

func (*HDRDecoder) SetDimensions

func (d *HDRDecoder) SetDimensions(width, height, componentCount int) error

SetDimensions sets the image dimensions. Returns an error if dimensions exceed security limits.

func (*HDRDecoder) SetIgnoreExtension

func (d *HDRDecoder) SetIgnoreExtension(ignore bool)

SetIgnoreExtension sets whether to ignore HDR extension data. When true, only the base layer is decoded (backward compatibility mode).

func (*HDRDecoder) SetMetadata

func (d *HDRDecoder) SetMetadata(metadata *HDRMetadata)

SetMetadata sets the HDR metadata.

func (*HDRDecoder) SetProfile

func (d *HDRDecoder) SetProfile(profile Profile)

SetProfile sets the JPEG XT profile for decoding.

func (*HDRDecoder) SetToneMapParams

func (d *HDRDecoder) SetToneMapParams(params *ToneMapParams)

SetToneMapParams sets the tone mapping parameters.

func (*HDRDecoder) ValidateOutputSize

func (d *HDRDecoder) ValidateOutputSize(bytesPerSample int) error

ValidateOutputSize validates that the output buffer size is within limits.

type HDREncoder

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

HDREncoder encodes HDR image data in JPEG XT format. It supports all four JPEG XT profiles:

  • Profile A: Refinement coding (additional precision bits)
  • Profile B: Residual coding (HDR = base + residual)
  • Profile C: Floating-point HDR (IEEE 754 float32)
  • Profile D: 16-bit integer HDR (uint16)

The encoder generates backward-compatible JPEG files with HDR extension data stored in APP11 markers. Standard JPEG decoders will display the tone-mapped SDR base layer, while JPEG XT decoders can reconstruct the full HDR image.

func NewHDREncoder

func NewHDREncoder() *HDREncoder

NewHDREncoder creates a new HDR encoder instance.

func (*HDREncoder) Configure

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

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

func (*HDREncoder) Encode

func (e *HDREncoder) Encode(w io.Writer, hdrData []float32) error

Encode performs full HDR encoding, generating both base layer and extension data. The output is a complete JPEG file with embedded APP11 HDR extension markers.

func (*HDREncoder) EncodeToneMapParams

func (e *HDREncoder) EncodeToneMapParams() ([]byte, error)

EncodeToneMapParams encodes the tone mapping parameters to bytes. Format varies by operator type:

  • TMOReinhard: [type(1)][key(4)][whitepoint(4)][gamma(4)][saturation(4)]
  • TMOExposure: [type(1)][exposure(4)][gamma(4)]
  • TMOCustom: [type(1)][paramCount(1)][name_len(1)][name...][value(4)]...

func (*HDREncoder) GenerateBaseLayer

func (e *HDREncoder) GenerateBaseLayer(w io.Writer, hdrData []float32) (int, error)

GenerateBaseLayer generates the tone-mapped SDR base layer. This is a complete JPEG image that standard decoders can display. The base layer is generated by applying tone mapping to the HDR data.

func (*HDREncoder) GenerateExtensionData

func (e *HDREncoder) GenerateExtensionData(hdrData []float32) ([]byte, error)

GenerateExtensionData generates the HDR extension data for the configured profile. This data is embedded in APP11 markers and used to reconstruct HDR values.

func (*HDREncoder) SetMetadata

func (e *HDREncoder) SetMetadata(metadata *HDRMetadata)

SetMetadata sets the HDR metadata to embed in the encoded output.

func (*HDREncoder) SetProfile

func (e *HDREncoder) SetProfile(profile Profile)

SetProfile sets the JPEG XT profile for encoding.

func (*HDREncoder) SetQuality

func (e *HDREncoder) SetQuality(quality int)

SetQuality sets the JPEG quality for the base layer (1-100).

func (*HDREncoder) SetToneMapParams

func (e *HDREncoder) SetToneMapParams(params *ToneMapParams)

SetToneMapParams sets the tone mapping parameters for base layer generation.

func (*HDREncoder) WriteAPP11Marker

func (e *HDREncoder) WriteAPP11Marker(w io.Writer, extType ExtensionType, data []byte) error

WriteAPP11Marker writes an APP11 marker with the given extension data.

type HDRMetadata

type HDRMetadata struct {
	// ColorSpace indicates the color space of HDR data.
	ColorSpace ColorSpace

	// MinLuminance is the minimum display luminance (cd/m^2).
	MinLuminance float32

	// MaxLuminance is the maximum display luminance (cd/m^2).
	MaxLuminance float32

	// PrimaryRedX is the X chromaticity of red primary.
	PrimaryRedX float32

	// PrimaryRedY is the Y chromaticity of red primary.
	PrimaryRedY float32

	// PrimaryGreenX is the X chromaticity of green primary.
	PrimaryGreenX float32

	// PrimaryGreenY is the Y chromaticity of green primary.
	PrimaryGreenY float32

	// PrimaryBlueX is the X chromaticity of blue primary.
	PrimaryBlueX float32

	// PrimaryBlueY is the Y chromaticity of blue primary.
	PrimaryBlueY float32

	// WhitePointX is the X chromaticity of white point.
	WhitePointX float32

	// WhitePointY is the Y chromaticity of white point.
	WhitePointY float32

	// MaxContentLightLevel is the maximum content light level (cd/m^2).
	MaxContentLightLevel float32

	// MaxFrameAverageLightLevel is the maximum frame-average light level.
	MaxFrameAverageLightLevel float32
}

HDRMetadata contains HDR image metadata (e.g., mastering display info).

func (*HDRMetadata) Validate

func (m *HDRMetadata) Validate() error

Validate checks that HDR metadata values are reasonable.

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 bit depth per component in the output.
	BitDepth int

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

	// IsHDR indicates if the image contains HDR extension data.
	IsHDR bool

	// HasAlpha indicates if the image has an alpha channel.
	HasAlpha bool

	// ColorSpace is the color space of the image.
	ColorSpace ColorSpace

	// DynamicRange is the HDR dynamic range in stops (if HDR).
	DynamicRange float32

	// ToneMapParams contains the tone mapping parameters (if present).
	ToneMapParams *ToneMapParams

	// Metadata contains HDR metadata (if present).
	Metadata *HDRMetadata
}

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 Integer16HDRData

type Integer16HDRData struct {
	// Width is the width of the HDR image.
	Width int

	// Height is the height of the HDR image.
	Height int

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

	// LinearGamma indicates if data is linear (true) or gamma-encoded (false).
	LinearGamma bool

	// GammaValue is the gamma value if not linear.
	GammaValue float32

	// PixelData contains the 16-bit pixel values.
	PixelData []uint16
}

Integer16HDRData represents 16-bit integer HDR data for Profile D. Profile D uses 16-bit unsigned integers for extended dynamic range.

func (*Integer16HDRData) Validate

func (i *Integer16HDRData) Validate() error

Validate checks that 16-bit integer HDR data parameters are valid.

type NearLosslessDecoder

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

NearLosslessDecoder handles Part 8 lossless and near-lossless decoding. It supports:

  • Lossless mode (error bound = 0): bit-exact reconstruction
  • Near-lossless mode (error bound > 0): bounded quantization error
  • Alpha channel coding

func NewNearLosslessDecoder

func NewNearLosslessDecoder() *NearLosslessDecoder

NewNearLosslessDecoder creates a new near-lossless decoder.

func (*NearLosslessDecoder) DecodeNearLosslessExt

func (d *NearLosslessDecoder) DecodeNearLosslessExt(extensionData []byte) ([]uint16, error)

DecodeNearLosslessExt performs near-lossless decoding of extension data. This is the main entry point for Part 8 decoding.

func (*NearLosslessDecoder) DetectLosslessProfile

func (d *NearLosslessDecoder) DetectLosslessProfile(header *APP11Header) bool

DetectLosslessProfile checks if the APP11 header indicates Part 8 lossless mode.

func (*NearLosslessDecoder) IsLossless

func (d *NearLosslessDecoder) IsLossless() bool

IsLossless returns true if the decoder is in lossless mode (error bound = 0).

func (*NearLosslessDecoder) MergeColorAndAlpha

func (d *NearLosslessDecoder) MergeColorAndAlpha(rgbData, alphaData []uint8) ([]uint8, error)

MergeColorAndAlpha merges RGB data with alpha channel to produce RGBA.

func (*NearLosslessDecoder) MergeColorAndAlpha16

func (d *NearLosslessDecoder) MergeColorAndAlpha16(rgbData, alphaData []uint16) ([]uint16, error)

MergeColorAndAlpha16 merges 16-bit RGB data with 16-bit alpha.

func (*NearLosslessDecoder) ParseAlphaExtension

func (d *NearLosslessDecoder) ParseAlphaExtension(data []byte) (*AlphaChannelData, error)

ParseAlphaExtension parses alpha channel extension data.

func (*NearLosslessDecoder) SetDimensions

func (d *NearLosslessDecoder) SetDimensions(width, height, componentCount int) error

SetDimensions sets the image dimensions for the decoder.

func (*NearLosslessDecoder) SetErrorBound

func (d *NearLosslessDecoder) SetErrorBound(bound int) error

SetErrorBound sets the near-lossless error bound. A bound of 0 means lossless mode (bit-exact). Returns an error if the bound is out of valid range.

type Parser

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

Parser handles parsing of JPEG XT APP11 marker segments. It validates marker structure and extracts HDR extension data.

func NewParser

func NewParser(data []byte) *Parser

NewParser creates a new JPEG XT 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) ParseAPP11Header

func (p *Parser) ParseAPP11Header() (*APP11Header, error)

ParseAPP11Header parses an APP11 marker header and validates JPEG XT namespace. Returns the parsed header or an error if the marker is invalid.

func (*Parser) ParseExtensionData

func (p *Parser) ParseExtensionData() (*ExtensionData, error)

ParseExtensionData parses a complete APP11 extension segment including header and data. Returns the extension data structure or an error if parsing fails.

func (*Parser) ParseRefinementData

func (p *Parser) ParseRefinementData(ext *ExtensionData) (*RefinementData, error)

ParseRefinementData parses refinement scan data for Profile A. This extracts the additional precision bits stored in APP11 segments.

func (*Parser) ParseResidualData

func (p *Parser) ParseResidualData(ext *ExtensionData) (*ResidualData, error)

ParseResidualData parses residual coding data for Profile B. This extracts the residual image data used to reconstruct HDR values.

type Profile

type Profile uint8

Profile constants define the JPEG XT coding profiles per ISO/IEC 18477.

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

	// ProfileA represents refinement coding profile.
	// This profile adds precision to base layer DCT coefficients through
	// refinement scans stored in APP11 segments.
	// Defined in ISO/IEC 18477-1.
	ProfileA Profile = 1

	// ProfileB represents residual coding profile.
	// This profile encodes HDR residual data separately, reconstructing
	// HDR values from base layer plus residual.
	// Defined in ISO/IEC 18477-1.
	ProfileB Profile = 2

	// ProfileC represents HDR floating-point coding profile.
	// Uses IEEE 754 floating-point representation for HDR pixel values.
	// Defined in ISO/IEC 18477-7.
	ProfileC Profile = 3

	// ProfileD represents 16-bit integer coding profile (IDR).
	// Uses 16-bit integer representation for extended dynamic range.
	// Defined in ISO/IEC 18477-6.
	ProfileD Profile = 4
)

func (Profile) IsValid

func (p Profile) IsValid() bool

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

func (Profile) String

func (p Profile) String() string

String returns a human-readable name for the profile.

type RefinementData

type RefinementData struct {
	// ScanIndex indicates which scan this refinement applies to.
	ScanIndex uint8

	// ComponentMask indicates which components are refined (bitmask).
	ComponentMask uint8

	// BitPosition indicates the bit position being refined (MSB = 0).
	BitPosition uint8

	// SuccessiveLow is the lower bound for successive approximation.
	SuccessiveLow uint8

	// SuccessiveHigh is the upper bound for successive approximation.
	SuccessiveHigh uint8

	// CoefficientData contains the refinement coefficient data.
	CoefficientData []byte

	// BlockCount is the number of 8x8 blocks in the refinement scan.
	BlockCount int
}

RefinementData represents refinement scan data for Profile A. In Profile A, additional precision bits are encoded as refinement scans and stored in APP11 segments.

func (*RefinementData) Validate

func (r *RefinementData) Validate() error

Validate checks that refinement data parameters are valid.

type ReinhardToneMapper

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

ReinhardToneMapper implements the Reinhard global tone mapping operator. This uses a logarithmic-based mapping to compress HDR luminance to SDR. Reference: Reinhard et al., "Photographic Tone Reproduction for Digital Images"

func NewReinhardToneMapper

func NewReinhardToneMapper(params *ToneMapParams) *ReinhardToneMapper

NewReinhardToneMapper creates a new Reinhard tone mapper with the given parameters.

func (*ReinhardToneMapper) GetParams

func (r *ReinhardToneMapper) GetParams() *ToneMapParams

GetParams returns the current tone mapping parameters.

func (*ReinhardToneMapper) GetType

GetType returns the tone mapping operator type.

func (*ReinhardToneMapper) ToneMap

func (r *ReinhardToneMapper) ToneMap(hdr []float32) ([]float32, error)

ToneMap applies Reinhard global tone mapping to HDR data. The algorithm:

  1. Scale luminance by key value
  2. Apply Reinhard operator: L_d = L / (1 + L)
  3. Apply white point adjustment for bright values
  4. Apply gamma correction

type ResidualData

type ResidualData struct {
	// ResidualMode indicates the residual encoding mode.
	ResidualMode uint8

	// ScaleFactor is the scaling factor for residual values.
	ScaleFactor float32

	// OffsetValue is the offset applied to residual values.
	OffsetValue float32

	// BitDepth is the bit depth of residual values.
	BitDepth uint8

	// ComponentCount is the number of color components in the residual.
	ComponentCount uint8

	// Width is the width of the residual image.
	Width int

	// Height is the height of the residual image.
	Height int

	// ResidualImage contains the encoded residual image data.
	ResidualImage []byte
}

ResidualData represents residual coding data for Profile B. In Profile B, the HDR image is reconstructed by combining the base layer with a residual image that captures the difference.

func (*ResidualData) Validate

func (r *ResidualData) Validate() error

Validate checks that residual data parameters are valid.

type ToneMapOperatorType

type ToneMapOperatorType uint8

ToneMapOperatorType defines the type of tone mapping operator.

const (
	// TMONone indicates no tone mapping (raw HDR output).
	TMONone ToneMapOperatorType = 0

	// TMOReinhard indicates Reinhard global tone mapper.
	TMOReinhard ToneMapOperatorType = 1

	// TMOExposure indicates exposure-based linear tone mapper.
	TMOExposure ToneMapOperatorType = 2

	// TMOFilmic indicates filmic (S-curve) tone mapper.
	TMOFilmic ToneMapOperatorType = 3

	// TMOCustom indicates a custom/vendor-specific tone mapper.
	TMOCustom ToneMapOperatorType = 255
)

func (ToneMapOperatorType) String

func (t ToneMapOperatorType) String() string

String returns a human-readable name for the tone mapping operator.

type ToneMapParams

type ToneMapParams struct {
	// OperatorType indicates which TMO to use.
	OperatorType ToneMapOperatorType

	// Key is the key value for Reinhard operator (typical: 0.18).
	Key float32

	// Exposure is the exposure adjustment in stops.
	Exposure float32

	// Gamma is the output gamma correction value.
	Gamma float32

	// WhitePoint is the luminance mapped to white (for Reinhard).
	WhitePoint float32

	// Saturation controls color saturation after tone mapping.
	Saturation float32

	// CustomParams contains additional parameters for custom TMOs.
	CustomParams map[string]float32
}

ToneMapParams contains parameters for tone mapping operators.

func NewDefaultToneMapParams

func NewDefaultToneMapParams() *ToneMapParams

NewDefaultToneMapParams creates default tone mapping parameters.

func ParseToneMapParams

func ParseToneMapParams(data []byte) (*ToneMapParams, error)

ParseToneMapParams parses tone mapping parameters from extension data. The format varies based on the operator type:

  • TMOReinhard: [type(1)][key(4)][whitepoint(4)][gamma(4)][saturation(4)]
  • TMOExposure: [type(1)][exposure(4)][gamma(4)]
  • TMOCustom: [type(1)][paramCount(1)][name_len(1)][name...][value(4)]...

type ToneMapper

type ToneMapper interface {
	// ToneMap applies the tone mapping operator to HDR data.
	// Input is HDR floating-point values (can exceed [0, 1]).
	// Output is SDR values in the range [0, 1].
	ToneMap(hdr []float32) ([]float32, error)

	// GetType returns the type of tone mapping operator.
	GetType() ToneMapOperatorType

	// GetParams returns the current tone mapping parameters.
	GetParams() *ToneMapParams
}

ToneMapper defines the interface for tone mapping operators. Tone mappers convert HDR (high dynamic range) data to SDR (standard dynamic range) for display on conventional monitors.

func CreateToneMapper

func CreateToneMapper(params *ToneMapParams) ToneMapper

CreateToneMapper creates a ToneMapper based on the operator type in params.

Jump to

Keyboard shortcuts

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