jpeg

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

README

jpeg

A comprehensive, pure-Go library for JPEG image processing: encoding, decoding, DCT-coefficient access, metadata parsing, and security-hardened handling of all JPEG format variants.

Install

go get github.com/0verkilll/jpeg

Sponsor

If this project is useful to you, please consider supporting its development:

Sponsor @0verkilll on GitHub

License

MIT

Documentation

Overview

Package jpeg provides zero-dependency JPEG DCT coefficient extraction, metadata parsing, and full IDCT pixel reconstruction decoding.

This library enables low-level access to JPEG internals including quantized DCT coefficients, Huffman tables, quantization tables, EXIF metadata, and marker sequences - essential for image forensics, steganography analysis, and advanced image processing.

Architecture

The package follows SOLID principles with an interface-based architecture:

  • Public API provides backward-compatible adapters
  • internal/ packages contain refactored, security-hardened implementations
  • Dependency injection enables testability and modularity

Key Features

  • Zero external dependencies (pure Go standard library)
  • Full IDCT pixel reconstruction via Decode() method
  • DCT coefficient extraction for steganalysis via Extract() method
  • Multiple DCT implementations: AAN (fast), Reference (precise), Integer
  • Chroma upsampling support: 4:4:4, 4:2:2, 4:2:0, Grayscale
  • Color conversion: BT.601 (default) and BT.709 standards
  • Security hardening: bounds checking, overflow protection, cycle detection

Basic Usage - Decode to Image

To decode a JPEG file to an image.Image for display or processing:

data, _ := os.ReadFile("image.jpg")
decoder := jpeg.NewImageDecoder()
img, err := decoder.Decode(data)
if err != nil {
    log.Fatal(err)
}
// img is *image.RGBA for color images or *image.Gray for grayscale

Basic Usage - Extract DCT Coefficients

To extract DCT coefficients for steganalysis or forensics:

data, _ := os.ReadFile("image.jpg")
decoder := jpeg.NewDecoder()
coefficients, err := decoder.Extract(data)
if err != nil {
    log.Fatal(err)
}
for _, coeff := range coefficients {
    fmt.Printf("Value=%d at (%d,%d) component=%d\n",
        coeff.Value, coeff.Row, coeff.Col, coeff.Component)
}

Advanced Usage - Custom Decoder Options

To configure the decoder with specific options:

opts := &jpeg.DecoderOptions{
    DCT:              jpeg.DCTReference,           // Use precise reference DCT
    ColorConversion:  jpeg.ColorConversionBT709,   // HD video color space
    ChromaUpsampling: jpeg.UpsamplingBilinear,     // Higher quality upsampling
}
decoder := jpeg.NewDecoderWithOptions(opts)
img, err := decoder.Decode(data)

DCT Transformer Selection

The package provides three DCT implementations for different use cases:

dct := jpeg.NewDCT()           // Default: AAN fast DCT (recommended)
dct := jpeg.NewReferenceDCT()  // Slow but mathematically precise
dct := jpeg.NewIntegerDCT()    // Reserved for future fixed-point optimization

For custom DCT/IDCT operations, all implementations satisfy the DCTTransformer interface.

For more examples, see the README.md and test files.

Package jpeg provides comprehensive JPEG family format decoding and encoding.

This library supports 36+ JPEG variants across the entire JPEG family of standards, making it one of the most complete Go implementations for JPEG format handling. It provides both high-level convenience APIs and low-level access to JPEG internals for advanced use cases.

Supported Formats

Standard JPEG (ITU-T T.81):

  • Baseline DCT (sequential, Huffman coded)
  • Extended DCT (sequential, extended precision)
  • Progressive DCT (multi-scan)
  • Lossless (predictive coding)
  • Arithmetic coded variants of all above
  • Differential coded variants of all above

Modern JPEG Extensions:

  • JPEG 2000 (ITU-T T.800) - wavelet-based compression with JP2, JPX, MJ2
  • JPEG-LS (ITU-T T.87) - lossless and near-lossless compression
  • JPEG XR (ITU-T T.832) - HD Photo format
  • JPEG XL (ISO/IEC 18181) - next-generation format
  • JPEG XT (ISO/IEC 18477) - HDR extension
  • JPEG XS (ISO/IEC 21122) - low-latency, visually lossless

Specialized JPEG Formats:

  • JPEG Pleno - light field, holography, point cloud
  • JPEG AI - neural network based compression
  • JPEG XE - event camera data
  • JUMBF - metadata containers
  • JPEG 360 - omnidirectional images
  • JLINK - linked content
  • JPEG Trust - authenticity verification

Basic Usage

The simplest way to decode a JPEG image:

file, err := os.Open("image.jpg")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

img, err := jpeg.Decode(file)
if err != nil {
    log.Fatal(err)
}
// Use img as image.Image

To get image information without full decoding:

info, err := jpeg.DecodeInfo(file)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Format: %s, Size: %dx%d\n", info.Format, info.Width, info.Height)

To detect format and decode in one step:

img, format, err := jpeg.DetectAndDecode(file)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Decoded %s image\n", format)

Advanced Usage

For more control over decoding, use the decoder interfaces:

dec, err := jpeg.NewSimpleDecoder(reader)
if err != nil {
    log.Fatal(err)
}
info := dec.GetImageInfo()
img, err := dec.DecodeImage()

For format-specific decoding with full options:

dec, err := jpeg.NewSimpleDecoderForFormat(reader, jpeg.FormatJPEG2000)
if err != nil {
    log.Fatal(err)
}
img, err := dec.DecodeImage()

Format Detection

The package provides robust format detection:

// Check if a format is supported
if jpeg.IsSupported("JPEG 2000") {
    fmt.Println("JPEG 2000 is supported!")
}

// Get list of all supported formats
formats := jpeg.SupportedFormats()
for _, f := range formats {
    fmt.Println(f.String())
}

Low-Level Access

For image forensics, steganography analysis, and advanced processing, the package provides low-level access to JPEG internals:

  • DCT coefficient extraction
  • Quantization table access
  • Huffman table inspection
  • EXIF and metadata parsing
  • Marker sequence analysis

Example for DCT coefficient extraction:

decoder := jpeg.NewDecoder()
result, err := decoder.Decode(data)
if err != nil {
    log.Fatal(err)
}
// Access DCT coefficients
for _, block := range result.DCTBlocks {
    // Analyze quantized coefficients
}

Encoding

The package also supports encoding to various JPEG formats:

encoder := jpeg.NewEncoder()
opts := &jpeg.EncoderOptions{
    Quality:     95,
    Progressive: true,
}
data, err := encoder.Encode(img, opts)

Thread Safety

All decoder and encoder instances are safe for concurrent use from multiple goroutines. Each instance maintains its own state and does not share mutable data with other instances.

Error Handling

The package defines specific error types for different failure conditions:

  • ErrNilReader: nil reader provided
  • ErrEmptyData: empty input data
  • ErrAPIUnsupportedFormat: format not recognized
  • ErrAPIDecodeFailure: decoding failed

Errors can be checked using errors.Is():

if errors.Is(err, jpeg.ErrAPIUnsupportedFormat) {
    // Handle unsupported format
}

Architecture

The package follows SOLID principles with an interface-based architecture:

  • FormatDetector: identifies image formats from byte sequences
  • Decoder: common interface for all format decoders
  • HDRDecoder: extended interface for HDR content
  • StreamDecoder: interface for tile-based streaming decode
  • LowLatencyDecoder: interface for real-time applications

Internal packages provide format-specific implementations that are composed through the public API facade.

Package jpeg provides unified decoding for all JPEG family formats. This file implements the unified decoder that routes to appropriate internal decoders based on format detection.

Example (ErrorHandling)

Example_errorHandling demonstrates proper error handling patterns. Always check for errors when decoding JPEG images.

package main

import (
	"bytes"
	"fmt"

	"github.com/0verkilll/jpeg"
)

func main() {
	// Example with invalid data
	invalidData := []byte{0x00, 0x00, 0x00}

	_, err := jpeg.Decode(bytes.NewReader(invalidData))
	if err != nil {
		fmt.Println("Error detected: invalid JPEG data")
	}

	// Example with empty reader
	_, err = jpeg.Decode(bytes.NewReader([]byte{}))
	if err != nil {
		fmt.Println("Error detected: empty data")
	}

	// Example with nil reader
	_, err = jpeg.Decode(nil)
	if err != nil {
		fmt.Println("Error detected: nil reader")
	}
}
Output:
Error detected: invalid JPEG data
Error detected: empty data
Error detected: nil reader
Example (FormatInfo)

Example_formatInfo demonstrates accessing format-specific information. The ImageInfo struct contains details about the detected format.

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/0verkilll/jpeg"
)

// createExampleJPEG creates a minimal valid baseline JPEG for examples.
// This returns a 1x1 grayscale JPEG image.
func createExampleJPEG() []byte {
	return []byte{

		0xFF, 0xD8,

		0xFF, 0xE0, 0x00, 0x10,
		'J', 'F', 'I', 'F', 0x00,
		0x01, 0x01,
		0x00,
		0x00, 0x01,
		0x00, 0x01,
		0x00, 0x00,

		0xFF, 0xDB, 0x00, 0x43, 0x00,

		16, 11, 10, 16, 24, 40, 51, 61,
		12, 12, 14, 19, 26, 58, 60, 55,
		14, 13, 16, 24, 40, 57, 69, 56,
		14, 17, 22, 29, 51, 87, 80, 62,
		18, 22, 37, 56, 68, 109, 103, 77,
		24, 35, 55, 64, 81, 104, 113, 92,
		49, 64, 78, 87, 103, 121, 120, 101,
		72, 92, 95, 98, 112, 100, 103, 99,

		0xFF, 0xC0, 0x00, 0x0B,
		0x08,
		0x00, 0x01,
		0x00, 0x01,
		0x01,
		0x01,
		0x11,
		0x00,

		0xFF, 0xC4, 0x00, 0x1F, 0x00,
		0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
		0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
		0x08, 0x09, 0x0A, 0x0B,

		0xFF, 0xC4, 0x00, 0xB5, 0x10,
		0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
		0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D,
		0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
		0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
		0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
		0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
		0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16,
		0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
		0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
		0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
		0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
		0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
		0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
		0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
		0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
		0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
		0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
		0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
		0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
		0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
		0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,
		0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
		0xF9, 0xFA,

		0xFF, 0xDA, 0x00, 0x08,
		0x01,
		0x01, 0x00,
		0x00, 0x3F, 0x00,

		0xFB, 0xD3, 0x28, 0xA6,

		0xFF, 0xD9,
	}
}

func main() {
	jpegData := createExampleJPEG()

	info, err := jpeg.DecodeInfo(bytes.NewReader(jpegData))
	if err != nil {
		log.Fatal(err)
	}

	// Check format properties
	fmt.Printf("Format: %s\n", info.Format)
	fmt.Printf("Is HDR: %v\n", info.HasHDR)
	fmt.Printf("Is Low-Latency: %v\n", info.IsLowLatency)
}
Output:
Format: Baseline JPEG (SOF0)
Is HDR: false
Is Low-Latency: false
Example (FormatList)

Example_formatList demonstrates iterating through supported formats. This can be used to build UI format selectors or documentation.

package main

import (
	"fmt"

	"github.com/0verkilll/jpeg"
)

func main() {
	formats := jpeg.SupportedFormats()

	// Count format categories
	var standard, extended, specialized int
	for _, f := range formats {
		name := f.String()
		switch name {
		case "JPEG 2000", "JPEG XL", "JPEG XR":
			extended++
		case "JPEG-LS", "JPEG XT (HDR)", "JPEG XS (Low-Latency)":
			specialized++
		default:
			standard++
		}
	}

	fmt.Printf("Total formats: %d\n", len(formats))
	fmt.Printf("Categories: standard=%d, extended=%d, specialized=%d\n",
		standard, extended, specialized)
}
Output:
Total formats: 37
Categories: standard=31, extended=3, specialized=3

Index

Examples

Constants

View Source
const (
	// J2KSOC is the JPEG 2000 start of codestream marker
	J2KSOC = 0xFF4F
	J2KSOT = 0xFF90 // Start of tile-part
	J2KSOD = 0xFF93 // Start of data
	J2KEOC = 0xFFD9 // End of codestream
	J2KSIZ = 0xFF51 // Image and tile size
	J2KCOD = 0xFF52 // Coding style default
	J2KCOC = 0xFF53 // Coding style component
	J2KRGN = 0xFF5E // Region of interest
	J2KQCD = 0xFF5C // Quantization default
	J2KQCC = 0xFF5D // Quantization component
	J2KPOC = 0xFF5F // Progression order change
	J2KTLM = 0xFF55 // Tile-part lengths
	J2KPLM = 0xFF57 // Packet length, main header
	J2KPLT = 0xFF58 // Packet length, tile-part header
	J2KPPM = 0xFF60 // Packed packet headers, main header
	J2KPPT = 0xFF61 // Packed packet headers, tile-part header
	J2KSOP = 0xFF91 // Start of packet
	J2KEPH = 0xFF92 // End of packet header
	J2KCRG = 0xFF63 // Component registration
	J2KCOM = 0xFF64 // Comment
)
View Source
const (
	// BlockSize is the standard JPEG block size (8x8 pixels).
	BlockSize = 8
	// BlockSize2 is the total number of coefficients in a block.
	BlockSize2 = BlockSize * BlockSize
)
View Source
const (
	// WeightQuantizationTable is the weight for quantization table matching.
	WeightQuantizationTable = 0.5
	// WeightAPPMarker is the weight for APP marker analysis.
	WeightAPPMarker = 0.3
	// WeightHuffmanTable is the weight for Huffman table analysis.
	WeightHuffmanTable = 0.2
)

Confidence weight constants for different detection methods.

View Source
const (
	// MaxImageDimension is the maximum allowed width or height.
	// Prevents integer overflow in dimension calculations.
	// JPEG standard supports up to 65535, but we limit for safety.
	MaxImageDimension = 65535

	// MinImageDimension is the minimum allowed width or height.
	MinImageDimension = 1

	// MaxImagePixels is the maximum total pixels allowed.
	// Prevents memory exhaustion attacks.
	// 100 megapixels = ~300MB for RGB, ~400MB for RGBA
	MaxImagePixels = 100_000_000

	// MaxMemoryAllocation is the maximum single allocation size.
	// Prevents resource exhaustion from malformed dimensions.
	MaxMemoryAllocation = 1 << 30 // 1GB

	// MaxQuality is the maximum quality setting.
	MaxQuality = 100

	// MinQuality is the minimum quality setting.
	MinQuality = 0

	// MaxBitsPerSample is the maximum bits per sample.
	MaxBitsPerSample = 16

	// MinBitsPerSample is the minimum bits per sample.
	MinBitsPerSample = 1
)
View Source
const (
	// BoxTypeJP2Signature is the JP2 signature box type
	BoxTypeJP2Signature = "jP  "
	BoxTypeFileType     = "ftyp"
	BoxTypeJP2Header    = "jp2h"
	BoxTypeImageHeader  = "ihdr"
	BoxTypeColourSpec   = "colr"
	BoxTypeCodestream   = "jp2c"
	BoxTypeResolution   = "res "
	BoxTypeUUID         = "uuid"
	BoxTypeUUIDInfo     = "uinf"
	BoxTypeXML          = "xml "
)
View Source
const DefaultEncoderComment = "0verkilll JPEG Encoder"

DefaultEncoderComment is the default comment embedded in all encoded JPEGs.

Variables

View Source
var (
	// ErrNilReader is returned when a nil reader is provided to a decode function.
	// Always check that your reader is non-nil before calling decode functions.
	ErrNilReader = errors.New("jpeg: nil reader")

	// ErrEmptyData is returned when the reader contains no data.
	// This can happen with empty files or readers that have already been consumed.
	ErrEmptyData = errors.New("jpeg: empty data")

	// ErrAPIUnsupportedFormat is returned when the format is not recognized.
	// Use SupportedFormats() to see which formats are supported.
	ErrAPIUnsupportedFormat = errors.New("jpeg: unsupported or unrecognized format")

	// ErrAPIDecodeFailure is returned when decoding fails due to corrupted
	// or invalid image data.
	ErrAPIDecodeFailure = errors.New("jpeg: decode failure")
)
View Source
var (
	// ErrEncoderNotInitialized indicates the encoder was not properly initialized.
	ErrEncoderNotInitialized = errors.New("encoder not initialized")

	// ErrEncoderInvalidInput indicates invalid input was provided to the encoder.
	ErrEncoderInvalidInput = errors.New("invalid encoder input")

	// ErrEncoderBufferTooSmall indicates the output buffer is too small.
	ErrEncoderBufferTooSmall = errors.New("encoder buffer too small")

	// ErrEncoderUnsupportedFormat indicates the format is not supported.
	ErrEncoderUnsupportedFormat = errors.New("unsupported encoder format")

	// ErrEncoderUnsupportedColorSpace indicates the color space is not supported.
	ErrEncoderUnsupportedColorSpace = errors.New("unsupported color space for encoding")

	// ErrEncoderTransformFailed indicates a transform operation failed.
	ErrEncoderTransformFailed = errors.New("encoder transform failed")

	// ErrEncoderQuantizationFailed indicates quantization failed.
	ErrEncoderQuantizationFailed = errors.New("encoder quantization failed")

	// ErrEncoderEntropyCoding indicates entropy coding failed.
	ErrEncoderEntropyCoding = errors.New("encoder entropy coding failed")
)

Sentinel errors for common encoder error conditions. These can be used with errors.Is for error checking.

View Source
var (
	// ErrNilInput indicates a required input was nil.
	ErrNilInput = errors.New("input cannot be nil")

	// ErrInvalidDimension indicates an invalid width or height.
	ErrInvalidDimension = errors.New("dimension out of valid range")

	// ErrDimensionOverflow indicates dimension calculation would overflow.
	ErrDimensionOverflow = errors.New("dimension calculation would overflow")

	// ErrInsufficientData indicates the pixel buffer is too small.
	ErrInsufficientData = errors.New("pixel buffer too small for dimensions")

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

	// ErrInvalidQuality indicates quality is out of range.
	ErrInvalidQuality = errors.New("quality must be between 0 and 100")

	// ErrInvalidBitsPerSample indicates invalid bit depth.
	ErrInvalidBitsPerSample = errors.New("bits per sample out of valid range")

	// ErrResourceLimit indicates a resource limit was exceeded.
	ErrResourceLimit = errors.New("resource limit exceeded")

	// ErrInvalidStride indicates stride is invalid for dimensions.
	ErrInvalidStride = errors.New("stride invalid for image dimensions")
)

Common validation errors

View Source
var (
	// ErrEOF indicates end of file or data stream has been reached.
	// This is returned when attempting to read beyond available data.
	ErrEOF = errors.New("EOF")

	// ErrInvalidPosition indicates an invalid position was specified
	// for seeking or reading in the byte stream (e.g., negative position).
	ErrInvalidPosition = errors.New("invalid position")

	// ErrIntegerOverflow indicates an arithmetic operation would overflow.
	// This is used to prevent integer overflow vulnerabilities in calculations.
	ErrIntegerOverflow = errors.New("integer overflow")

	// ErrInvalidMarker indicates a malformed or invalid JPEG marker was encountered.
	// This includes markers with invalid codes or incorrect structure.
	ErrInvalidMarker = errors.New("invalid JPEG marker")

	// ErrInvalidLength indicates an invalid length field was encountered.
	// This includes negative lengths, lengths that exceed remaining data,
	// or lengths that are too small for the expected data structure.
	ErrInvalidLength = errors.New("invalid length")

	// ErrOutOfBounds indicates an array or slice access would be out of bounds.
	// This is used to prevent buffer overflows and panic conditions.
	ErrOutOfBounds = errors.New("index out of bounds")
)
View Source
var (
	ErrNotJPEG       = errors.New("not a valid JPEG file")
	ErrTruncatedFile = errors.New("truncated file")
	ErrNoSOFMarker   = errors.New("no SOF marker found")
)

Format detection errors

View Source
var (
	// ErrNotValidJPEG is returned when data does not start with JPEG SOI marker.
	ErrNotValidJPEG = errors.New("data is not a valid JPEG: missing SOI marker (0xFFD8)")

	// ErrNoDQTMarker is returned when a JPEG file contains no DQT markers.
	ErrNoDQTMarker = errors.New("JPEG contains no quantization table (DQT) markers")

	// ErrLosslessJPEG is returned for lossless JPEG (SOF3) where quality estimation
	// is not applicable since lossless compression does not use quantization.
	ErrLosslessJPEG = errors.New("quality estimation not applicable to lossless JPEG (SOF3)")

	// ErrEmptyTables is returned when no quantization tables are provided.
	ErrEmptyTables = errors.New("no quantization tables provided")
)
View Source
var EncoderQualityMappings = map[EncoderFamily]EncoderQualityMapping{
	EncoderLibJPEG: {
		Name:             "libjpeg/IJG",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},
	EncoderPhotoshop: {
		Name:             "Adobe Photoshop",
		Curve:            photoshopQualityCurve,
		ScaleMin:         1,
		ScaleMax:         12,
		UsesLibjpegScale: false,
	},
	EncoderMozJPEG: {
		Name:             "MozJPEG",
		Curve:            mozjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},
	EncoderUnknown: {
		Name:             "Unknown (libjpeg default)",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},

	EncoderCanon: {
		Name:             "Canon",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},
	EncoderNikon: {
		Name:             "Nikon",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},
	EncoderSony: {
		Name:             "Sony",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},
	EncoderApple: {
		Name:             "Apple",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},
	EncoderSamsung: {
		Name:             "Samsung",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},

	EncoderF5James: {
		Name:             "F5/James",
		Curve:            libjpegQualityCurve,
		ScaleMin:         1,
		ScaleMax:         100,
		UsesLibjpegScale: true,
	},
}

EncoderQualityMappings maps encoder families to their quality curve definitions. This registry enables looking up the appropriate quality curve for any detected encoder.

View Source
var ErrOverflow = errors.New("arithmetic overflow")

ErrOverflow indicates an arithmetic operation would overflow.

View Source
var ErrUnderflow = errors.New("arithmetic underflow")

ErrUnderflow indicates an arithmetic operation would underflow.

View Source
var StandardChrominanceQuantTable = [BlockSize2]int{
	17, 18, 24, 47, 99, 99, 99, 99,
	18, 21, 26, 66, 99, 99, 99, 99,
	24, 26, 56, 99, 99, 99, 99, 99,
	47, 66, 99, 99, 99, 99, 99, 99,
	99, 99, 99, 99, 99, 99, 99, 99,
	99, 99, 99, 99, 99, 99, 99, 99,
	99, 99, 99, 99, 99, 99, 99, 99,
	99, 99, 99, 99, 99, 99, 99, 99,
}

StandardChrominanceQuantTable is the standard chrominance quantization table from ITU-T T.81 Annex K.1 for quality 50.

View Source
var StandardLuminanceQuantTable = [BlockSize2]int{
	16, 11, 10, 16, 24, 40, 51, 61,
	12, 12, 14, 19, 26, 58, 60, 55,
	14, 13, 16, 24, 40, 57, 69, 56,
	14, 17, 22, 29, 51, 87, 80, 62,
	18, 22, 37, 56, 68, 109, 103, 77,
	24, 35, 55, 64, 81, 104, 113, 92,
	49, 64, 78, 87, 103, 121, 120, 101,
	72, 92, 95, 98, 112, 100, 103, 99,
}

StandardLuminanceQuantTable is the standard luminance quantization table from ITU-T T.81 Annex K.1 for quality 50.

View Source
var StdEncoderACChrominanceBits = [16]int{
	0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119,
}

StdEncoderACChrominanceBits contains the number of Huffman codes of each length (1-16 bits) for the standard AC chrominance table.

Defined in ITU-T T.81 Annex K, Section K.3.3.2 (Table K.6). Used for encoding AC coefficients in Cb and Cr components.

View Source
var StdEncoderACChrominanceValues = []byte{}/* 162 elements not displayed */

StdEncoderACChrominanceValues contains the symbol values for the standard AC chrominance Huffman table, ordered by increasing code length.

Defined in ITU-T T.81 Annex K, Section K.3.3.2 (Table K.6). Contains 162 symbols representing all valid run/size combinations.

View Source
var StdEncoderACLuminanceBits = [16]int{
	0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125,
}

StdEncoderACLuminanceBits contains the number of Huffman codes of each length (1-16 bits) for the standard AC luminance table.

Defined in ITU-T T.81 Annex K, Section K.3.3.2 (Table K.5). AC tables encode run/size pairs where:

  • Upper 4 bits = run length (number of preceding zero coefficients)
  • Lower 4 bits = size (category of the non-zero coefficient)

Special symbols: 0x00 = EOB (End of Block), 0xF0 = ZRL (16 zeros)

View Source
var StdEncoderACLuminanceValues = []byte{}/* 162 elements not displayed */

StdEncoderACLuminanceValues contains the symbol values for the standard AC luminance Huffman table, ordered by increasing code length.

Defined in ITU-T T.81 Annex K, Section K.3.3.2 (Table K.5). Contains 162 symbols representing all valid run/size combinations.

View Source
var StdEncoderDCChrominanceBits = [16]int{
	0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
}

StdEncoderDCChrominanceBits contains the number of Huffman codes of each length (1-16 bits) for the standard DC chrominance table.

Defined in ITU-T T.81 Annex K, Section K.3.3.1 (Table K.4). Used for encoding DC coefficient differences in Cb and Cr components.

View Source
var StdEncoderDCChrominanceValues = []byte{
	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
}

StdEncoderDCChrominanceValues contains the symbol values for the standard DC chrominance Huffman table, ordered by increasing code length.

Defined in ITU-T T.81 Annex K, Section K.3.3.1 (Table K.4).

View Source
var StdEncoderDCLuminanceBits = [16]int{
	0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
}

StdEncoderDCLuminanceBits contains the number of Huffman codes of each length (1-16 bits) for the standard DC luminance table.

This array is defined in ITU-T T.81 Annex K, Section K.3.3.1 (Table K.3). It specifies how many codes exist for each bit length in the Huffman tree. For DC coefficients, this encodes the "category" (number of additional bits needed to represent the DC difference value).

The standard DC luminance table has 12 symbols (categories 0-11), with the following code length distribution:

  • 1 code of length 2
  • 5 codes of length 3
  • 1 code of length 4
  • 1 code each of lengths 5-9
View Source
var StdEncoderDCLuminanceValues = []byte{
	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
}

StdEncoderDCLuminanceValues contains the symbol values for the standard DC luminance Huffman table, ordered by increasing code length.

Defined in ITU-T T.81 Annex K, Section K.3.3.1 (Table K.3). These represent DC coefficient categories (0-11), where each category indicates how many additional bits follow the Huffman code to encode the actual DC difference value.

View Source
var UnzigzagOrder [BlockSize2]int

UnzigzagOrder is the inverse of ZigzagOrder.

View Source
var ZigzagOrder = [BlockSize2]int{
	0, 1, 8, 16, 9, 2, 3, 10,
	17, 24, 32, 25, 18, 11, 4, 5,
	12, 19, 26, 33, 40, 48, 41, 34,
	27, 20, 13, 6, 7, 14, 21, 28,
	35, 42, 49, 56, 57, 50, 43, 36,
	29, 22, 15, 23, 30, 37, 44, 51,
	58, 59, 52, 45, 38, 31, 39, 46,
	53, 60, 61, 54, 47, 55, 62, 63,
}

ZigzagOrder is the zigzag scan order for 8x8 blocks. This is used to order DCT coefficients from low to high frequency.

Functions

func AnalyzeDCTDistribution

func AnalyzeDCTDistribution(coefficients []int) float64

AnalyzeDCTDistribution analyzes DCT coefficient distribution for statistical anomalies that indicate re-encoding.

Natural images have characteristic DCT coefficient distributions: - DC coefficients follow roughly normal distribution - AC coefficients follow Laplacian (double exponential) distribution - Higher frequency coefficients are more likely to be zero

Re-encoded images show deviations from these patterns: - "Holes" in the histogram from double quantization - Abnormal zero-run distributions - Non-Laplacian AC coefficient distributions

Parameters:

  • coefficients: Slice of DCT coefficients to analyze

Returns a score from 0.0 to 1.0 indicating anomaly level. Higher scores indicate stronger deviation from expected patterns.

func CalculateMCUCount

func CalculateMCUCount(width, height int, components []EncoderComponentSpec) (mcuCols, mcuRows, totalMCUs int)

CalculateMCUCount calculates the number of MCUs needed for an image.

Parameters:

  • width: Image width in pixels
  • height: Image height in pixels
  • components: Slice of component specifications

Returns:

  • mcuCols: Number of MCU columns
  • mcuRows: Number of MCU rows
  • totalMCUs: Total number of MCUs

func CalculateReEncodingLikelihood

func CalculateReEncodingLikelihood(data []byte, tables map[int][64]int) float64

CalculateReEncodingLikelihood calculates a combined re-encoding likelihood score by integrating multiple detection signals.

The function combines: 1. Double quantization patterns in tables 2. Luminance/chrominance quality mismatch 3. DCT coefficient distribution anomalies

Parameters:

  • data: Raw JPEG file bytes (used for DCT analysis)
  • tables: Quantization tables extracted from the JPEG

Returns a score from 0.0 to 1.0 indicating re-encoding likelihood. Values above 0.5 suggest the image has likely been re-encoded.

func CalculateTableHash

func CalculateTableHash(table [64]int) uint64

CalculateTableHash computes a fast hash of a quantization table for comparison purposes. Uses FNV-1a style hashing.

Parameters:

  • table: The quantization table to hash

Returns:

  • uint64: A hash value for the table

func CheckCharacteristicRatios

func CheckCharacteristicRatios(table [64]int, expected []float64) float64

CheckCharacteristicRatios checks how well a table's coefficient ratios match expected ratios and returns a similarity score.

Parameters:

  • table: The observed quantization table
  • expected: Expected ratios [coeff1/coeff0, coeff2/coeff0, ...] where indices correspond to positions 1, 8, 9, 16 respectively

Returns:

  • float64: Similarity score from 0.0 (no match) to 1.0 (perfect match)

func CheckedAddInt

func CheckedAddInt(a, b int) (int, error)

CheckedAddInt adds two int values with overflow checking. Returns the result and an error if overflow would occur.

func CheckedAddInt64

func CheckedAddInt64(a, b int64) (int64, error)

CheckedAddInt64 adds two int64 values with overflow checking. Returns the result and an error if overflow would occur.

func CheckedMulInt

func CheckedMulInt(a, b int) (int, error)

CheckedMulInt multiplies two int values with overflow checking. Returns the result and an error if overflow would occur.

func CheckedMulInt64

func CheckedMulInt64(a, b int64) (int64, error)

CheckedMulInt64 multiplies two int64 values with overflow checking. Returns the result and an error if overflow would occur.

func CheckedSubInt

func CheckedSubInt(a, b int) (int, error)

CheckedSubInt subtracts two int values with underflow checking. Returns the result and an error if underflow would occur.

func CheckedSubInt64

func CheckedSubInt64(a, b int64) (int64, error)

CheckedSubInt64 subtracts two int64 values with underflow checking. Returns the result and an error if underflow would occur.

func ClampBlock

func ClampBlock(block *[BlockSize2]float64, max float64)

ClampBlock clamps all values in a block to [0, max].

func ComputeTableHash

func ComputeTableHash(table [64]int) string

ComputeTableHash generates a SHA-256 hash from a quantization table. The hash is computed from the normalized table values, ensuring consistent hashes regardless of table storage order.

Parameters:

  • table: A 64-element quantization table in row-major order

Returns:

  • A hex-encoded SHA-256 hash string (64 characters)

The function handles both 8-bit and 16-bit precision tables by including all significant bytes in the hash computation.

func ComputeTablesHash

func ComputeTablesHash(tables map[int][64]int) string

ComputeTablesHash generates a SHA-256 hash from multiple quantization tables. This is useful for creating a combined signature from all tables in a JPEG.

Parameters:

  • tables: Map of quantization tables indexed by table ID

Returns:

  • A hex-encoded SHA-256 hash string (64 characters)

func Decode

func Decode(r io.Reader) (img image.Image, err error)

Decode reads a JPEG image from r and returns it as an image.Image. It automatically detects the format and uses the appropriate decoder.

Supported formats include standard JPEG (baseline, extended, progressive, lossless), JPEG 2000, JPEG XL, JPEG XR, JPEG-LS, JPEG XT (HDR), JPEG XS (low-latency), and more. See SupportedFormats() for the complete list.

The returned image type depends on the source:

  • Grayscale images: *image.Gray or *image.Gray16
  • Color images: *image.RGBA

Returns an error if:

  • The reader is nil (ErrNilReader)
  • The reader contains no data (ErrEmptyData)
  • The format cannot be detected or decoded

Example:

file, _ := os.Open("image.jpg")
defer file.Close()
img, err := jpeg.Decode(file)
if err != nil {
    log.Fatal(err)
}
// Use img as image.Image
Example

ExampleDecode demonstrates basic JPEG decoding. The Decode function reads a JPEG image and returns an image.Image.

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/0verkilll/jpeg"
)

// createExampleJPEG creates a minimal valid baseline JPEG for examples.
// This returns a 1x1 grayscale JPEG image.
func createExampleJPEG() []byte {
	return []byte{

		0xFF, 0xD8,

		0xFF, 0xE0, 0x00, 0x10,
		'J', 'F', 'I', 'F', 0x00,
		0x01, 0x01,
		0x00,
		0x00, 0x01,
		0x00, 0x01,
		0x00, 0x00,

		0xFF, 0xDB, 0x00, 0x43, 0x00,

		16, 11, 10, 16, 24, 40, 51, 61,
		12, 12, 14, 19, 26, 58, 60, 55,
		14, 13, 16, 24, 40, 57, 69, 56,
		14, 17, 22, 29, 51, 87, 80, 62,
		18, 22, 37, 56, 68, 109, 103, 77,
		24, 35, 55, 64, 81, 104, 113, 92,
		49, 64, 78, 87, 103, 121, 120, 101,
		72, 92, 95, 98, 112, 100, 103, 99,

		0xFF, 0xC0, 0x00, 0x0B,
		0x08,
		0x00, 0x01,
		0x00, 0x01,
		0x01,
		0x01,
		0x11,
		0x00,

		0xFF, 0xC4, 0x00, 0x1F, 0x00,
		0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
		0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
		0x08, 0x09, 0x0A, 0x0B,

		0xFF, 0xC4, 0x00, 0xB5, 0x10,
		0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
		0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D,
		0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
		0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
		0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
		0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
		0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16,
		0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
		0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
		0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
		0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
		0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
		0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
		0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
		0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
		0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
		0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
		0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
		0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
		0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
		0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,
		0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
		0xF9, 0xFA,

		0xFF, 0xDA, 0x00, 0x08,
		0x01,
		0x01, 0x00,
		0x00, 0x3F, 0x00,

		0xFB, 0xD3, 0x28, 0xA6,

		0xFF, 0xD9,
	}
}

func main() {
	// Create sample JPEG data (in real use, this would come from a file)
	jpegData := createExampleJPEG()

	// Decode the JPEG image
	img, err := jpeg.Decode(bytes.NewReader(jpegData))
	if err != nil {
		log.Fatal(err)
	}

	// Use the decoded image
	bounds := img.Bounds()
	fmt.Printf("Decoded image: %dx%d pixels\n", bounds.Dx(), bounds.Dy())
}
Output:
Decoded image: 1x1 pixels

func DecodeACValue

func DecodeACValue(runSize byte, additionalBits uint16) (runLength int, value int)

DecodeACValue decodes an AC coefficient from run/size and additional bits.

func DecodeDCValue

func DecodeDCValue(category byte, additionalBits uint16) int

DecodeDCValue decodes a DC coefficient from category and additional bits.

func DetectDoubleQuantization

func DetectDoubleQuantization(table [64]int) float64

DetectDoubleQuantization analyzes a quantization table for patterns that indicate double quantization (re-encoding).

When a JPEG is re-encoded, the quantization table values show characteristic patterns because the DCT coefficients have already been quantized once. This creates:

  • Periodicity in coefficient values
  • "Ghost" steps where certain values appear more frequently
  • Non-uniform spacing between quantization steps

The detection looks for:

  1. GCD patterns: If many coefficients share a common divisor, it suggests previous quantization with that step size
  2. Histogram gaps: Re-encoding creates characteristic gaps in the histogram of coefficient values
  3. Coefficient ratio anomalies: The ratios between certain coefficients deviate from expected patterns

Parameters:

  • table: The quantization table to analyze

Returns a score from 0.0 to 1.0 indicating likelihood of double quantization. Higher scores indicate stronger evidence of re-encoding.

func DetectLocale

func DetectLocale() string

DetectLocale automatically detects the system locale from environment variables.

It checks the following environment variables in order:

  • LC_ALL
  • LC_MESSAGES
  • LANG

The detected locale is normalized to the format used by this package (e.g., "en-US"). Common system formats like "en_US.UTF-8" are converted to "en-US".

If the detected locale is not in the list of supported locales returned by GetSupportedLocales(), or if no locale can be detected, it falls back to "en-US".

Example:

// Auto-detect and create translator
locale := jpeg.DetectLocale()
translator, err := jpeg.NewTranslator(locale)
if err != nil {
    log.Fatal(err)
}
jpeg.SetTranslator(translator)

Example - Check what was detected:

locale := jpeg.DetectLocale()
fmt.Printf("Detected locale: %s\n", locale)

Returns:

  • string: The detected locale code (e.g., "en-US", "es-ES") or "en-US" as fallback

func DetectQualityMismatch

func DetectQualityMismatch(lumQuality, chromQuality int) float64

DetectQualityMismatch detects when luminance and chrominance tables have significantly different quality levels, which can indicate re-encoding or post-processing.

When an image is edited and re-saved, the editor may use different quality settings than the original, creating a mismatch between the apparent quality of the luminance and chrominance channels.

Parameters:

  • lumQuality: Estimated quality from luminance table (1-100)
  • chromQuality: Estimated quality from chrominance table (1-100)

Returns a score from 0.0 to 1.0 indicating the severity of the mismatch. Values above 0.5 suggest significant mismatch that may indicate re-encoding.

func EncodeACValue

func EncodeACValue(runLength int, value int) (runSize byte, additionalBits uint16, nAdditionalBits int)

EncodeACValue encodes an AC coefficient with run-length. Returns the run/size byte (RRRRSSSS) and additional bits.

func EncodeCoefficientsToJPEG

func EncodeCoefficientsToJPEG(coefficients []int, meta *CoeffEncoderMetadata, opts *EncoderOptions) ([]byte, error)

EncodeCoefficientsToJPEG is a convenience function for encoding coefficients to JPEG. It creates a baseline encoder with the specified options and encodes the coefficients.

func EncodeDCValue

func EncodeDCValue(diff int) (category byte, additionalBits uint16, nAdditionalBits int)

EncodeDCValue encodes a DC coefficient difference. Returns the category (SSSS) and additional bits.

func ExtractBlock

func ExtractBlock(img *ImageData, component int, bx, by int) *[BlockSize2]float64

ExtractBlock extracts an 8x8 block from image data at position (bx, by).

func GetEncoderQualityCurve

func GetEncoderQualityCurve(encoder EncoderFamily, quality int) [64]int

GetEncoderQualityCurve returns the quantization table for a given encoder and quality setting. This is a convenience function that handles encoder lookup and defaults gracefully.

Parameters:

  • encoder: The encoder family
  • quality: Quality value in the encoder's native scale

Returns the quantization table for the specified encoder and quality.

func GetLogger

func GetLogger() logger.LeveledLogger

GetLogger returns the currently configured global logger, or nil if none is set.

When no logger is configured (nil), the library's logging calls are no-ops with zero performance overhead.

This function is thread-safe and can be called from multiple goroutines.

Example - Check if logging is enabled:

log := jpeg.GetLogger()
if log != nil {
    // Logger is configured, logging is active
    fmt.Println("Logging is enabled")
} else {
    fmt.Println("Logging is disabled")
}

Example - Temporarily swap loggers:

// Save current logger
original := jpeg.GetLogger()

// Set a debug logger temporarily
jpeg.SetLogger(debugLogger)

// ... perform operations ...

// Restore original logger
jpeg.SetLogger(original)

Note: This delegates to the logger package's global state.

func GetSupportedLocales

func GetSupportedLocales() []string

GetSupportedLocales returns the list of locales supported by this package.

It reads the list of embedded locale files and returns their locale codes.

The package ships with embedded locale files:

  • en-US (English)
  • es-ES (Spanish)
  • fr-FR (French)

The returned array is sorted alphabetically for consistency.

If the embedded filesystem cannot be read (which should never happen in normal operation), this function returns a fallback array containing only "en-US" to ensure graceful degradation.

Example:

locales := jpeg.GetSupportedLocales()
fmt.Println(locales)
// Output: [en-US es-ES fr-FR]

// Display available languages to user
for _, locale := range locales {
    fmt.Printf("- %s\n", locale)
}

Returns:

  • []string: Sorted array of supported locale codes

func IsSuperBox

func IsSuperBox(boxType string) bool

IsSuperBox returns true if the box type contains other boxes.

func IsSupported

func IsSupported(formatName string) bool

IsSupported checks if a format name is supported by this library. The name is compared case-insensitively and allows partial matches.

This is useful for checking user input or configuration values against the supported formats.

Example:

if jpeg.IsSupported("JPEG 2000") {
    fmt.Println("JPEG 2000 is supported")
}
if jpeg.IsSupported("jp2") {
    fmt.Println("JP2 is supported")
}
Example

ExampleIsSupported demonstrates checking if a format name is supported. The matching is case-insensitive and supports partial matches.

package main

import (
	"fmt"

	"github.com/0verkilll/jpeg"
)

func main() {
	// Check various format names
	fmt.Println("JPEG:", jpeg.IsSupported("JPEG"))
	fmt.Println("JPEG 2000:", jpeg.IsSupported("JPEG 2000"))
	fmt.Println("JPEG XL:", jpeg.IsSupported("JPEG XL"))
	fmt.Println("PNG:", jpeg.IsSupported("PNG"))
}
Output:
JPEG: true
JPEG 2000: true
JPEG XL: true
PNG: false

func LevelShift

func LevelShift(block *[BlockSize2]float64, bits int)

LevelShift applies level shifting to an 8x8 block (subtract 128 for 8-bit).

func LevelUnshift

func LevelUnshift(block *[BlockSize2]float64, bits int)

LevelUnshift reverses level shifting (add 128 for 8-bit).

func MCUDimensions

func MCUDimensions(components []EncoderComponentSpec) (mcuWidth, mcuHeight, blocksPerMCU int)

MCUDimensions calculates the MCU (Minimum Coded Unit) dimensions based on component sampling factors.

Parameters:

  • components: Slice of component specifications

Returns:

  • mcuWidth: Width of one MCU in pixels
  • mcuHeight: Height of one MCU in pixels
  • blocksPerMCU: Total number of 8x8 blocks per MCU

func MustAddInt

func MustAddInt(a, b int) int

MustAddInt adds two integers, panicking on overflow. Only use this in tests or where overflow is truly impossible.

func MustMulInt

func MustMulInt(a, b int) int

MustMulInt multiplies two integers, panicking on overflow. Only use this in tests or where overflow is truly impossible.

func NewTranslator

func NewTranslator(locale ...string) (*i18n.Translator, error)

NewTranslator creates an i18n translator with embedded locale translations.

It loads translation files that are embedded in the package binary, providing a batteries-included translation experience.

The created translator:

  • Loads from embedded locale files (no external files needed)
  • Uses "en-US" as the default/fallback locale
  • Sets the requested locale as the current locale
  • Supports all locales returned by GetSupportedLocales()

After creating the translator, pass it to SetTranslator() to enable automatic translation of all error messages in this package.

If the requested locale is not supported, an error is returned. Use GetSupportedLocales() to see the list of available locales.

Auto-Detection:

Call without arguments or with an empty string to auto-detect the locale from system environment variables (LC_ALL, LC_MESSAGES, LANG). If detection fails or the detected locale is not supported, it falls back to "en-US".

Example - Auto-Detect Locale (Recommended):

// Auto-detect locale from system environment
translator, err := jpeg.NewTranslator()
if err != nil {
    log.Fatal(err)
}
jpeg.SetTranslator(translator)

Example - Specific Language:

// Enable Spanish translations
translator, err := jpeg.NewTranslator("es-ES")
if err != nil {
    log.Fatal(err)
}
jpeg.SetTranslator(translator)

// Now all error messages will be in Spanish
data, err := Decode(invalidJPEG)
fmt.Println(err) // Error in Spanish!

Example - Runtime Language Switching:

translator, _ := jpeg.NewTranslator("en-US")
jpeg.SetTranslator(translator)

// Later, switch to French
translator.SetLocale("fr-FR")
// Errors now appear in French

Example - Checking Available Locales:

locales := jpeg.GetSupportedLocales()
fmt.Println("Supported languages:", locales)

// Create translator for first available locale
translator, err := jpeg.NewTranslator(locales[0])

Binary Size Impact:

The embedded locale files add approximately 1-2KB to the binary size
(~300-500 bytes per locale x 3 locales).

Parameters:

  • locale: Optional locale code (e.g., "en-US", "es-ES", "fr-FR"). Omit or pass empty string for auto-detect

Returns:

  • *i18n.Translator: Configured translator instance
  • error: Error if locale is not supported or initialization fails

Errors:

  • Returns error if the requested locale file doesn't exist
  • Returns error if i18n.New() fails to create the translator
  • Returns error if the embedded filesystem cannot be accessed

func NormalizeQualityToLibjpeg

func NormalizeQualityToLibjpeg(quality int, encoder EncoderFamily) int

NormalizeQualityToLibjpeg converts a quality value from an encoder's native scale to the libjpeg-equivalent 1-100 scale.

This enables comparison of quality settings across different encoders:

  • Photoshop quality 12 becomes approximately libjpeg quality 98
  • MozJPEG quality values are already on the 1-100 scale but may be adjusted
  • Unknown encoders default to pass-through (assumes libjpeg scale)

Parameters:

  • quality: Quality value in the encoder's native scale
  • encoder: The encoder family that produced the quality value

Returns the normalized quality on a libjpeg-compatible 1-100 scale.

func ParallelForEachFormat

func ParallelForEachFormat(files [][]byte, fn func(data []byte, format Format) interface{}) []interface{}

ParallelForEachFormat runs the given function on each file concurrently. Results are collected and returned in input order.

func PopulateEncoderDetection

func PopulateEncoderDetection(estimate *QualityEstimate, data []byte, tables map[int][64]int)

PopulateEncoderDetection fills in the encoder detection fields of a QualityEstimate based on combined analysis from all sources.

This function: - Sets DetectedEncoder field - Sets EncoderConfidence field - Sets ConfidenceBreakdown.EncoderDetection

Parameters:

  • estimate: The QualityEstimate to update
  • data: Raw JPEG file bytes (for APP marker analysis)
  • tables: Pre-extracted quantization tables

func ReverseEngineerEncoderQuality

func ReverseEngineerEncoderQuality(table [64]int, encoder EncoderFamily) int

ReverseEngineerEncoderQuality estimates the original quality setting used by an encoder to produce the given quantization table.

This function tries to find the quality value that would produce the closest match to the observed table when using the specified encoder's quality curve.

Parameters:

  • table: The observed quantization table from the JPEG file
  • encoder: The encoder family that produced the table

Returns the estimated quality in the encoder's native scale.

func SafeBlockCount

func SafeBlockCount(width, height int) (int, error)

SafeBlockCount calculates the number of 8x8 blocks needed for given dimensions.

func SafeBlockIndex

func SafeBlockIndex(blockX, blockY, blocksPerRow, totalBlocks int) (int, error)

SafeBlockIndex calculates DCT block index with bounds checking.

func SafeBufferSize

func SafeBufferSize(width, height, channels int) (int64, error)

SafeBufferSize calculates buffer size from width, height, and channels with overflow checking. Returns the size and an error if overflow would occur.

func SafeDivInt

func SafeDivInt(a, b int) (int, error)

SafeDivInt performs integer division with zero-divisor checking.

func SafeDivInt64

func SafeDivInt64(a, b int64) (int64, error)

SafeDivInt64 performs int64 division with zero-divisor checking.

func SafeMCUCount

func SafeMCUCount(width, height, hMax, vMax int) (int, error)

SafeMCUCount calculates the number of MCUs needed for given dimensions and sampling.

func SafePixelOffset

func SafePixelOffset(x, y, stride, bufLen int) (int, error)

SafePixelOffset calculates pixel offset with bounds checking. Returns the offset and an error if out of bounds.

func SafeStrideSize

func SafeStrideSize(width, channels int) (int, error)

SafeStrideSize calculates stride from width and channels with overflow checking.

func ScaleQuantTable

func ScaleQuantTable(table [BlockSize2]int, quality int) [BlockSize2]int

ScaleQuantTable scales a quantization table based on quality (1-100). Quality 50 gives the standard table, lower quality increases quantization.

func SetLogger

func SetLogger(l logger.LeveledLogger)

SetLogger sets the global logger for the jpeg package. This allows the application to provide a custom logger for capturing internal warnings, debug information, and other events from the library.

The logger must implement the logger.LeveledLogger interface from github.com/0verkilll/logger, which requires Debug, Info, Warn, Error, and Fatal methods.

Pass nil to disable logging (the default state).

This function is thread-safe and can be called from multiple goroutines.

Example - Using the logger package:

import "github.com/0verkilll/logger"

// Use the package's default logger
jpeg.SetLogger(logger.GetLogger())

Example - Using a custom logger implementation:

type MyLogger struct {
    underlying *slog.Logger
}

func (l *MyLogger) Debug(msg string, args ...any) {
    l.underlying.Debug(msg, args...)
}

func (l *MyLogger) Info(msg string, args ...any) {
    l.underlying.Info(msg, args...)
}

func (l *MyLogger) Warn(msg string, args ...any) {
    l.underlying.Warn(msg, args...)
}

func (l *MyLogger) Error(msg string, args ...any) {
    l.underlying.Error(msg, args...)
}

func (l *MyLogger) Fatal(msg string, args ...any) {
    l.underlying.Error(msg, args...)
    os.Exit(1)
}

myLogger := &MyLogger{underlying: slog.Default()}
jpeg.SetLogger(myLogger)

Example - Disable logging:

// Disable all logging
jpeg.SetLogger(nil)

Example - Using NopLogger explicitly:

// Explicitly use NopLogger (equivalent to nil)
jpeg.SetLogger(&jpeg.NopLogger{})

Note: This delegates to the logger package's global state, ensuring a single logger is shared across all packages using github.com/0verkilll/logger.

func SetTranslator

func SetTranslator(translator TranslatorProvider)

SetTranslator sets the global translator for this package. This allows the application to provide translations for error messages and other user-facing strings.

Pass nil to disable translations and use English defaults.

This function is thread-safe and can be called from multiple goroutines.

Example:

translator, _ := i18n.New(
    i18n.WithFileSystemLoader("locales"),
    i18n.WithDefaultLocale("en-US"),
)
jpeg.SetTranslator(translator)

func StoreBlock

func StoreBlock(img *ImageData, component int, bx, by int, block *[BlockSize2]float64)

StoreBlock stores an 8x8 block to image data at position (bx, by).

func SubsamplingQualityScore

func SubsamplingQualityScore(mode ChromaSubsamplingMode) float64

SubsamplingQualityScore returns a quality indicator score based on the chroma subsampling mode. Higher scores indicate higher quality intent.

Score mapping:

  • 4:4:4 = 1.0: No chroma subsampling indicates highest quality intent. The encoder preserved full color resolution, typical of high-quality professional workflows.
  • 4:2:2 = 0.7: Moderate horizontal chroma reduction. Used in broadcast and professional video workflows as a compromise.
  • 4:2:0 = 0.5: Standard consumer subsampling with both horizontal and vertical chroma reduction. Most common mode for photos and web images.
  • Unknown = 0.5: Default to moderate quality assumption.

Parameters:

  • mode: The detected ChromaSubsamplingMode

Returns a quality score from 0.0 to 1.0.

func ValidateBufferSize

func ValidateBufferSize(size int64) error

ValidateBufferSize checks if a buffer allocation size is safe. Returns an error if the size would exceed resource limits or overflow.

func ValidateDimensions

func ValidateDimensions(width, height int) error

ValidateDimensions validates width and height without full ImageData. Useful for early validation before allocating buffers.

func ValidateEncoderOptions

func ValidateEncoderOptions(opts *EncoderOptions) error

ValidateEncoderOptions validates encoder options. If opts is nil, returns nil (defaults will be used).

func ValidateImageData

func ValidateImageData(img *ImageData) error

ValidateImageData performs comprehensive validation of ImageData. Returns nil if valid, or a ValidationError with details if invalid.

func WriteAPP0

func WriteAPP0(w io.Writer) error

WriteAPP0 writes a JFIF APP0 marker to w.

The APP0 marker (0xFF 0xE0) contains JFIF metadata including: - JFIF identifier ("JFIF\0") - Version (1.01) - Pixel density units and values - Thumbnail dimensions (none in this implementation)

This function writes a minimal JFIF header with no thumbnail.

func WriteAPP0Version

func WriteAPP0Version(w io.Writer, major, minor byte) error

WriteAPP0Version writes a JFIF APP0 marker with the given version. JFIF spec allows 1.00, 1.01, or 1.02; f5.jar uses 1.00 when its canonical comment is preserved, 1.01 otherwise.

func WriteCOM

func WriteCOM(w io.Writer, comment string) error

WriteCOM writes a Comment marker to w.

Parameters:

  • comment: The comment string to embed

The COM marker (0xFF 0xFE) can contain arbitrary text data. It's commonly used for encoder identification (e.g., F5/James signature) or metadata.

Note: Very long comments may need to be split across multiple COM markers due to the 16-bit length field limitation.

func WriteDHT

func WriteDHT(w io.Writer, tables []HuffmanSpec) error

WriteDHT writes Define Huffman Table markers to w.

Parameters:

  • tables: Slice of Huffman table specifications

Each Huffman table specification includes: - Class (0 = DC, 1 = AC) - Table ID (0-3) - Bits array (count of codes for each length 1-16) - Values array (symbols in order of increasing code length)

func WriteDQT

func WriteDQT(w io.Writer, tables map[int][64]int) error

WriteDQT writes Define Quantization Table markers to w.

Parameters:

  • tables: Map of table ID (0-3) to quantization table values in natural order

The quantization values are written in zigzag order as required by the JPEG specification (ITU-T T.81 B.2.4.1). Each table has a precision/ID byte followed by 64 values (8-bit precision).

Multiple tables can be written in a single DQT segment.

func WriteEOI

func WriteEOI(w io.Writer) error

WriteEOI writes the End of Image marker to w.

The EOI marker (0xFF 0xD9) must appear at the very end of every valid JPEG file. It has no payload or length field.

func WriteSOF0

func WriteSOF0(w io.Writer, width, height int, components []EncoderComponentSpec) error

WriteSOF0 writes a Start of Frame marker for baseline DCT encoding.

Parameters:

  • width: Image width in pixels (1-65535)
  • height: Image height in pixels (1-65535)
  • components: Slice of component specifications

The SOF0 marker (0xFF 0xC0) defines the frame header for baseline sequential DCT encoding with Huffman coding. It includes: - Sample precision (always 8 bits for baseline) - Image dimensions - Number of components and their specifications

func WriteSOI

func WriteSOI(w io.Writer) error

WriteSOI writes the Start of Image marker to w.

The SOI marker (0xFF 0xD8) must appear at the very beginning of every valid JPEG file. It has no payload or length field.

func WriteSOS

func WriteSOS(w io.Writer, components []ScanComponent) error

WriteSOS writes a Start of Scan marker to w.

Parameters:

  • components: Slice of scan component specifications

The SOS marker (0xFF 0xDA) begins the entropy-coded segment. It includes: - Number of components in the scan - Component selector and table assignments - Spectral selection (Ss=0, Se=63 for baseline) - Successive approximation (Ah=0, Al=0 for baseline)

After the SOS marker, entropy-coded data follows until the next marker.

func ZigzagDecode

func ZigzagDecode(block *[BlockSize2]int) *[BlockSize2]int

ZigzagDecode reorders coefficients from zigzag order to natural order.

func ZigzagEncode

func ZigzagEncode(block *[BlockSize2]int) *[BlockSize2]int

ZigzagEncode reorders coefficients from natural order to zigzag order.

func ZigzagToNatural

func ZigzagToNatural(zigzagTable [BlockSize2]int) [BlockSize2]int

ZigzagToNatural converts a 64-entry quantization table from zigzag order (as stored in the JPEG DQT marker and returned by Decoder.QuantizationTable) into natural (row-major) order, which is the order expected by EncoderOptions.LuminanceQuantTable / ChrominanceQuantTable and by StandardLuminanceQuantTable / ScaleQuantTable.

natural[ZigzagOrder[i]] = zigzagTable[i]

Types

type APPMarkerHints

type APPMarkerHints struct {
	// JFIFVersion is the JFIF version from APP0 marker (e.g., "1.01", "1.02").
	JFIFVersion string

	// HasJFIFThumbnail indicates whether the JFIF marker contains a thumbnail.
	HasJFIFThumbnail bool

	// ExifMake is the camera manufacturer from APP1 EXIF Make tag.
	ExifMake string

	// ExifModel is the camera model from APP1 EXIF Model tag.
	ExifModel string

	// ExifSoftware is the software field from APP1 EXIF Software tag.
	ExifSoftware string

	// HasICCProfile indicates whether an APP2 ICC profile marker is present.
	HasICCProfile bool

	// HasPhotoshopMarker indicates whether an APP13 Photoshop marker is present.
	HasPhotoshopMarker bool

	// PhotoshopVersion is the Photoshop version extracted from APP13 marker.
	PhotoshopVersion string

	// Has8BIMResources indicates whether 8BIM resource blocks were found.
	Has8BIMResources bool

	// HasAdobeMarker indicates whether an APP14 Adobe marker is present.
	HasAdobeMarker bool

	// AdobeDCTVersion is the DCTEncodeVersion from APP14 Adobe marker.
	AdobeDCTVersion int

	// AdobeColorTransform is the ColorTransform value from APP14 Adobe marker.
	// Values: 0=Unknown, 1=YCbCr, 2=YCCK
	AdobeColorTransform int

	// CommentStrings contains all COM marker comment strings.
	CommentStrings []string

	// RawAPPMarkers contains all raw APP marker segments for further analysis.
	RawAPPMarkers []RawAPPMarker
}

APPMarkerHints contains encoder identification hints extracted from APP markers. This struct aggregates information from various application-specific markers that can help identify the encoder that produced a JPEG image.

func ExtractAPPMarkerHints

func ExtractAPPMarkerHints(data []byte) (*APPMarkerHints, error)

ExtractAPPMarkerHints scans JPEG data for all APP markers (APP0-APP15), COM markers, and extracts encoder-relevant information into APPMarkerHints.

Parameters:

  • data: Raw JPEG file bytes starting with SOI marker

Returns:

  • *APPMarkerHints: Struct containing all extracted marker hints
  • error: If data is not valid JPEG

The function handles multiple markers of the same type and extracts structured data from known marker formats.

type APPSegment

type APPSegment struct {
	AppType    int    // APP marker type (0-15)
	Identifier string // Application identifier (e.g., "JFIF", "Exif")
	Data       []byte // Application-specific data
}

APPSegment represents Application marker data.

type AlgorithmConfig

type AlgorithmConfig struct {
	// LeastSquares configures the least-squares matching algorithm.
	LeastSquares AlgorithmSettings

	// ScaleFactor configures the scale factor reverse engineering algorithm.
	ScaleFactor AlgorithmSettings

	// DCTHistogram configures the DCT coefficient histogram analysis algorithm.
	DCTHistogram AlgorithmSettings
}

AlgorithmConfig defines the configuration for all estimation algorithms.

type AlgorithmResult

type AlgorithmResult struct {
	// Method identifies which algorithm produced this result.
	Method EstimationMethod

	// Quality is the estimated quality level (1-100).
	Quality int

	// Confidence is the confidence level of this algorithm's estimate (0.0-1.0).
	Confidence float64

	// Weight is the configured weight for this algorithm.
	Weight float64
}

AlgorithmResult represents the result from a single estimation algorithm.

type AlgorithmSettings

type AlgorithmSettings struct {
	// Enabled indicates whether this algorithm should be used.
	Enabled bool

	// Weight is the relative weight of this algorithm in the combined estimate.
	// Higher weights give the algorithm more influence on the final quality value.
	Weight float64
}

AlgorithmSettings defines the configuration for a single estimation algorithm.

type ArithmeticLosslessEncoder

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

ArithmeticLosslessEncoder implements arithmetic lossless JPEG encoding.

func NewArithmeticLosslessEncoder

func NewArithmeticLosslessEncoder(opts *EncoderOptions) *ArithmeticLosslessEncoder

NewArithmeticLosslessEncoder creates a new arithmetic lossless encoder.

func NewArithmeticLosslessEncoderWithOptions

func NewArithmeticLosslessEncoderWithOptions(opts *EncoderOptions, losslessOpts *LosslessOptions) *ArithmeticLosslessEncoder

NewArithmeticLosslessEncoderWithOptions creates encoder with specific lossless options.

func (*ArithmeticLosslessEncoder) Encode

func (e *ArithmeticLosslessEncoder) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to arithmetic lossless JPEG bytes.

func (*ArithmeticLosslessEncoder) EncodeImage

func (e *ArithmeticLosslessEncoder) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to arithmetic lossless JPEG bytes.

func (*ArithmeticLosslessEncoder) Format

func (e *ArithmeticLosslessEncoder) Format() Format

Format returns the target encoding format.

func (*ArithmeticLosslessEncoder) Predictor

func (e *ArithmeticLosslessEncoder) Predictor() int

Predictor returns the current predictor mode.

func (*ArithmeticLosslessEncoder) SetPredictor

func (e *ArithmeticLosslessEncoder) SetPredictor(predictor int) error

SetPredictor sets the prediction mode (1-7).

func (*ArithmeticLosslessEncoder) SetQuality

func (e *ArithmeticLosslessEncoder) SetQuality(_ int) error

SetQuality is a no-op for lossless encoding.

type ArithmeticProgressiveEncoder

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

ArithmeticProgressiveEncoder implements arithmetic progressive JPEG encoding.

func NewArithmeticProgressiveEncoder

func NewArithmeticProgressiveEncoder(opts *EncoderOptions) *ArithmeticProgressiveEncoder

NewArithmeticProgressiveEncoder creates a new arithmetic progressive encoder.

func NewArithmeticProgressiveEncoderWithScript

func NewArithmeticProgressiveEncoderWithScript(opts *EncoderOptions, script *ScanScript) *ArithmeticProgressiveEncoder

NewArithmeticProgressiveEncoderWithScript creates encoder with custom scan script.

func (*ArithmeticProgressiveEncoder) Encode

func (e *ArithmeticProgressiveEncoder) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to arithmetic progressive JPEG bytes.

func (*ArithmeticProgressiveEncoder) EncodeImage

func (e *ArithmeticProgressiveEncoder) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to arithmetic progressive JPEG bytes.

func (*ArithmeticProgressiveEncoder) Format

Format returns the target encoding format.

func (*ArithmeticProgressiveEncoder) SetQuality

func (e *ArithmeticProgressiveEncoder) SetQuality(quality int) error

SetQuality sets the encoding quality (1-100).

type ArithmeticSequentialEncoder

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

ArithmeticSequentialEncoder implements arithmetic sequential JPEG encoding.

func NewArithmeticSequential12BitEncoder

func NewArithmeticSequential12BitEncoder(opts *EncoderOptions) *ArithmeticSequentialEncoder

NewArithmeticSequential12BitEncoder creates an arithmetic encoder with 12-bit precision.

func NewArithmeticSequentialEncoder

func NewArithmeticSequentialEncoder(opts *EncoderOptions) *ArithmeticSequentialEncoder

NewArithmeticSequentialEncoder creates a new arithmetic sequential encoder.

func (*ArithmeticSequentialEncoder) Encode

func (e *ArithmeticSequentialEncoder) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to arithmetic sequential JPEG bytes.

func (*ArithmeticSequentialEncoder) EncodeImage

func (e *ArithmeticSequentialEncoder) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to arithmetic sequential JPEG bytes.

func (*ArithmeticSequentialEncoder) Format

func (e *ArithmeticSequentialEncoder) Format() Format

Format returns the target encoding format.

func (*ArithmeticSequentialEncoder) SetQuality

func (e *ArithmeticSequentialEncoder) SetQuality(quality int) error

SetQuality sets the encoding quality (1-100).

type AsyncEventReader

type AsyncEventReader interface {
	// StartReading begins asynchronous event reading.
	StartReading(r io.Reader) error

	// ReadEvent reads the next event without blocking.
	// Returns io.EOF when no more events are available.
	ReadEvent() (*VisualEvent, error)

	// StopReading terminates the reading session.
	StopReading() error
}

AsyncEventReader provides asynchronous event reading. Implements ISP for streaming event access. Enables real-time processing of event streams.

type BaselineCoeffEncoder

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

BaselineCoeffEncoder wraps baselineEncoder for coefficient encoding.

func NewBaselineEncoderForCoefficients

func NewBaselineEncoderForCoefficients(opts *EncoderOptions) *BaselineCoeffEncoder

NewBaselineEncoderForCoefficients creates a new encoder for coefficient encoding. This encoder can encode pre-computed DCT coefficients back to a valid JPEG.

func (*BaselineCoeffEncoder) EncodeCoefficients

func (e *BaselineCoeffEncoder) EncodeCoefficients(coefficients []int, meta *CoeffEncoderMetadata) ([]byte, error)

EncodeCoefficients creates a JPEG from pre-computed DCT coefficients.

Parameters:

  • coefficients: []int of quantized DCT coefficients in the order extracted by decoder (each block is 64 coefficients in zigzag order, blocks interleaved by MCU)
  • meta: metadata about the image (dimensions, component count, quant tables)

Returns the encoded JPEG bytes or an error.

func (*BaselineCoeffEncoder) SetOptions

func (e *BaselineCoeffEncoder) SetOptions(opts *EncoderOptions) error

SetOptions sets new encoder options.

func (*BaselineCoeffEncoder) SetQuality

func (e *BaselineCoeffEncoder) SetQuality(quality int) error

SetQuality sets the encoding quality (0-100).

type BasicFormatInfo

type BasicFormatInfo struct {
	Name        string
	Description string
}

BasicFormatInfo contains basic name and description for a format.

type BatchDetector

type BatchDetector interface {
	// DetectBatch detects formats for multiple byte slices concurrently.
	// Returns results in the same order as input.
	DetectBatch(files [][]byte) []DetectionResult

	// DetectBatchWithInfo detects formats with detailed info for multiple files.
	DetectBatchWithInfo(files [][]byte) []DetectionResult
}

BatchDetector detects formats for multiple files concurrently.

func NewConcurrentDetector

func NewConcurrentDetector(workers int) BatchDetector

NewConcurrentDetector creates a new concurrent detector with the specified worker count. If workers is 0, it defaults to the number of CPUs.

func NewConcurrentDetectorWithDetector

func NewConcurrentDetectorWithDetector(workers int, detector FormatDetector) BatchDetector

NewConcurrentDetectorWithDetector creates a concurrent detector with a custom detector.

type BitStreamReader

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

BitStreamReader reads bits from an underlying io.Reader with JPEG byte unstuffing.

func NewBitStreamReader

func NewBitStreamReader(r io.Reader) *BitStreamReader

NewBitStreamReader creates a new bit stream reader.

func (*BitStreamReader) ReadBits

func (br *BitStreamReader) ReadBits(nBits int) (uint32, error)

ReadBits reads the given number of bits.

type BitStreamWriter

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

BitStreamWriter writes bits to an underlying io.Writer with JPEG byte stuffing.

func NewBitStreamWriter

func NewBitStreamWriter(w io.Writer) *BitStreamWriter

NewBitStreamWriter creates a new bit stream writer.

func (*BitStreamWriter) BytesWritten

func (bw *BitStreamWriter) BytesWritten() int

BytesWritten returns the number of bytes written.

func (*BitStreamWriter) Error

func (bw *BitStreamWriter) Error() error

Error returns the first error encountered.

func (*BitStreamWriter) Flush

func (bw *BitStreamWriter) Flush() error

Flush writes any remaining bits, padding with 1s.

func (*BitStreamWriter) WriteBits

func (bw *BitStreamWriter) WriteBits(bits uint32, nBits int) error

WriteBits writes the given number of bits.

func (*BitStreamWriter) WriteCode

func (bw *BitStreamWriter) WriteCode(code HuffmanEncoderCode) error

WriteCode writes a Huffman code.

type BlockReconstructor

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

BlockReconstructor handles the reconstruction of 8x8 pixel blocks from quantized DCT coefficients during JPEG decoding.

The reconstruction pipeline follows the JPEG standard (ITU-T T.81):

  1. Zigzag decode: Convert coefficients from zigzag order to natural 8x8 order
  2. Dequantize: Multiply coefficients by quantization table values
  3. IDCT: Transform from frequency domain to spatial domain
  4. Level unshift: Add 128 (for 8-bit samples) to restore original range
  5. Clamp: Limit values to valid range [0, 255]

func NewBlockReconstructor

func NewBlockReconstructor(bits int) *BlockReconstructor

NewBlockReconstructor creates a new BlockReconstructor for the given sample precision. For standard 8-bit JPEG, use bits=8.

func NewBlockReconstructorWithDCT

func NewBlockReconstructorWithDCT(bits int, dct DCTTransformer) *BlockReconstructor

NewBlockReconstructorWithDCT creates a new BlockReconstructor with a specific DCT implementation. This allows using alternative DCT implementations (reference, integer) for testing or specific accuracy/performance requirements.

func (*BlockReconstructor) Reconstruct

func (br *BlockReconstructor) Reconstruct(coeffs *[BlockSize2]int, qtable *[BlockSize2]int) *[BlockSize2]byte

Reconstruct transforms quantized DCT coefficients to pixel values.

Parameters:

  • coeffs: Quantized DCT coefficients in zigzag order (as stored in JPEG)
  • qtable: Quantization table in zigzag order (as stored in JPEG DQT marker)

Returns:

  • Reconstructed pixel values as bytes, clamped to [0, 255]

The method performs the complete reconstruction pipeline:

  1. Dequantize in zigzag order (both coeffs and qtable are zigzag)
  2. Zigzag decode to natural 8x8 order
  3. Apply IDCT to transform to spatial domain
  4. Apply level unshift (+128 for 8-bit)
  5. Clamp to valid pixel range [0, 255]

func (*BlockReconstructor) ReconstructToFloat

func (br *BlockReconstructor) ReconstructToFloat(coeffs *[BlockSize2]int, qtable *[BlockSize2]int) *[BlockSize2]float64

ReconstructToFloat transforms quantized DCT coefficients to floating-point pixel values. This variant is useful when further processing is needed before final conversion to bytes.

Parameters:

  • coeffs: Quantized DCT coefficients in zigzag order
  • qtable: Quantization table in zigzag order (as stored in JPEG DQT marker)

Returns:

  • Reconstructed pixel values as float64, NOT clamped (allows further processing)

type BufferError

type BufferError struct {
	Operation  string // The operation that failed (e.g., "read", "write", "allocate")
	Position   int    // Position in the buffer where error occurred
	Expected   int    // Expected buffer size or position
	Actual     int    // Actual buffer size or position
	BufferName string // Name of the buffer (e.g., "pixel buffer", "output buffer")
	Cause      error  // Underlying cause
}

BufferError represents a buffer-related error during encoding. It provides position information for debugging.

func NewBufferError

func NewBufferError(operation, bufferName string, position, expected, actual int, cause error) *BufferError

NewBufferError creates a new BufferError.

func (*BufferError) Error

func (e *BufferError) Error() string

Error implements the error interface.

func (*BufferError) Is

func (e *BufferError) Is(target error) bool

Is implements the errors.Is interface.

func (*BufferError) Unwrap

func (e *BufferError) Unwrap() error

Unwrap implements the errors.Unwrap interface.

type ByteReader

type ByteReader interface {
	// ReadByte reads and returns the next byte.
	// Returns error if no more bytes available.
	ReadByte() (byte, error)

	// Position returns the current read position.
	Position() int

	// SetPosition sets the read position.
	SetPosition(pos int)

	// Remaining returns the number of unread bytes.
	Remaining() int

	// Len returns the total length of the data.
	Len() int
}

ByteReader defines an interface for reading bytes with position tracking. This abstraction allows the JPEG decoder to work with any byte source.

func NewByteReader

func NewByteReader(data []byte) ByteReader

NewByteReader creates a ByteReader from a byte slice.

type CODMarker

type CODMarker struct {
	CodingStyle                byte // Coding style flags
	ProgressionOrder           int  // Progression order
	QualityLayers              int  // Number of layers
	MultipleComponentTransform bool // MCT used
	DecompositionLevels        int  // Number of decomposition levels
	CodeBlockWidth             int  // Code-block width exponent
	CodeBlockHeight            int  // Code-block height exponent
	CodeBlockStyle             byte // Code-block style
	Transformation             int  // Wavelet transformation (0=9-7, 1=5-3)
}

CODMarker represents JPEG 2000 Coding Style Default marker.

type ChromaSubsampler

type ChromaSubsampler interface {
	// Subsample applies chroma subsampling to YCbCr image data.
	// Returns Y plane and subsampled Cb, Cr planes.
	Subsample(img *ImageData) (y, cb, cr []byte, cbWidth, cbHeight int)

	// Mode returns the subsampling mode.
	Mode() ChromaSubsampling
}

ChromaSubsampler performs chroma subsampling on YCbCr data.

func NewChromaSubsampler

func NewChromaSubsampler(mode ChromaSubsampling) ChromaSubsampler

NewChromaSubsampler creates a chroma subsampler for the given mode.

type ChromaSubsampling

type ChromaSubsampling int

ChromaSubsampling represents chroma subsampling mode.

const (
	// Subsampling444 is no subsampling (full resolution chroma).
	Subsampling444 ChromaSubsampling = iota
	// Subsampling422 is horizontal 2:1 subsampling.
	Subsampling422
	// Subsampling420 is horizontal and vertical 2:1 subsampling.
	Subsampling420
	// Subsampling411 is horizontal 4:1 subsampling.
	Subsampling411
	// SubsamplingGrayscale is no chroma components.
	SubsamplingGrayscale
)

func (ChromaSubsampling) String

func (s ChromaSubsampling) String() string

String returns the subsampling mode name.

type ChromaSubsamplingMode

type ChromaSubsamplingMode int

ChromaSubsamplingMode represents the chroma subsampling mode detected in the JPEG.

const (
	// ChromaSubsamplingUnknown indicates the subsampling mode could not be determined.
	ChromaSubsamplingUnknown ChromaSubsamplingMode = iota
	// ChromaSubsampling444 indicates 4:4:4 subsampling (no chroma subsampling).
	ChromaSubsampling444
	// ChromaSubsampling422 indicates 4:2:2 subsampling (horizontal halving).
	ChromaSubsampling422
	// ChromaSubsampling420 indicates 4:2:0 subsampling (horizontal and vertical halving).
	ChromaSubsampling420
)

func DetectChromaSubsampling

func DetectChromaSubsampling(data []byte) ChromaSubsamplingMode

DetectChromaSubsampling analyzes JPEG data to detect the chroma subsampling mode by parsing the SOF marker for component sampling factors.

The sampling factors in SOF markers indicate how each component is sampled:

  • 4:4:4: All components have same sampling factors (e.g., Y:1x1, Cb:1x1, Cr:1x1)
  • 4:2:2: Y has 2x horizontal sampling vs chroma (e.g., Y:2x1, Cb:1x1, Cr:1x1)
  • 4:2:0: Y has 2x2 sampling vs chroma (e.g., Y:2x2, Cb:1x1, Cr:1x1)

Parameters:

  • data: Raw JPEG file bytes

Returns the detected ChromaSubsamplingMode, or ChromaSubsamplingUnknown if the mode cannot be determined.

func (ChromaSubsamplingMode) String

func (m ChromaSubsamplingMode) String() string

String returns the string representation of the ChromaSubsamplingMode.

type ChromaUpsampler

type ChromaUpsampler interface {
	// Upsample upsamples chroma planes (Cb, Cr) to match luma (Y) resolution.
	// Input: y, cb, cr are the plane data with their respective dimensions.
	// Output: yOut, cbOut, crOut are the planes at full luma resolution.
	// The Y plane passes through unchanged; Cb and Cr are upsampled.
	Upsample(y, cb, cr []byte, yWidth, yHeight, cbWidth, cbHeight int) (yOut, cbOut, crOut []byte)

	// Mode returns the chroma subsampling mode this upsampler handles.
	Mode() ChromaSubsampling
}

ChromaUpsampler performs chroma upsampling to restore subsampled chroma planes to full luma resolution for JPEG decoding.

func NewChromaUpsampler

func NewChromaUpsampler(mode ChromaSubsampling) ChromaUpsampler

NewChromaUpsampler creates a chroma upsampler for the given subsampling mode. Uses nearest-neighbor interpolation by default for speed.

func NewChromaUpsamplerWithMode

func NewChromaUpsamplerWithMode(mode ChromaSubsampling, upsamplingMode UpsamplingMode) ChromaUpsampler

NewChromaUpsamplerWithMode creates a chroma upsampler with specified interpolation.

type CodestreamParser

type CodestreamParser interface {
	// ParseSIZ parses Image and Tile Size marker.
	ParseSIZ(data []byte) (*SIZMarker, error)

	// ParseCOD parses Coding Style Default marker.
	ParseCOD(data []byte) (*CODMarker, error)

	// ParseQCD parses Quantization Default marker.
	ParseQCD(data []byte) (*QCDMarker, error)

	// ParseSOT parses Start of Tile-part marker.
	ParseSOT(data []byte) (*SOTMarker, error)
}

CodestreamParser parses JPEG 2000 codestream markers. Implements ISP for codestream marker parsing.

func DefaultCodestreamParser

func DefaultCodestreamParser() CodestreamParser

DefaultCodestreamParser returns the default CodestreamParser implementation.

func NewCodestreamParser

func NewCodestreamParser(validator SecurityValidator) CodestreamParser

NewCodestreamParser creates a new CodestreamParser with optional security validator. If validator is nil, uses the default security validator.

type CoeffEncoder

type CoeffEncoder interface {
	// EncodeCoefficients creates a JPEG from pre-computed DCT coefficients.
	// This is useful for steganography where coefficients are modified in-place.
	EncodeCoefficients(coefficients []int, meta *CoeffEncoderMetadata) ([]byte, error)
}

CoeffEncoder provides coefficient encoding capabilities. This is a specialized encoder for re-encoding JPEGs from DCT coefficients.

type CoeffEncoderMetadata

type CoeffEncoderMetadata struct {
	// Image dimensions
	Width  int
	Height int

	// Number of components (1 for grayscale, 3 for YCbCr)
	ComponentCount int

	// Chroma subsampling mode (for YCbCr images)
	Subsampling ChromaSubsampling

	// Quantization tables (map from table ID to 64-element table in zigzag order)
	// If nil, standard tables at quality 75 will be used
	QuantTables map[int][64]int

	// Quality (0-100) - used if QuantTables is nil
	Quality int
}

CoeffEncoderMetadata holds metadata needed to re-encode a JPEG from coefficients. This should be populated from a decoded JPEG's metadata.

type CoefficientExtractor

type CoefficientExtractor interface {
	// Extract extracts quantized DCT coefficients from JPEG image data.
	// Returns coefficients with frequency mode information (row, col, component).
	Extract(data []byte) ([]DCTCoefficient, error)

	// GetImageDimensions returns the width and height of the decoded image.
	GetImageDimensions() (width, height int)

	// GetComponentCount returns the number of color components (typically 3 for YCbCr).
	GetComponentCount() int
}

CoefficientExtractor defines the interface for extracting DCT coefficients from JPEG images.

func NewDecoder

func NewDecoder() CoefficientExtractor

NewDecoder creates a new JPEG coefficient extractor. Returns an implementation of CoefficientExtractor.

Use this when you need to extract raw DCT coefficients for analysis, such as steganalysis or forensics. For full image decoding, use NewImageDecoder.

type CoefficientRatio

type CoefficientRatio struct {
	// Position is the coefficient index in the quantization table (0-63).
	Position int

	// ExpectedRatio is the expected value of table[Position] / table[0].
	ExpectedRatio float64

	// Weight is the importance of this ratio in signature matching.
	// Higher weight means more significant for identification.
	Weight float64
}

CoefficientRatio represents the expected ratio of a specific coefficient position relative to the DC coefficient (position 0).

type ColorConversionStandard

type ColorConversionStandard int

ColorConversionStandard specifies which color conversion standard to use.

const (
	// ColorConversionBT601 uses ITU-R BT.601 color conversion (SD video).
	// This is the default and most common standard for JPEG images.
	ColorConversionBT601 ColorConversionStandard = iota

	// ColorConversionBT709 uses ITU-R BT.709 color conversion (HD video).
	// Use this for images that were encoded with HD video color space.
	ColorConversionBT709
)

func (ColorConversionStandard) String

func (c ColorConversionStandard) String() string

String returns the color conversion standard name.

type ColorConverter

type ColorConverter interface {
	// RGBToYCbCr converts RGB to YCbCr using specified standard.
	RGBToYCbCr(r, g, b uint8) (y, cb, cr uint8)

	// YCbCrToRGB converts YCbCr to RGB using specified standard.
	YCbCrToRGB(y, cb, cr uint8) (r, g, b uint8)

	// Standard returns the color conversion standard name.
	Standard() string
}

ColorConverter converts between color spaces.

func NewBT601Converter

func NewBT601Converter() ColorConverter

NewBT601Converter creates a BT.601 color converter.

func NewBT709Converter

func NewBT709Converter() ColorConverter

NewBT709Converter creates a BT.709 color converter.

type ColorSpace

type ColorSpace int

ColorSpace represents the color space of image data.

const (
	// ColorSpaceUnknown indicates unknown color space.
	ColorSpaceUnknown ColorSpace = iota
	// ColorSpaceGrayscale is single-channel grayscale.
	ColorSpaceGrayscale
	// ColorSpaceRGB is 3-channel RGB.
	ColorSpaceRGB
	// ColorSpaceRGBA is 4-channel RGBA.
	ColorSpaceRGBA
	// ColorSpaceYCbCr is 3-channel YCbCr (luminance + chrominance).
	ColorSpaceYCbCr
	// ColorSpaceCMYK is 4-channel CMYK.
	ColorSpaceCMYK
)

func (ColorSpace) Channels

func (cs ColorSpace) Channels() int

Channels returns the number of channels for this color space.

func (ColorSpace) String

func (cs ColorSpace) String() string

String returns the color space name.

type ComponentError

type ComponentError struct {
	ComponentID int    // Component ID (1=Y, 2=Cb, 3=Cr, etc.)
	Operation   string // Operation that failed
	Message     string // Error message
	Cause       error  // Underlying cause
}

ComponentError represents an error related to image component processing.

func NewComponentError

func NewComponentError(componentID int, operation, message string, cause error) *ComponentError

NewComponentError creates a new ComponentError.

func (*ComponentError) Error

func (e *ComponentError) Error() string

Error implements the error interface.

func (*ComponentError) Unwrap

func (e *ComponentError) Unwrap() error

Unwrap implements the errors.Unwrap interface.

type ComponentReconstructor

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

ComponentReconstructor manages reconstruction of a single color component, including DC prediction tracking across blocks.

func NewComponentReconstructor

func NewComponentReconstructor(componentID, qtableID, bits int) *ComponentReconstructor

NewComponentReconstructor creates a ComponentReconstructor for a specific color component.

func (*ComponentReconstructor) ComponentID

func (cr *ComponentReconstructor) ComponentID() int

ComponentID returns the component ID (0=Y, 1=Cb, 2=Cr).

func (*ComponentReconstructor) QuantTableID

func (cr *ComponentReconstructor) QuantTableID() int

QuantTableID returns the quantization table ID for this component.

func (*ComponentReconstructor) ReconstructBlock

func (cr *ComponentReconstructor) ReconstructBlock(coeffs *[BlockSize2]int, dcDiff int, qtable *[BlockSize2]int) *[BlockSize2]byte

ReconstructBlock reconstructs a single 8x8 block for this component. The dcDiff parameter is the differential DC coefficient from the JPEG stream. The qtable parameter is the quantization table for this component.

func (*ComponentReconstructor) Reset

func (cr *ComponentReconstructor) Reset()

Reset resets the DC predictor for this component. Call this at restart marker boundaries.

type ComponentSpec

type ComponentSpec struct {
	BitDepth             int  // Bit depth (with sign bit in MSB)
	Signed               bool // True if signed samples
	HorizontalSeparation int  // Horizontal sub-sampling
	VerticalSeparation   int  // Vertical sub-sampling
}

ComponentSpec represents component specification in SIZ marker.

type ConfidenceBreakdown

type ConfidenceBreakdown struct {
	// QuantizationTableScore is the confidence from quantization table matching (0.0-1.0).
	// This is weighted at 0.5 in the final calculation.
	QuantizationTableScore float64

	// APPMarkerScore is the confidence from APP marker analysis (0.0-1.0).
	// This is weighted at 0.3 in the final calculation.
	APPMarkerScore float64

	// HuffmanTableScore is the confidence from Huffman table analysis (0.0-1.0).
	// This is weighted at 0.2 in the final calculation.
	HuffmanTableScore float64

	// ContradictionPenalty is a multiplier penalty for conflicting signals (0.0-1.0).
	// A value of 0.0 means no penalty, 0.5 means 50% reduction, 1.0 means zero confidence.
	ContradictionPenalty float64

	// FinalConfidence is the calculated final confidence after applying weights and penalties.
	FinalConfidence float64

	// ContradictionDetails lists specific contradictions detected.
	// Examples: ["adobe-marker-with-camera-exif", "incompatible-table-source"]
	ContradictionDetails []string
}

ConfidenceBreakdown provides detailed confidence scoring from each detection method. It tracks contributions from quantization table analysis, APP marker parsing, and Huffman table analysis, along with any contradiction penalties.

type ConfidenceCalculator

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

ConfidenceCalculator calculates final confidence scores from multiple detection methods. It applies weighted averaging and contradiction penalties to produce a final confidence.

func NewConfidenceCalculator

func NewConfidenceCalculator() *ConfidenceCalculator

NewConfidenceCalculator creates a new ConfidenceCalculator with default weights. Default weights: quant=0.5, app=0.3, huffman=0.2

func (*ConfidenceCalculator) CalculateFinalConfidence

func (c *ConfidenceCalculator) CalculateFinalConfidence(breakdown *ConfidenceBreakdown) float64

CalculateFinalConfidence computes the final confidence score from a breakdown. It applies weighted averaging of the three detection methods and then applies any contradiction penalty.

Formula: finalConfidence = (quant*0.5 + app*0.3 + huffman*0.2) * (1 - penalty)

Parameters:

  • breakdown: The confidence breakdown with scores from each method

Returns:

  • The final confidence value between 0.0 and 1.0

func (*ConfidenceCalculator) DetectContradictions

func (c *ConfidenceCalculator) DetectContradictions(encoderFamily string, hints *APPMarkerHints) []string

DetectContradictions analyzes encoder family and APP marker hints to detect conflicting signals that indicate unreliable identification.

Common contradictions include:

  • Camera EXIF data with Adobe APP marker (camera didn't use Adobe software)
  • Mobile device EXIF with desktop software markers
  • libjpeg tables with proprietary encoder markers

Parameters:

  • encoderFamily: The detected encoder family ("camera", "adobe", "libjpeg", etc.)
  • hints: APP marker hints containing EXIF and other metadata

Returns:

  • A slice of contradiction descriptions, empty if no contradictions found

type Configurable

type Configurable interface {
	// GetOptions returns the current configuration options.
	GetOptions() *EncoderOptions

	// SetOptions sets new configuration options.
	// Returns an error if the options are invalid.
	SetOptions(opts *EncoderOptions) error
}

Configurable represents types that can be configured with options. Implements ISP for configuration management.

type DCPredictor

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

DCPredictor performs DC coefficient prediction for JPEG encoding.

func NewDCPredictor

func NewDCPredictor() *DCPredictor

NewDCPredictor creates a new DC predictor.

func (*DCPredictor) Predict

func (p *DCPredictor) Predict(component int, dc int) int

Predict returns the differential DC value and updates the predictor.

func (*DCPredictor) Reset

func (p *DCPredictor) Reset()

Reset resets the DC predictor (call at restart intervals).

func (*DCPredictor) Unpredict

func (p *DCPredictor) Unpredict(component int, diff int) int

Unpredict reconstructs the original DC value from differential.

type DCTCoefficient

type DCTCoefficient struct {
	// Value is the quantized DCT coefficient value
	Value int16

	// Row is the row position in the 8x8 DCT block (0-7)
	Row int

	// Col is the column position in the 8x8 DCT block (0-7)
	Col int

	// Component is the color component index (0=Y, 1=Cb, 2=Cr)
	Component int

	// BlockX is the horizontal block index in the image
	BlockX int

	// BlockY is the vertical block index in the image
	BlockY int
}

DCTCoefficient represents a single DCT coefficient with its position and metadata. This structure is used by the Fridrich steganalysis attack for per-frequency-mode. histogram analysis.

type DCTHistogramAnalyzer

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

DCTHistogramAnalyzer performs DCT coefficient histogram analysis for quality estimation. It implements a secondary quality estimation algorithm that analyzes the statistical distribution of quantized DCT coefficients.

func NewDCTHistogramAnalyzer

func NewDCTHistogramAnalyzer() *DCTHistogramAnalyzer

NewDCTHistogramAnalyzer creates a new DCT histogram analyzer with default settings. The analyzer uses a bucket width of 10 and supports coefficient values up to +/- 255.

func (*DCTHistogramAnalyzer) AnalyzeCoefficients

func (a *DCTHistogramAnalyzer) AnalyzeCoefficients(coefficients []int, blockSize int) (*DCTHistogramResult, error)

AnalyzeCoefficients performs complete histogram analysis on coefficient data. This is the primary entry point for analyzing raw coefficient values.

Parameters:

  • coefficients: Slice of quantized DCT coefficients
  • blockSize: Size of each DCT block (typically 64)

Returns:

  • *DCTHistogramResult: Complete analysis results
  • error: If analysis fails

func (*DCTHistogramAnalyzer) AnalyzeDCTCoefficients

func (a *DCTHistogramAnalyzer) AnalyzeDCTCoefficients(dctCoeffs []DCTCoefficient) (*DCTHistogramResult, error)

AnalyzeDCTCoefficients performs histogram analysis on DCTCoefficient structs. This integrates with the existing coefficient extraction from decoder.go.

Parameters:

  • dctCoeffs: Slice of DCTCoefficient structs (from Decoder.Extract())

Returns:

  • *DCTHistogramResult: Complete analysis results
  • error: If analysis fails

func (*DCTHistogramAnalyzer) CalculateHistogramSpread

func (a *DCTHistogramAnalyzer) CalculateHistogramSpread(histogram []HistogramBucket) float64

CalculateHistogramSpread calculates the spread (standard deviation) of a histogram. Higher spread indicates broader distribution (typically higher quality images).

Parameters:

  • histogram: Histogram buckets to analyze

Returns:

  • Standard deviation of the distribution

func (*DCTHistogramAnalyzer) EstimateQualityFromHistogram

func (a *DCTHistogramAnalyzer) EstimateQualityFromHistogram(histogram []HistogramBucket) (quality int, confidence float64)

EstimateQualityFromHistogram estimates JPEG quality from a coefficient histogram. The estimation is based on statistical properties:

  • Higher quality = broader distribution, lower zero percentage
  • Lower quality = narrower distribution clustered around zero

Parameters:

  • histogram: AC coefficient histogram buckets

Returns:

  • quality: Estimated quality level (1-100)
  • confidence: Confidence in the estimate (0.0-1.0)

func (*DCTHistogramAnalyzer) ExtractACHistogram

func (a *DCTHistogramAnalyzer) ExtractACHistogram(coefficients []int, blockSize int) []HistogramBucket

ExtractACHistogram extracts a histogram of AC coefficients from quantized DCT data. AC coefficients are all coefficients except the DC (position 0 in each block).

Parameters:

  • coefficients: Slice of quantized DCT coefficients (all blocks concatenated)
  • blockSize: Size of each DCT block (typically 64 for 8x8 blocks)

Returns:

  • Histogram buckets covering the range of AC coefficient values

func (*DCTHistogramAnalyzer) ExtractDCHistogram

func (a *DCTHistogramAnalyzer) ExtractDCHistogram(coefficients []int, blockSize int) []HistogramBucket

ExtractDCHistogram extracts a histogram of DC coefficients from quantized DCT data. DC coefficients are at position 0 of each block.

Parameters:

  • coefficients: Slice of quantized DCT coefficients (all blocks concatenated)
  • blockSize: Size of each DCT block (typically 64 for 8x8 blocks)

Returns:

  • Histogram buckets covering the range of DC coefficient values

type DCTHistogramResult

type DCTHistogramResult struct {
	// EstimatedQuality is the estimated JPEG quality (1-100) based on histogram analysis.
	EstimatedQuality int

	// Confidence is the confidence level of the quality estimate (0.0-1.0).
	Confidence float64

	// ACHistogram is the histogram of AC coefficients.
	ACHistogram []HistogramBucket

	// DCHistogram is the histogram of DC coefficients.
	DCHistogram []HistogramBucket

	// Spread is the standard deviation of the coefficient distribution.
	Spread float64

	// ZeroPercentage is the percentage of zero coefficients (0.0-1.0).
	ZeroPercentage float64

	// Kurtosis is the kurtosis of the distribution (peakedness).
	Kurtosis float64
}

DCTHistogramResult holds the results of DCT coefficient histogram analysis. This provides an independent quality estimate based on coefficient distribution.

type DCTImplementation

type DCTImplementation int

DCTImplementation specifies which DCT implementation to use for decoding.

const (
	// DCTDefault uses the recommended default implementation (AAN/float DCT).
	// Best balance of performance and accuracy for most use cases.
	DCTDefault DCTImplementation = iota

	// DCTReference uses the mathematically precise reference implementation.
	// Slower but more accurate, useful for verification and testing.
	DCTReference

	// DCTInteger uses the integer DCT implementation.
	// Currently wraps float DCT, reserved for future fixed-point optimization.
	DCTInteger
)

func (DCTImplementation) String

func (d DCTImplementation) String() string

String returns the DCT implementation name.

type DCTTransformer

type DCTTransformer interface {
	// Forward performs forward DCT on an 8x8 block.
	// Input values should be level-shifted (subtracted by 128 for 8-bit).
	Forward(block *[BlockSize2]float64)

	// Inverse performs inverse DCT on an 8x8 block.
	// Output values need to be level-shifted back (add 128 for 8-bit).
	Inverse(block *[BlockSize2]float64)
}

DCTTransformer performs forward and inverse DCT operations.

func NewAANDCT deprecated

func NewAANDCT() DCTTransformer

NewAANDCT is a deprecated alias for NewSeparableDCT. The original name was a misnomer: the implementation is a straightforward separable 2D DCT, not the Arai/Agui/Nakajima fast algorithm. The alias is retained for API stability.

Deprecated: Use NewSeparableDCT instead.

func NewDCT

func NewDCT() DCTTransformer

NewDCT returns the recommended default DCT transformer implementation.

This convenience function returns NewSeparableDCT(), which provides the best balance of performance and accuracy for most JPEG encoding and decoding use cases.

Performance vs Accuracy Tradeoffs:

  • NewSeparableDCT() (default): Fast floating-point separable 2D implementation with excellent accuracy. Roundtrip error < 1e-9. Recommended for production use.
  • NewReferenceDCT(): Slow but mathematically precise reference implementation. Best for verification and testing. Roundtrip error < 1e-10.
  • NewIntegerDCT(): Currently wraps the separable float DCT. Reserved for future fixed-point optimization targeting embedded systems or SIMD acceleration.

For custom DCT/IDCT operations or specific implementation requirements, use the individual constructor functions directly.

func NewIntegerDCT

func NewIntegerDCT() DCTTransformer

NewIntegerDCT creates an integer DCT transformer.

func NewReferenceDCT

func NewReferenceDCT() DCTTransformer

NewReferenceDCT creates a reference DCT transformer (slow but accurate).

func NewSeparableDCT

func NewSeparableDCT() DCTTransformer

NewSeparableDCT creates a new floating-point DCT transformer that applies the 1D DCT separably (rows then columns) with precomputed cosine values. Round-trip error is below 1e-9 for 8-bit inputs.

type DHTSegment

type DHTSegment struct {
	TableClass int     // 0 = DC table, 1 = AC table
	TableID    int     // Table destination identifier (0-3)
	Bits       [16]int // Number of codes of each length
	Values     []byte  // Symbol values
}

DHTSegment represents Define Huffman Table marker data.

type DQTSegment

type DQTSegment struct {
	Precision int        // 0 = 8-bit, 1 = 16-bit
	TableID   int        // Table destination identifier (0-3)
	Values    [64]uint16 // Quantization values in zigzag order
}

DQTSegment represents Define Quantization Table marker data.

type DecodeMetadata

type DecodeMetadata struct {
	// HDRMetadata contains HDR-specific metadata (JPEG XT)
	HDR *HDRDecodeMetadata

	// LightFieldMetadata contains light field metadata (JPEG Pleno)
	LightField *LightFieldDecodeMetadata

	// TrustMetadata contains trust/provenance metadata (JPEG Trust)
	Trust *TrustDecodeMetadata
}

DecodeMetadata contains format-specific metadata from decoding.

type DecodeResult

type DecodeResult struct {
	// Format is the detected JPEG format
	Format Format

	// Image is the decoded image for standard JPEG formats
	// This is nil for non-image formats like point clouds
	Image image.Image

	// HDRData contains HDR pixel data when HDROutputFloat32 is used
	// Each value is a linear light float32 in range [0, +inf)
	HDRData []float32

	// HDRUint16Data contains HDR pixel data when HDROutputUint16 is used
	// Each value is a 16-bit unsigned integer
	HDRUint16Data []uint16

	// LightFieldViews contains decoded light field views for JPEG Pleno
	// Each view is indexed by (u, v) coordinates
	LightFieldViews map[[2]int]image.Image

	// PointCloud contains decoded point cloud data for JPEG Pleno
	PointCloud *PointCloudResult

	// EventStream contains decoded events for JPEG XE
	EventStream *EventStreamResult

	// Metadata contains format-specific metadata
	Metadata *DecodeMetadata

	// Width and Height of the decoded image/data
	Width  int
	Height int

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

DecodeResult represents the result of a unified decode operation. It contains the decoded data in various possible formats depending on the input format and decoder options.

type Decoder

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

Decoder implements the CoefficientExtractor and ImageDecoder interfaces using a pure internal implementation without any pkg/ dependencies.

This adapter follows the SOLID Adapter pattern, wrapping the internal JPEG decoding functionality while providing a clean interface for the refactored architecture. The underlying implementation handles:

  • JPEG marker parsing (SOI, SOF, DHT, DQT, SOS, EOI)
  • Huffman table decoding
  • Quantized DCT coefficient extraction
  • De-zigzag transformation
  • IDCT pixel reconstruction (via Decode method)

This design allows the complex JPEG decoding logic to remain isolated while integrating cleanly with the new dependency-injected architecture.

func NewDecoderWithOptions

func NewDecoderWithOptions(opts *DecoderOptions) *Decoder

NewDecoderWithOptions creates a new JPEG decoder with custom options. The returned decoder implements both CoefficientExtractor and ImageDecoder.

DecoderOptions allows configuring:

  • DCT: Select DCT implementation (Default/AAN, Reference, Integer)
  • ColorConversion: Select color standard (BT.601, BT.709)
  • ChromaUpsampling: Select upsampling quality (NearestNeighbor, Bilinear)

Example:

opts := &jpeg.DecoderOptions{
    DCT:              jpeg.DCTReference,
    ColorConversion:  jpeg.ColorConversionBT601,
    ChromaUpsampling: jpeg.UpsamplingBilinear,
}
decoder := jpeg.NewDecoderWithOptions(opts)

func (*Decoder) ClearSignatureCache

func (d *Decoder) ClearSignatureCache()

ClearSignatureCache drops the cached signature for this decoder. Pre-leak-fix this removed the *Decoder entry from a package-level map and was the only way to avoid an unbounded leak. With the signature now on the Decoder receiver, the method is a courtesy: a Decoder that goes out of scope is reclaimed by the GC together with its signature, so callers no longer need to call ClearSignatureCache to bound memory.

func (*Decoder) Decode

func (d *Decoder) Decode(data []byte) (image.Image, error)

Decode decodes JPEG image data to a reconstructed pixel image.

The decoding pipeline:

  1. Parse JPEG markers and extract frame/scan information
  2. Extract quantized DCT coefficients from entropy-coded data
  3. For each 8x8 block: dequantize, apply IDCT, level unshift, clamp
  4. Assemble reconstructed blocks into Y, Cb, Cr planes
  5. Upsample chroma to match luma resolution (for 4:2:0, 4:2:2)
  6. Convert YCbCr to RGB using configured color standard
  7. Return assembled image

Returns:

  • *image.RGBA for color images (YCbCr, CMYK converted to RGB)
  • *image.Gray for grayscale images
  • error if the JPEG data is invalid or cannot be decoded

func (*Decoder) Extract

func (d *Decoder) Extract(data []byte) ([]DCTCoefficient, error)

Extract extracts quantized DCT coefficients from JPEG image data with frequency mode information (row, col, component).

The method:

  1. Parses JPEG structure (markers, tables, scan data)
  2. Decodes Huffman-encoded coefficient data
  3. Maps zigzag indices to (row, col) positions using zigzagToMode table
  4. Assigns component index (Y=0, Cb=1, Cr=2) to each coefficient
  5. Returns coefficients as DCTCoefficient structs

Coefficient Organization: The internal decoder returns coefficients in MCU-interleaved order (NOT planar) — this docstring previously claimed planar order and was misleading. For 4:2:0 subsampling each MCU writes its 4 Y blocks, then 1 Cb block, then 1 Cr block; for 4:4:4 each MCU writes Y, Cb, Cr per 8x8 position. This matches the order the Huffman decoder walks the JPEG bitstream and the order James R. Weeks' JpegEncoder.java builds its coeff[] array, so f5messageembed + f5.jar consume the SAME logical coefficient at each permutation index. Within each 64-element block the coefficients are in zigzag order (the JPEG bitstream's native layout); callers that need natural (row-major) order use ApplyDeZigZag. Verified 2026-05-23 by Go↔Java parity testing.

This method enriches each coefficient with its frequency mode position to enable per-mode histogram analysis for Fridrich steganalysis.

Parameters:

  • data: Raw JPEG file bytes

Returns:

  • []DCTCoefficient: Coefficients with mode information (Value, Row, Col, Component)
  • error: Any decoding errors

func (*Decoder) Format

func (d *Decoder) Format() Format

Format returns the detected JPEG format of the last decoded image.

This method allows efficient format checking without parsing the JPEG twice. The format is detected during Decode() and cached for later retrieval.

Returns FormatUnknown if:

  • No image has been decoded yet
  • The format detection failed during decode

Example - Check format after decoding:

decoder := jpeg.NewDecoderWithOptions(opts)
img, err := decoder.Decode(data)
if err != nil {
    return err
}
if decoder.Format() != jpeg.FormatBaselineJPEG {
    return errors.New("only baseline JPEG is supported")
}

func (*Decoder) GetComponentCount

func (d *Decoder) GetComponentCount() int

GetComponentCount returns the number of color components. Implements the CoefficientExtractor interface.

func (*Decoder) GetDimensions

func (d *Decoder) GetDimensions() (width, height int)

GetDimensions returns the width and height of the last decoded image.

This information is useful for:

  • Calculating total DCT blocks (width * height / 64)
  • Validating coefficient count
  • Logging and debugging

Returns (0, 0) if no image has been decoded yet.

func (*Decoder) GetImageDimensions

func (d *Decoder) GetImageDimensions() (width, height int)

GetImageDimensions returns the width and height of the decoded image. Implements the CoefficientExtractor interface.

func (*Decoder) IsBaseline

func (d *Decoder) IsBaseline() bool

IsBaseline returns true if the decoded image is a baseline JPEG (SOF0).

This is a convenience method equivalent to checking Format() == FormatBaselineJPEG. Use this for simple format validation when you only need to verify baseline format.

Returns false if:

  • No image has been decoded yet
  • The format is not baseline JPEG (progressive, lossless, etc.)

Example:

decoder := jpeg.NewDecoderWithOptions(opts)
img, err := decoder.Decode(data)
if err != nil {
    return err
}
if !decoder.IsBaseline() {
    return errors.New("only baseline JPEG is supported")
}

func (*Decoder) QualityFactor

func (d *Decoder) QualityFactor() int

QualityFactor returns the estimated JPEG quality factor (1-100) of the decoded image.

This method analyzes the quantization tables to estimate the libjpeg-equivalent quality setting that was used when encoding the image. A value of 100 represents minimal compression (highest quality), while 1 represents maximum compression.

Returns 0 if:

  • No image has been decoded yet
  • No quantization tables are available
  • Quality estimation failed

Note: This is an estimate. The actual quality setting may differ for images encoded with non-standard quantization tables or custom encoders.

Example:

decoder := jpeg.NewDecoderWithOptions(opts)
img, err := decoder.Decode(data)
if err != nil {
    return err
}
quality := decoder.QualityFactor()
if quality < 80 {
    log.Printf("Low quality JPEG detected: %d", quality)
}

func (*Decoder) QuantizationTable

func (d *Decoder) QuantizationTable(component int) []int

QuantizationTable returns the quantization table for the specified component.

Component indices:

  • 0: Luminance (Y) - typically uses table ID 0
  • 1: Chrominance Cb - typically uses table ID 1
  • 2: Chrominance Cr - typically uses table ID 1 (shared with Cb)

Returns nil if:

  • No image has been decoded yet
  • The component index is out of range
  • No quantization table exists for the component

The returned slice contains 64 values in zigzag order, matching the standard JPEG quantization table format. Do not modify the returned slice.

Example:

decoder := jpeg.NewDecoderWithOptions(opts)
img, err := decoder.Decode(data)
if err != nil {
    return err
}
lumaTable := decoder.QuantizationTable(0)
if lumaTable != nil {
    fmt.Printf("DC quantization step: %d\n", lumaTable[0])
}

func (*Decoder) Signature

func (d *Decoder) Signature() *Signature

Signature returns the cached Signature from the last Decode or Extract operation. Returns nil if no JPEG has been decoded yet or if signature extraction failed.

This method provides efficient post-decode access to JPEG metadata without requiring re-parsing of the JPEG data. The signature is cached during the Decode() or Extract() call.

Example:

decoder := jpeg.NewDecoderWithOptions(nil)
img, err := decoder.Decode(data)
if err != nil {
    log.Fatal(err)
}
sig := decoder.Signature()
if sig != nil {
    fmt.Printf("Image has %d comments\n", len(sig.Comments))
}

type DecoderOptions

type DecoderOptions struct {
	// DCT specifies which DCT implementation to use.
	// Default: DCTDefault (AAN fast DCT)
	DCT DCTImplementation

	// ColorConversion specifies the YCbCr to RGB conversion standard.
	// Default: ColorConversionBT601
	ColorConversion ColorConversionStandard

	// ChromaUpsampling specifies the chroma upsampling quality.
	// Default: UpsamplingNearestNeighbor (faster)
	// Set to UpsamplingBilinear for higher quality at the cost of speed.
	ChromaUpsampling UpsamplingMode

	// HDROutput specifies how HDR data should be output.
	// Default: HDROutputSDR (tone-mapped to 8-bit)
	// Only applies to JPEG XT and other HDR-capable formats.
	HDROutput HDROutputMode

	// HDRIgnoreExtension when true ignores HDR extension data.
	// Only decodes the base layer for backward compatibility.
	// Default: false (decode full HDR)
	HDRIgnoreExtension bool

	// LightFieldView specifies which views to extract from light fields.
	// Default: LightFieldViewCenter (extract center view only)
	LightFieldView LightFieldViewMode

	// LightFieldViewU specifies the U coordinate for LightFieldViewSpecific mode.
	// Default: 0
	LightFieldViewU int

	// LightFieldViewV specifies the V coordinate for LightFieldViewSpecific mode.
	// Default: 0
	LightFieldViewV int

	// PointCloudFormat specifies the output format for point cloud data.
	// Default: PointCloudRaw
	PointCloudFormat PointCloudOutputFormat

	// PointCloudIncludeNormals when true includes surface normals if available.
	// Default: false
	PointCloudIncludeNormals bool

	// PointCloudIncludeColors when true includes color information if available.
	// Default: true
	PointCloudIncludeColors bool

	// LowLatencyMode when true enables line-by-line decoding for minimal latency.
	// Only applies to JPEG XS format.
	// Default: false (decode complete frame)
	LowLatencyMode bool
}

DecoderOptions configures the behavior of the JPEG decoder. These options allow quality/speed tradeoffs for different use cases and control output format for extended JPEG formats.

func DefaultDecoderOptions

func DefaultDecoderOptions() *DecoderOptions

DefaultDecoderOptions returns the default decoder configuration. Uses fast DCT, BT.601 color conversion, and nearest-neighbor upsampling. HDR images are tone-mapped to SDR by default for backward compatibility.

func HDRDecoderOptions

func HDRDecoderOptions() *DecoderOptions

HDRDecoderOptions returns decoder options optimized for HDR output. Uses float32 output mode for maximum dynamic range preservation.

func LightFieldDecoderOptions

func LightFieldDecoderOptions() *DecoderOptions

LightFieldDecoderOptions returns decoder options for extracting all light field views.

func LowLatencyDecoderOptions

func LowLatencyDecoderOptions() *DecoderOptions

LowLatencyDecoderOptions returns decoder options optimized for low latency. Enables line-by-line decoding for JPEG XS streams.

type DefaultValidator

type DefaultValidator struct{}

DefaultValidator implements the Validator interface with standard validation logic.

func (*DefaultValidator) SafeAdd

func (v *DefaultValidator) SafeAdd(a, b int) (int, error)

SafeAdd performs overflow-safe addition.

Returns ErrIntegerOverflow if the addition would overflow or underflow.

Algorithm: - For positive operands: check if result < either operand (wrapped around) - For negative operands: check if result > either operand (wrapped around) - For mixed signs: addition is always safe (moving toward zero).

func (*DefaultValidator) SafeMultiply

func (v *DefaultValidator) SafeMultiply(a, b int) (int, error)

SafeMultiply performs overflow-safe multiplication.

Returns ErrIntegerOverflow if the multiplication would overflow or underflow.

Algorithm: - Handle zero cases (always safe) - Perform multiplication. - Verify result by dividing back (if result/b != a, overflow occurred).

func (*DefaultValidator) ValidateCoefficient

func (v *DefaultValidator) ValidateCoefficient(value int) error

ValidateCoefficient validates that a DCT coefficient value fits in int16 range. Returns ErrOutOfBounds if value is outside [-32768, 32767] range.

func (*DefaultValidator) ValidateMarkerLength

func (v *DefaultValidator) ValidateMarkerLength(length int, remaining int) error

ValidateMarkerLength validates that a marker length is valid and within remaining data.

Returns ErrInvalidLength if: - length is negative. - remaining is negative. - length exceeds remaining data.

func (*DefaultValidator) ValidatePosition

func (v *DefaultValidator) ValidatePosition(pos int, maxPos int) error

ValidatePosition validates that a position is within valid bounds.

Returns ErrInvalidPosition if: - pos is negative. - maxPos is negative. - pos exceeds maxPos.

func (*DefaultValidator) ValidateSliceAccess

func (v *DefaultValidator) ValidateSliceAccess(index int, sliceLen int) error

ValidateSliceAccess validates that a slice index is within bounds.

Returns ErrOutOfBounds if: - sliceLen is negative or zero. - index is negative. - index is >= sliceLen (out of bounds).

func (*DefaultValidator) ValidateTableIndex

func (v *DefaultValidator) ValidateTableIndex(index int, maxIndex int) error

ValidateTableIndex validates that an index is within valid table bounds.

Returns ErrOutOfBounds if: - index is negative. - maxIndex is negative. - index exceeds maxIndex.

type DetectionResult

type DetectionResult struct {
	Data   []byte      // Original data reference
	Format Format      // Detected format
	Info   *FormatInfo // Detailed format information (optional)
	Error  error       // Any error that occurred
}

DetectionResult represents the result of format detection.

func DetectFormatsConcurrently

func DetectFormatsConcurrently(files [][]byte) []DetectionResult

DetectFormatsConcurrently detects formats for multiple files using goroutines. This is a convenience function that uses the default number of workers (NumCPU).

func DetectFormatsWithInfoConcurrently

func DetectFormatsWithInfoConcurrently(files [][]byte) []DetectionResult

DetectFormatsWithInfoConcurrently detects formats with info for multiple files. This is a convenience function that uses the default number of workers (NumCPU).

type DifferentialEncodingMode

type DifferentialEncodingMode int

DifferentialEncodingMode specifies the DCT mode for differential encoding.

const (
	// DifferentialSequential uses sequential DCT encoding
	DifferentialSequential DifferentialEncodingMode = iota
)

type DifferentialLosslessEncoder

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

DifferentialLosslessEncoder implements differential lossless encoding.

func NewDifferentialLosslessArithmeticEncoder

func NewDifferentialLosslessArithmeticEncoder(opts *EncoderOptions) *DifferentialLosslessEncoder

NewDifferentialLosslessArithmeticEncoder creates encoder with arithmetic coding (SOF15).

func NewDifferentialLosslessEncoder

func NewDifferentialLosslessEncoder(opts *EncoderOptions) *DifferentialLosslessEncoder

NewDifferentialLosslessEncoder creates a new differential lossless encoder.

func (*DifferentialLosslessEncoder) Encode

func (e *DifferentialLosslessEncoder) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to differential lossless JPEG bytes.

func (*DifferentialLosslessEncoder) EncodeImage

func (e *DifferentialLosslessEncoder) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to differential lossless JPEG bytes.

func (*DifferentialLosslessEncoder) Format

func (e *DifferentialLosslessEncoder) Format() Format

Format returns the target encoding format.

func (*DifferentialLosslessEncoder) Predictor

func (e *DifferentialLosslessEncoder) Predictor() int

Predictor returns the current predictor mode.

func (*DifferentialLosslessEncoder) SetHierarchyOptions

func (e *DifferentialLosslessEncoder) SetHierarchyOptions(opts *HierarchicalOptions)

SetHierarchyOptions sets the hierarchical encoding options.

func (*DifferentialLosslessEncoder) SetLosslessOptions

func (e *DifferentialLosslessEncoder) SetLosslessOptions(opts *LosslessOptions)

SetLosslessOptions sets the lossless encoding options.

func (*DifferentialLosslessEncoder) SetPredictor

func (e *DifferentialLosslessEncoder) SetPredictor(predictor int) error

SetPredictor sets the prediction mode (1-7).

func (*DifferentialLosslessEncoder) SetQuality

func (e *DifferentialLosslessEncoder) SetQuality(_ int) error

SetQuality is a no-op for lossless encoding.

type DifferentialProgressiveEncoder

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

DifferentialProgressiveEncoder implements differential progressive DCT encoding.

func NewDifferentialProgressiveArithmeticEncoder

func NewDifferentialProgressiveArithmeticEncoder(opts *EncoderOptions) *DifferentialProgressiveEncoder

NewDifferentialProgressiveArithmeticEncoder creates encoder with arithmetic coding (SOF14).

func NewDifferentialProgressiveEncoder

func NewDifferentialProgressiveEncoder(opts *EncoderOptions) *DifferentialProgressiveEncoder

NewDifferentialProgressiveEncoder creates a new differential progressive encoder.

func (*DifferentialProgressiveEncoder) Encode

func (e *DifferentialProgressiveEncoder) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to differential progressive JPEG bytes.

func (*DifferentialProgressiveEncoder) EncodeImage

func (e *DifferentialProgressiveEncoder) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to differential progressive JPEG bytes.

func (*DifferentialProgressiveEncoder) Format

Format returns the target encoding format.

func (*DifferentialProgressiveEncoder) SetHierarchyOptions

func (e *DifferentialProgressiveEncoder) SetHierarchyOptions(opts *HierarchicalOptions)

SetHierarchyOptions sets the hierarchical encoding options.

func (*DifferentialProgressiveEncoder) SetQuality

func (e *DifferentialProgressiveEncoder) SetQuality(quality int) error

SetQuality sets the encoding quality (1-100).

func (*DifferentialProgressiveEncoder) SetScanScript

func (e *DifferentialProgressiveEncoder) SetScanScript(script *ScanScript)

SetScanScript sets a custom scan script for progressive encoding.

type DifferentialSequentialEncoder

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

DifferentialSequentialEncoder implements differential sequential DCT encoding.

func NewDifferentialSequentialArithmeticEncoder

func NewDifferentialSequentialArithmeticEncoder(opts *EncoderOptions) *DifferentialSequentialEncoder

NewDifferentialSequentialArithmeticEncoder creates encoder with arithmetic coding (SOF13).

func NewDifferentialSequentialEncoder

func NewDifferentialSequentialEncoder(opts *EncoderOptions) *DifferentialSequentialEncoder

NewDifferentialSequentialEncoder creates a new differential sequential encoder.

func (*DifferentialSequentialEncoder) Encode

func (e *DifferentialSequentialEncoder) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to differential sequential JPEG bytes.

func (*DifferentialSequentialEncoder) EncodeImage

func (e *DifferentialSequentialEncoder) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to differential sequential JPEG bytes.

func (*DifferentialSequentialEncoder) Format

Format returns the target encoding format.

func (*DifferentialSequentialEncoder) SetHierarchyOptions

func (e *DifferentialSequentialEncoder) SetHierarchyOptions(opts *HierarchicalOptions)

SetHierarchyOptions sets the hierarchical encoding options.

func (*DifferentialSequentialEncoder) SetQuality

func (e *DifferentialSequentialEncoder) SetQuality(quality int) error

SetQuality sets the encoding quality (1-100).

type EXIFMetadataParser

type EXIFMetadataParser interface {
	// Parse extracts EXIF metadata from APP1 marker data.
	// Returns Data struct with all available fields populated, or error if parsing fails.
	Parse(data []byte) (*exif.Data, error)
}

EXIFMetadataParser defines the interface for parsing EXIF metadata from JPEG APP1 marker data. This abstraction follows the Dependency Inversion Principle, allowing different. implementations of EXIF parsing while keeping the interface stable.

NOTE: This will replace the concrete EXIFParser type after refactoring is complete.

type EXIFParser

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

EXIFParser extracts EXIF metadata from JPEG APP1 marker data. This is a backward-compatible adapter that delegates to the refactored internal parser.

func NewEXIFParser

func NewEXIFParser() *EXIFParser

NewEXIFParser creates a new EXIF parser. Dependency Injection: Creates internal parser with validator.

func (*EXIFParser) Parse

func (p *EXIFParser) Parse(data []byte) (*exif.Data, error)

Parse extracts EXIF metadata from APP1 marker data. Delegates to internal parser implementation.

type Encoder

type Encoder interface {
	// Encode encodes raw pixel data to JPEG bytes.
	Encode(img *ImageData) ([]byte, error)

	// EncodeImage encodes Go's image.Image to JPEG bytes.
	EncodeImage(img image.Image) ([]byte, error)

	// Format returns the target encoding format.
	Format() Format

	// SetQuality sets encoding quality (0-100, format-dependent).
	SetQuality(quality int) error
}

Encoder encodes images to JPEG format. Implements ISP with focused encoding methods.

func NewEncoder

func NewEncoder(format Format, opts *EncoderOptions) (Encoder, error)

NewEncoder creates a new encoder for the specified format.

type EncoderBitWriter

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

EncoderBitWriter writes variable-length bit sequences to an underlying io.Writer with JPEG byte stuffing (0xFF -> 0xFF 0x00) for entropy data.

This type is specifically designed for JPEG encoding where: - Bits are written most-significant bit first - Any 0xFF byte in the entropy-coded data must be followed by 0x00 - Partial bytes are padded with 1-bits when flushed (per JPEG spec)

Example usage:

var buf bytes.Buffer
bw := NewEncoderBitWriter(&buf)
bw.WriteBits(0xABC, 12)  // Write 12 bits
bw.Flush()               // Pad and flush remaining bits

func NewEncoderBitWriter

func NewEncoderBitWriter(w io.Writer) *EncoderBitWriter

NewEncoderBitWriter creates a new bit writer that writes to w.

The writer will automatically perform JPEG byte stuffing: any 0xFF byte written will be followed by a 0x00 byte to distinguish it from JPEG markers.

func (*EncoderBitWriter) BytesWritten

func (bw *EncoderBitWriter) BytesWritten() int

BytesWritten returns the total number of bytes written to the underlying writer, including byte stuffing bytes.

func (*EncoderBitWriter) Error

func (bw *EncoderBitWriter) Error() error

Error returns the first error encountered during writing, or nil if no error has occurred.

func (*EncoderBitWriter) Flush

func (bw *EncoderBitWriter) Flush() error

Flush writes any remaining bits, padding with 1-bits as per JPEG spec.

According to ITU-T T.81, partial bytes at the end of entropy-coded segments must be padded with 1-bits. This ensures that the padding bits cannot be confused with valid Huffman codes (which typically have 0 bits in significant positions).

Returns an error if the underlying write fails.

func (*EncoderBitWriter) Reset

func (bw *EncoderBitWriter) Reset()

Reset resets the bit writer's internal state without affecting the underlying writer. This can be used to start a new entropy-coded segment.

func (*EncoderBitWriter) WriteBits

func (bw *EncoderBitWriter) WriteBits(bits uint32, n int) error

WriteBits writes n bits from the least significant bits of value.

Parameters:

  • bits: The value containing the bits to write (LSB-aligned)
  • n: Number of bits to write (1-32)

The bits are written most-significant bit first, which is the JPEG standard bit ordering. For example, WriteBits(0x5, 3) writes the bit sequence "101".

Returns an error if the underlying write fails, or if a previous error was encountered.

func (*EncoderBitWriter) WriteByteAligned

func (bw *EncoderBitWriter) WriteByteAligned(b byte) error

WriteByteAligned writes a complete byte directly, flushing any partial byte first. This is useful for writing marker data.

Note: This method should typically only be used when you're certain the bit stream is or should be byte-aligned.

type EncoderComponentSpec

type EncoderComponentSpec struct {
	// ID is the component identifier (1-255, typically 1=Y, 2=Cb, 3=Cr).
	ID int

	// HSampling is the horizontal sampling factor (1-4).
	// This determines how many 8x8 blocks of this component are in each MCU
	// in the horizontal direction.
	HSampling int

	// VSampling is the vertical sampling factor (1-4).
	// This determines how many 8x8 blocks of this component are in each MCU
	// in the vertical direction.
	VSampling int

	// QuantTableID is the quantization table selector (0-3).
	// Specifies which DQT table to use for this component.
	QuantTableID int

	// DCTableID is the DC Huffman table selector (0-3) for encoding.
	// Only used when building the scan; not written to SOF marker.
	DCTableID int

	// ACTableID is the AC Huffman table selector (0-3) for encoding.
	// Only used when building the scan; not written to SOF marker.
	ACTableID int
}

EncoderComponentSpec defines a color component's encoding parameters for the SOF (Start of Frame) marker.

In JPEG, an image typically has 1 component (grayscale) or 3 components (Y, Cb, Cr for color images). Each component has its own sampling factors and quantization table assignment.

Note: This type is distinct from ComponentSpec in interfaces.go, which is used for JPEG 2000 component specifications.

func Get420ComponentSpecs

func Get420ComponentSpecs() []EncoderComponentSpec

Get420ComponentSpecs returns the component specifications for 4:2:0 chroma subsampling.

4:2:0 is the most common JPEG subsampling mode, where chrominance is sampled at half resolution in both horizontal and vertical dimensions. This results in 4 Y blocks, 1 Cb block, and 1 Cr block per MCU.

MCU structure (2x2 Y blocks + 1 Cb + 1 Cr):

Y0  Y1
Y2  Y3
Cb  Cr

func Get422ComponentSpecs

func Get422ComponentSpecs() []EncoderComponentSpec

Get422ComponentSpecs returns the component specifications for 4:2:2 chroma subsampling.

4:2:2 samples chrominance at half resolution horizontally but full resolution vertically. This results in 2 Y blocks, 1 Cb block, and 1 Cr block per MCU (in a 2x1 arrangement).

MCU structure (2x1 Y blocks + 1 Cb + 1 Cr):

Y0  Y1  Cb  Cr

func Get444ComponentSpecs

func Get444ComponentSpecs() []EncoderComponentSpec

Get444ComponentSpecs returns the component specifications for 4:4:4 chroma subsampling (no subsampling).

4:4:4 uses full resolution for all components. Each MCU contains exactly one 8x8 block of each component.

MCU structure (1x1 of each):

Y  Cb  Cr

func GetGrayscaleComponentSpecs

func GetGrayscaleComponentSpecs() []EncoderComponentSpec

GetGrayscaleComponentSpecs returns the component specifications for grayscale images (single Y component).

Grayscale images have only a luminance component with no chroma. Each MCU contains exactly one 8x8 block.

type EncoderDetector

type EncoderDetector interface {
	// DetectEncoder analyzes raw JPEG file bytes to detect the encoder.
	// It parses DQT markers and APP markers from the JPEG structure and
	// analyzes patterns to identify the software, device, or library
	// that produced the image.
	//
	// Returns:
	//   - *EncoderSignature: Comprehensive encoder identification
	//   - error: If data is not valid JPEG or lacks required markers
	//
	// Errors returned for:
	//   - Non-JPEG data (missing SOI marker 0xFFD8)
	//   - JPEG without DQT markers
	//   - Lossless JPEG (SOF3) where encoder detection is not applicable
	DetectEncoder(data []byte) (*EncoderSignature, error)

	// DetectEncoderFromTables detects the encoder from pre-parsed quantization tables.
	// This is useful when JPEG data has already been partially parsed.
	//
	// Parameters:
	//   - tables: Map of quantization tables indexed by table ID (0-3)
	//     - ID 0: Typically luminance (Y) table
	//     - ID 1: Typically chrominance (Cb/Cr) table
	//
	// Returns:
	//   - *EncoderSignature: Comprehensive encoder identification
	//   - error: If tables map is empty or contains invalid data
	DetectEncoderFromTables(tables map[int][64]int) (*EncoderSignature, error)
}

EncoderDetector detects the encoder that produced a JPEG image. Implements ISP with focused methods for encoder signature detection.

This interface provides two entry points:

  • DetectEncoder: For raw JPEG file bytes (parses DQT and APP markers)
  • DetectEncoderFromTables: For pre-parsed quantization tables

The detection uses quantization table signature matching, APP marker analysis, and Huffman table patterns to identify the encoder.

func NewEncoderDetector

func NewEncoderDetector(validator SecurityValidator) EncoderDetector

NewEncoderDetector creates a new EncoderDetector instance. The validator parameter is optional; if nil, no validation is performed.

Usage:

detector := NewEncoderDetector(nil)
signature, err := detector.DetectEncoder(jpegData)

type EncoderError

type EncoderError struct {
	Format  Format // The encoding format that failed
	Phase   string // The encoding phase (e.g., "DCT", "quantization", "entropy")
	Message string // Human-readable error description
	Cause   error  // Underlying cause of the error
}

EncoderError represents an error during JPEG encoding. It provides context about which encoder format and phase failed.

func NewEncoderError

func NewEncoderError(format Format, phase, message string, cause error) *EncoderError

NewEncoderError creates a new EncoderError.

func (*EncoderError) Error

func (e *EncoderError) Error() string

Error implements the error interface.

func (*EncoderError) Is

func (e *EncoderError) Is(target error) bool

Is implements the errors.Is interface for error comparison.

func (*EncoderError) Unwrap

func (e *EncoderError) Unwrap() error

Unwrap implements the errors.Unwrap interface for error chaining.

type EncoderFamily

type EncoderFamily int

EncoderFamily represents the family of encoder that produced the JPEG.

const (
	// EncoderUnknown indicates the encoder could not be identified.
	EncoderUnknown EncoderFamily = iota
	// EncoderLibJPEG indicates the standard Independent JPEG Group encoder.
	EncoderLibJPEG
	// EncoderPhotoshop indicates Adobe Photoshop encoder.
	EncoderPhotoshop
	// EncoderMozJPEG indicates Mozilla's MozJPEG encoder.
	EncoderMozJPEG
	// EncoderCanon indicates Canon camera JPEG encoder.
	EncoderCanon
	// EncoderNikon indicates Nikon camera JPEG encoder.
	EncoderNikon
	// EncoderSony indicates Sony camera JPEG encoder.
	EncoderSony
	// EncoderApple indicates Apple device JPEG encoder.
	EncoderApple
	// EncoderSamsung indicates Samsung device JPEG encoder.
	EncoderSamsung
	// EncoderF5James indicates the F5/James JpegEncoder (F5Android steganography encoder).
	// This encoder uses identical IJG quality scaling formula but is identifiable
	// via its characteristic COM marker: "JPEG Encoder Copyright 1998, James R. Weeks and BioElectroMech."
	EncoderF5James
)

func DetectEncoderFromAllSources

func DetectEncoderFromAllSources(data []byte, tables map[int][64]int) (EncoderFamily, float64)

DetectEncoderFromAllSources combines APP marker hints with quantization table signature analysis to detect the encoder that produced a JPEG.

This function integrates multiple detection sources: 1. APP marker analysis (EXIF Make/Model, Photoshop markers, Adobe markers) 2. Quantization table signature matching 3. Confidence weighting and conflict resolution

Parameters:

  • data: Raw JPEG file bytes
  • tables: Pre-extracted quantization tables (map of table ID to table)

Returns:

  • EncoderFamily: The most likely encoder family
  • float64: Combined confidence score (0.0-1.0)

func MatchCameraSignature

func MatchCameraSignature(table [64]int) (EncoderFamily, float64)

MatchCameraSignature attempts to identify the camera manufacturer that produced a quantization table by matching against known signatures.

Parameters:

  • table: The observed quantization table (64 coefficients in row-major order)

Returns:

  • EncoderFamily: The detected encoder family, or EncoderUnknown if no match
  • float64: Confidence in the detection (0.0-1.0)

func (EncoderFamily) String

func (e EncoderFamily) String() string

String returns the string representation of the EncoderFamily.

type EncoderOptions

type EncoderOptions struct {
	Quality           int               // Quality level 0-100 (default 75)
	ChromaSubsampling ChromaSubsampling // Chroma subsampling mode
	Progressive       bool              // Use progressive encoding if supported
	OptimizeHuffman   bool              // Generate optimized Huffman tables
	Lossless          bool              // Use lossless mode if supported
	RestartInterval   int               // MCU rows between restart markers (0 = disabled)
	Comment           string            // Comment to embed in JPEG (empty = use default)
	DisableComment    bool              // Set to true to disable comment embedding

	// LuminanceQuantTable, when non-nil, overrides the scalar-Quality-derived
	// luminance quantization table for baseline encoding. The table must be in
	// NATURAL (row-major) order — the same order as StandardLuminanceQuantTable
	// and the output of ScaleQuantTable. Use ZigzagToNatural to convert a table
	// obtained from Decoder.QuantizationTable (which is in zigzag order).
	//
	// This exists so a re-compression step can reuse the SOURCE image's actual
	// quantization table instead of a standard table scaled by an estimated
	// scalar quality — required by Fridrich §3.2 cover-histogram estimation.
	// When nil (default), behavior is unchanged: ScaleQuantTable(standard, Quality).
	LuminanceQuantTable *[BlockSize2]int

	// ChrominanceQuantTable, when non-nil, overrides the chrominance
	// quantization table. Natural (row-major) order, same conventions as
	// LuminanceQuantTable. Ignored for grayscale encodes.
	ChrominanceQuantTable *[BlockSize2]int
}

EncoderOptions configures encoder behavior.

func DefaultEncoderOptions

func DefaultEncoderOptions() *EncoderOptions

DefaultEncoderOptions returns default encoding options.

type EncoderQualityMapping

type EncoderQualityMapping struct {
	// Name is the human-readable name of the encoder.
	Name string

	// Curve is the function that generates quantization tables for this encoder.
	Curve QualityCurve

	// ScaleMin is the minimum quality value for this encoder's native scale.
	ScaleMin int

	// ScaleMax is the maximum quality value for this encoder's native scale.
	ScaleMax int

	// UsesLibjpegScale indicates whether this encoder uses the standard
	// libjpeg 1-100 quality scale.
	UsesLibjpegScale bool
}

EncoderQualityMapping defines the quality mapping characteristics for an encoder family, including its quality curve and scale range.

type EncoderSignature

type EncoderSignature struct {
	// EncoderFamily is the broad encoder category.
	// Possible values: "libjpeg", "adobe", "camera", "mobile", "unknown"
	EncoderFamily string

	// EncoderName is the specific identification.
	// Examples: "libjpeg-turbo", "Photoshop CS6", "Canon EOS R5", "iPhone 15 Pro"
	EncoderName string

	// EncoderVersion is the version when detectable from APP markers or table patterns.
	EncoderVersion string

	// Confidence indicates identification reliability (0.0-1.0).
	// A value of 1.0 indicates high confidence match,
	// while lower values indicate uncertainty.
	Confidence float64

	// MatchMethod describes how identification was made.
	// Possible values: "quantization-table", "app-marker", "huffman-signature", "combined"
	MatchMethod string

	// TableSignatureHash is the SHA-256 hash of quantization tables for database lookup.
	TableSignatureHash string

	// DetectedPatterns lists all matched signature patterns.
	// Examples: ["ijg-standard-lum-q75", "ijg-standard-chrom-q75"]
	DetectedPatterns []string
}

EncoderSignature represents comprehensive identification of the encoder that produced a JPEG image.

type EncoderWithConfig

type EncoderWithConfig interface {
	Encoder
	Configurable
}

EncoderWithConfig combines Encoder with configuration capability. This allows full control over encoder settings.

type EncoderWithValidation

type EncoderWithValidation interface {
	Encoder
	Validatable
}

EncoderWithValidation combines Encoder with validation capability. This allows runtime validation before encoding operations.

type EstimationMethod

type EstimationMethod int

EstimationMethod represents the algorithm used for quality estimation.

const (
	// EstimationMethodLeastSquares uses sum of squared errors matching.
	EstimationMethodLeastSquares EstimationMethod = iota
	// EstimationMethodScaleFactor uses scale factor reverse engineering.
	EstimationMethodScaleFactor
	// EstimationMethodDCTHistogram uses DCT coefficient histogram analysis.
	EstimationMethodDCTHistogram
)

func (EstimationMethod) String

func (m EstimationMethod) String() string

String returns the string representation of the EstimationMethod.

type EventStreamDecoder

type EventStreamDecoder interface {
	// DecodeEvents decodes all events from the stream.
	DecodeEvents(r io.Reader) ([]VisualEvent, *EventStreamInfo, error)
}

EventStreamDecoder decodes event-based visual sensor data. Implements ISP for event stream decoding. Used by JPEG XE (ISO/IEC) for neuromorphic camera data.

type EventStreamInfo

type EventStreamInfo struct {
	Width          int    // Sensor width in pixels
	Height         int    // Sensor height in pixels
	EventCount     uint64 // Total number of events
	StartTimestamp uint64 // First event timestamp
	EndTimestamp   uint64 // Last event timestamp
	SensorType     string // Sensor type identifier
}

EventStreamInfo contains metadata about an event stream.

type EventStreamResult

type EventStreamResult struct {
	// Events contains the decoded visual events
	Events []VisualEventData

	// SensorWidth is the width of the event sensor
	SensorWidth int

	// SensorHeight is the height of the event sensor
	SensorHeight int

	// Duration is the total duration of the event stream in microseconds
	Duration uint64
}

EventStreamResult contains decoded event stream data for JPEG XE.

type ExtendedEncoder

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

ExtendedEncoder implements extended sequential JPEG encoding (SOF1).

func NewExtended12BitEncoder

func NewExtended12BitEncoder(opts *EncoderOptions) *ExtendedEncoder

NewExtended12BitEncoder creates a new extended sequential JPEG encoder with 12-bit precision.

func NewExtendedEncoder

func NewExtendedEncoder(opts *EncoderOptions) *ExtendedEncoder

NewExtendedEncoder creates a new extended sequential JPEG encoder.

func (*ExtendedEncoder) Encode

func (e *ExtendedEncoder) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to extended sequential JPEG bytes.

func (*ExtendedEncoder) EncodeImage

func (e *ExtendedEncoder) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to extended sequential JPEG bytes.

func (*ExtendedEncoder) Format

func (e *ExtendedEncoder) Format() Format

Format returns the target encoding format.

func (*ExtendedEncoder) Precision

func (e *ExtendedEncoder) Precision() int

Precision returns the current sample precision.

func (*ExtendedEncoder) SetPrecision

func (e *ExtendedEncoder) SetPrecision(precision int) error

SetPrecision sets the sample precision (8 or 12 bits).

func (*ExtendedEncoder) SetQuality

func (e *ExtendedEncoder) SetQuality(quality int) error

SetQuality sets encoding quality (0-100).

type Format

type Format int

Format represents the detected JPEG format type

const (
	// FormatUnknown indicates the format could not be determined
	FormatUnknown Format = iota

	// FormatBaselineJPEG is standard baseline DCT JPEG (SOF0)
	FormatBaselineJPEG

	// FormatExtendedJPEG is extended sequential DCT JPEG (SOF1)
	FormatExtendedJPEG

	// FormatProgressiveJPEG is progressive DCT JPEG (SOF2)
	FormatProgressiveJPEG

	// FormatLosslessJPEG is lossless JPEG (SOF3)
	FormatLosslessJPEG

	// FormatDifferentialSequential is differential sequential DCT (SOF5)
	FormatDifferentialSequential

	// FormatDifferentialProgressive is differential progressive DCT (SOF6)
	FormatDifferentialProgressive

	// FormatDifferentialLossless is differential lossless (SOF7)
	FormatDifferentialLossless

	// FormatArithmeticSequential is arithmetic coded sequential DCT (SOF9)
	FormatArithmeticSequential

	// FormatArithmeticProgressive is arithmetic coded progressive DCT (SOF10)
	FormatArithmeticProgressive

	// FormatArithmeticLossless is arithmetic coded lossless (SOF11)
	FormatArithmeticLossless

	// FormatDiffArithSequential is differential sequential DCT, arithmetic (SOF13)
	FormatDiffArithSequential

	// FormatDiffArithProgressive is differential progressive DCT, arithmetic (SOF14)
	FormatDiffArithProgressive

	// FormatDiffArithLossless is differential lossless, arithmetic (SOF15)
	FormatDiffArithLossless

	// FormatJPEG2000 is JPEG 2000 (JP2 or J2K codestream)
	FormatJPEG2000

	// FormatJPEGLS is JPEG-LS (ITU-T T.87 / ISO 14495-1)
	// Near-lossless and lossless compression using LOCO-I algorithm
	FormatJPEGLS

	// FormatJPEGLS_T870 is JPEG-LS with ITU-T T.870 extensions
	// Extended parameters for higher bit depths and improved context modeling
	FormatJPEGLS_T870

	// FormatJPEGXR is JPEG XR (ITU-T T.832 / ISO 29199-2)
	// Also known as HD Photo, supports HDR and wide color gamut
	FormatJPEGXR

	// FormatJPEGXL is JPEG XL (ISO 21122)
	// Modern next-gen format with high compression ratio
	FormatJPEGXL

	// FormatJPEGXT is JPEG XT (ISO/IEC 18477)
	// HDR extension for standard JPEG using APP11 marker
	FormatJPEGXT

	// FormatJPEGXS is JPEG XS (ISO/IEC 21122)
	// Low-latency, visually lossless codec for professional video
	// Uses bounded memory and sub-line latency for real-time streaming
	FormatJPEGXS

	// FormatJPX is JPEG 2000 Part 2 (ISO/IEC 15444-2)
	// Extended file format with additional color spaces and animation
	FormatJPX

	// FormatMJ2 is Motion JPEG 2000 (ISO/IEC 15444-3)
	// Video format using JPEG 2000 frames in ISO base media file format
	FormatMJ2

	// FormatJPM is JPEG 2000 Part 6 (ISO/IEC 15444-6)
	// Compound image file format for mixed raster/vector content
	FormatJPM

	// FormatHTJ2K is JPEG 2000 Part 15 (ISO/IEC 15444-15)
	// High-Throughput JPEG 2000 with 10x faster block decoding
	FormatHTJ2K

	// FormatJPSEC is JPEG 2000 Part 8 (ISO/IEC 15444-8)
	// Secure JPEG 2000 with encryption and authentication zones
	FormatJPSEC

	// FormatJPIP is JPEG 2000 Part 9 (ISO/IEC 15444-9)
	// Interactive protocol for streaming JPEG 2000 content
	FormatJPIP

	// FormatJP3D is JPEG 2000 Part 10 (ISO/IEC 15444-10)
	// Volumetric JPEG 2000 for 3D medical imaging
	FormatJP3D

	// FormatJPWL is JPEG 2000 Part 11 (ISO/IEC 15444-11)
	// Wireless JPEG 2000 with error protection and correction
	FormatJPWL

	// FormatJPEGPlenoLightField is JPEG Pleno Light Field (ISO/IEC 21794-2)
	// Plenoptic light field image format for 4D image arrays
	FormatJPEGPlenoLightField

	// FormatJPEGPlenoHolography is JPEG Pleno Holography (ISO/IEC 21794-5)
	// Digital hologram representation and coding
	FormatJPEGPlenoHolography

	// FormatJPEGPlenoPointCloud is JPEG Pleno Point Cloud (ISO/IEC 21794-6)
	// 3D point cloud representation and coding
	FormatJPEGPlenoPointCloud

	// FormatJPEGAI is JPEG AI (ISO/IEC 23090-4)
	// Neural network-based learned image compression
	// Uses neural networks for encoding and decoding with latent representations
	FormatJPEGAI

	// FormatJPEGXE is JPEG XE (ISO/IEC 21122-5)
	// Event camera data codec for neuromorphic sensors
	// Encodes asynchronous events (x, y, polarity, timestamp) from event cameras
	FormatJPEGXE

	// FormatJUMBF is JPEG Universal Metadata Box Format (ISO/IEC 19566-5)
	// Universal container for embedding metadata in JPEG files
	FormatJUMBF

	// FormatJPEG360 is JPEG 360 (ISO/IEC 19566-6)
	// 360-degree spherical image format with projection metadata
	FormatJPEG360

	// FormatJLINK is JPEG JLINK (ISO/IEC 19566-7)
	// Linking format for external references in JPEG files
	FormatJLINK

	// FormatJPEGTrust is JPEG Trust (ISO/IEC 21617)
	// Trust and provenance metadata for content authenticity
	FormatJPEGTrust
)

func DetectAndDecode

func DetectAndDecode(r io.Reader) (img image.Image, format Format, err error)

DetectAndDecode detects the format and decodes the image in one operation. Returns the decoded image, detected format, and any error.

This function is useful when you need to know the exact format that was used to decode the image. For simple decoding where format doesn't matter, use Decode instead.

Example:

img, format, err := jpeg.DetectAndDecode(reader)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Decoded %s image\n", format)
Example

ExampleDetectAndDecode demonstrates format detection combined with decoding. This returns both the decoded image and the detected format.

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/0verkilll/jpeg"
)

// createExampleJPEG creates a minimal valid baseline JPEG for examples.
// This returns a 1x1 grayscale JPEG image.
func createExampleJPEG() []byte {
	return []byte{

		0xFF, 0xD8,

		0xFF, 0xE0, 0x00, 0x10,
		'J', 'F', 'I', 'F', 0x00,
		0x01, 0x01,
		0x00,
		0x00, 0x01,
		0x00, 0x01,
		0x00, 0x00,

		0xFF, 0xDB, 0x00, 0x43, 0x00,

		16, 11, 10, 16, 24, 40, 51, 61,
		12, 12, 14, 19, 26, 58, 60, 55,
		14, 13, 16, 24, 40, 57, 69, 56,
		14, 17, 22, 29, 51, 87, 80, 62,
		18, 22, 37, 56, 68, 109, 103, 77,
		24, 35, 55, 64, 81, 104, 113, 92,
		49, 64, 78, 87, 103, 121, 120, 101,
		72, 92, 95, 98, 112, 100, 103, 99,

		0xFF, 0xC0, 0x00, 0x0B,
		0x08,
		0x00, 0x01,
		0x00, 0x01,
		0x01,
		0x01,
		0x11,
		0x00,

		0xFF, 0xC4, 0x00, 0x1F, 0x00,
		0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
		0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
		0x08, 0x09, 0x0A, 0x0B,

		0xFF, 0xC4, 0x00, 0xB5, 0x10,
		0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
		0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D,
		0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
		0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
		0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
		0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
		0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16,
		0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
		0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
		0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
		0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
		0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
		0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
		0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
		0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
		0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
		0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
		0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
		0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
		0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
		0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,
		0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
		0xF9, 0xFA,

		0xFF, 0xDA, 0x00, 0x08,
		0x01,
		0x01, 0x00,
		0x00, 0x3F, 0x00,

		0xFB, 0xD3, 0x28, 0xA6,

		0xFF, 0xD9,
	}
}

func main() {
	jpegData := createExampleJPEG()

	// Detect format and decode in one operation
	img, format, err := jpeg.DetectAndDecode(bytes.NewReader(jpegData))
	if err != nil {
		log.Fatal(err)
	}

	bounds := img.Bounds()
	fmt.Printf("Format: %s\n", format)
	fmt.Printf("Size: %dx%d\n", bounds.Dx(), bounds.Dy())
}
Output:
Format: Baseline JPEG (SOF0)
Size: 1x1

func DetectFormat

func DetectFormat(data []byte) (Format, error)

DetectFormat detects the JPEG format type from raw data

func SupportedFormats

func SupportedFormats() []Format

SupportedFormats returns a list of all supported JPEG formats. This includes all 36+ variants supported by this library.

The returned formats include:

  • Standard JPEG variants (baseline, extended, progressive, lossless)
  • Arithmetic coded variants
  • Differential coded variants
  • JPEG 2000 family (JP2, JPX, MJ2, JPM, HTJ2K)
  • JPEG-LS (lossless/near-lossless)
  • JPEG XR (HD Photo)
  • JPEG XL (next-generation)
  • JPEG XT (HDR extension)
  • JPEG XS (low-latency)
  • Specialized formats (Pleno, AI, Trust, etc.)
Example

ExampleSupportedFormats demonstrates listing all supported JPEG formats. This library supports 37 different JPEG format variants.

package main

import (
	"fmt"

	"github.com/0verkilll/jpeg"
)

func main() {
	formats := jpeg.SupportedFormats()
	fmt.Printf("Number of supported formats: %d\n", len(formats))
}
Output:
Number of supported formats: 37

func (Format) Info

func (f Format) Info() BasicFormatInfo

Info returns basic information about the format.

func (Format) Is3D

func (f Format) Is3D() bool

Is3D returns true if the format contains 3D or multi-dimensional data

func (Format) IsDifferential

func (f Format) IsDifferential() bool

IsDifferential returns true if the format is a differential encoding

func (Format) IsEventBased

func (f Format) IsEventBased() bool

IsEventBased returns true if the format is for event camera data

func (Format) IsHDR

func (f Format) IsHDR() bool

IsHDR returns true if the format supports HDR (high dynamic range)

func (Format) IsJPEG2000Family

func (f Format) IsJPEG2000Family() bool

IsJPEG2000Family returns true if the format is part of the JPEG 2000 family

func (Format) IsLossy

func (f Format) IsLossy() bool

IsLossy returns true if the format is lossy compression

func (Format) IsLowLatency

func (f Format) IsLowLatency() bool

IsLowLatency returns true if the format is designed for low-latency applications

func (Format) IsMetadataFormat

func (f Format) IsMetadataFormat() bool

IsMetadataFormat returns true if the format is a metadata container

func (Format) IsNeuralBased

func (f Format) IsNeuralBased() bool

IsNeuralBased returns true if the format uses neural network compression

func (Format) IsNextGen

func (f Format) IsNextGen() bool

IsNextGen returns true if the format is a next-generation JPEG format

func (Format) IsPlenoptic

func (f Format) IsPlenoptic() bool

IsPlenoptic returns true if the format is a JPEG Pleno plenoptic format

func (Format) IsProgressive

func (f Format) IsProgressive() bool

IsProgressive returns true if the format uses progressive encoding

func (Format) IsSecure

func (f Format) IsSecure() bool

IsSecure returns true if the format has security features

func (Format) String

func (f Format) String() string

String returns the human-readable format name

func (Format) UsesArithmeticCoding

func (f Format) UsesArithmeticCoding() bool

UsesArithmeticCoding returns true if the format uses arithmetic coding

type FormatAnalyzer

type FormatAnalyzer interface {
	FormatDetector

	// Analyze extracts comprehensive format information from raw data.
	// Returns FormatInfo with dimensions, components, and format details.
	Analyze(data []byte) (*FormatInfo, error)
}

FormatAnalyzer provides detailed format analysis including image dimensions. Extends FormatDetector with additional metadata extraction.

func DefaultFormatAnalyzer

func DefaultFormatAnalyzer() FormatAnalyzer

DefaultFormatAnalyzer returns the default FormatAnalyzer implementation.

type FormatDetector

type FormatDetector interface {
	// Detect identifies the JPEG format from raw byte data.
	// Returns the detected Format and any error encountered.
	Detect(data []byte) (Format, error)
}

FormatDetector detects the JPEG format type from raw data. Implements ISP with a single-method interface for format detection.

func DefaultFormatDetector

func DefaultFormatDetector() FormatDetector

DefaultFormatDetector returns the default FormatDetector implementation.

type FormatInfo

type FormatInfo struct {
	Format         Format
	Width          int
	Height         int
	Components     int
	BitsPerSample  int
	IsJPEG2000     bool
	IsJPEGXT       bool
	IsJPEGXS       bool
	IsJPEGPleno    bool
	IsJPEGAI       bool
	IsJPEGXE       bool
	IsJPEG2000Ext  bool // True for JPX, MJ2, JPM, HTJ2K, JPSEC, JPIP, JP3D, JPWL
	HasThumbnail   bool
	HasHDR         bool
	HasTrust       bool // True if JPEG Trust metadata present
	HasJUMBF       bool // True if JUMBF metadata present
	Has360Metadata bool // True if 360 metadata present
	HasLinks       bool // True if JLINK references present
}

FormatInfo contains detailed information about a detected format

func DetectFormatInfo

func DetectFormatInfo(data []byte) (*FormatInfo, error)

DetectFormatInfo detects format and extracts basic image information

type FrameDifferencer

type FrameDifferencer struct {
	// Reference image (upsampled from previous level)
	Reference *ImageData

	// Target image (current level)
	Target *ImageData

	// Differential image (residuals)
	Differential *ImageData
}

FrameDifferencer computes differential frames for hierarchical encoding.

func NewFrameDifferencer

func NewFrameDifferencer(reference, target *ImageData) (*FrameDifferencer, error)

NewFrameDifferencer creates a differencer for computing residuals.

func (*FrameDifferencer) ComputeDifferential

func (fd *FrameDifferencer) ComputeDifferential() (*ImageData, error)

ComputeDifferential calculates the residual image (target - reference).

type FullEncoder

type FullEncoder interface {
	Encoder
	Validatable
	Configurable
}

FullEncoder combines all encoder capabilities. Use this when full control over validation and configuration is needed.

type HDRDecodeMetadata

type HDRDecodeMetadata struct {
	Profile         int     // JPEG XT profile (A, B, C, D)
	DynamicRange    float64 // Dynamic range in stops
	MaxLuminance    float64 // Maximum luminance in cd/m^2
	MinLuminance    float64 // Minimum luminance in cd/m^2
	ToneMapOperator string  // Name of embedded tone mapping operator
}

HDRDecodeMetadata contains HDR-specific metadata.

type HDRDecoder

type HDRDecoder interface {
	// DecodeHDR decodes HDR image data from a reader.
	// Returns pixel data as float32 values (typically in linear light space).
	DecodeHDR(r io.Reader) ([]float32, *HDRMetadata, error)
}

HDRDecoder decodes High Dynamic Range image data. Implements ISP with a single focused method for HDR decoding. Used by JPEG XT (ISO/IEC 18477) decoder implementations.

type HDREncoder

type HDREncoder interface {
	// EncodeHDR encodes HDR pixel data to a writer.
	// Pixels should be linear float32 values.
	// Returns the number of bytes written.
	EncodeHDR(w io.Writer, pixels []float32, metadata *HDRMetadata) (int, error)
}

HDREncoder encodes images with HDR data. Implements ISP for HDR encoding operations. Used by JPEG XT (ISO/IEC 18477) encoder implementations.

type HDRInfoProvider

type HDRInfoProvider interface {
	// GetHDRInfo extracts HDR metadata from image data.
	GetHDRInfo(data []byte) (*HDRMetadata, error)
}

HDRInfoProvider provides HDR metadata without full decoding. Implements ISP for lightweight HDR information extraction.

type HDRMetadata

type HDRMetadata struct {
	Profile          int     // HDR profile (A, B, C, D)
	DynamicRange     float64 // Dynamic range in stops
	MaxLuminance     float64 // Maximum luminance in cd/m^2
	MinLuminance     float64 // Minimum luminance in cd/m^2
	BitDepth         int     // Bit depth of HDR data (e.g., 16, 32)
	IsFloatingPoint  bool    // True if floating-point representation
	ToneMapOperator  string  // Name of embedded tone mapping operator
	RefinementLayers int     // Number of refinement layers
}

HDRMetadata contains metadata for HDR image decoding. Used by JPEG XT and other HDR-capable formats.

type HDROutputMode

type HDROutputMode int

HDROutputMode specifies how HDR data should be output.

const (
	// HDROutputSDR tone-maps HDR to standard dynamic range (8-bit).
	// This is the default and provides backward compatibility.
	HDROutputSDR HDROutputMode = iota

	// HDROutputFloat32 outputs HDR data as float32 values.
	// Suitable for HDR displays and further processing.
	HDROutputFloat32

	// HDROutputUint16 outputs HDR data as 16-bit unsigned integers.
	// Suitable for high bit-depth workflows.
	HDROutputUint16
)

func (HDROutputMode) String

func (h HDROutputMode) String() string

String returns the HDR output mode name.

type HashLookupResult

type HashLookupResult struct {
	// EncoderFamily is the registered encoder family for this hash.
	EncoderFamily string

	// Quality is the quality level associated with this hash.
	Quality int

	// TableType indicates the type of table this hash represents.
	TableType TableType
}

HashLookupResult represents the result of looking up a table by hash.

type HierarchicalFrameStructure

type HierarchicalFrameStructure struct {
	// Original full-resolution image
	Original *ImageData

	// Pyramid of image levels from lowest to highest resolution
	Levels []*HierarchicalLevel

	// Options for hierarchical encoding
	Options *HierarchicalOptions
}

HierarchicalFrameStructure manages the multi-resolution pyramid for encoding.

func NewHierarchicalFrameStructure

func NewHierarchicalFrameStructure(img *ImageData, opts *HierarchicalOptions) (*HierarchicalFrameStructure, error)

NewHierarchicalFrameStructure creates a hierarchical structure from an image.

type HierarchicalFrameType

type HierarchicalFrameType int

HierarchicalFrameType indicates whether a frame is a reference or differential frame.

const (
	// FrameTypeNonDifferential is a standalone reference frame
	FrameTypeNonDifferential HierarchicalFrameType = iota
	// FrameTypeDifferential is a differential frame (encodes residuals)
	FrameTypeDifferential
)

type HierarchicalLevel

type HierarchicalLevel struct {
	// Width and height at this level
	Width  int
	Height int

	// Scale factor relative to full resolution (1 = full, 2 = half, etc.)
	ScaleFactor int

	// Frame type for this level
	FrameType HierarchicalFrameType

	// Image data at this level
	Data *ImageData
}

HierarchicalLevel represents a single level in the hierarchical pyramid.

type HierarchicalOptions

type HierarchicalOptions struct {
	// NumberOfLevels specifies how many resolution levels to encode (minimum 2)
	NumberOfLevels int

	// UseArithmetic enables arithmetic coding instead of Huffman
	UseArithmetic bool

	// BaseEncodingMode specifies the encoding mode for each level
	// Sequential, Progressive, or Lossless
	BaseEncodingMode DifferentialEncodingMode
}

HierarchicalOptions configures hierarchical/differential encoding.

func DefaultHierarchicalOptions

func DefaultHierarchicalOptions() *HierarchicalOptions

DefaultHierarchicalOptions returns sensible defaults for hierarchical encoding.

type HistogramBucket

type HistogramBucket struct {
	// Count is the number of coefficients in this bucket.
	Count int

	// RangeMin is the minimum value (inclusive) for this bucket.
	RangeMin int

	// RangeMax is the maximum value (inclusive) for this bucket.
	RangeMax int
}

HistogramBucket represents a single bucket in a coefficient histogram. It stores the count of coefficients falling within a specific value range.

type HologramData

type HologramData struct {
	Width       int         // Hologram width in pixels
	Height      int         // Hologram height in pixels
	Wavelength  float64     // Recording wavelength in meters
	PixelPitch  float64     // Pixel pitch in meters
	IsBinary    bool        // True if binary hologram, false if continuous-tone
	ComplexData []complex64 // Complex-valued hologram data (if applicable)
	RealData    []float32   // Real-valued hologram data (if binary)
}

HologramData represents decoded holographic data.

type HologramDecoder

type HologramDecoder interface {
	// DecodeHologram decodes holographic data from a reader.
	DecodeHologram(r io.Reader) (*HologramData, error)
}

HologramDecoder decodes holographic image data. Implements ISP for hologram data extraction. Used by JPEG Pleno Part 5 (ISO/IEC 21794-5).

type HuffTable

type HuffTable struct {

	// Public fields for backward compatibility
	BITS     [17]int
	HUFFVAL  [256]int
	HUFFCODE [257]int
	HUFFSIZE [257]int
	MINCODE  [17]int
	MAXCODE  [18]int
	VALPTR   [17]int
	Ln       int
	SI       int
	I        int
	J        int
	K        int
	LASTK    int
	CODE     int
	// contains filtered or unexported fields
}

HuffTable is a backward-compatible adapter for the refactored internal huffman table. This maintains the existing public API while using the improved internal implementation.

func NewHuffTable

func NewHuffTable(reader ByteReader) *HuffTable

NewHuffTable creates a new Huffman table from a byte reader. The reader parameter provides abstracted byte reading for platform independence.

type HuffmanAnalysisResult

type HuffmanAnalysisResult struct {
	// IsStandardDC indicates if DC tables match standard IJG patterns
	IsStandardDC bool

	// IsStandardAC indicates if AC tables match standard IJG patterns
	IsStandardAC bool

	// IsOptimized indicates if the Huffman tables appear to be optimized
	IsOptimized bool

	// HasCustomTables indicates completely custom (non-standard) tables
	HasCustomTables bool

	// DetectedPatterns contains specific pattern identifiers found
	DetectedPatterns []string

	// Confidence is the confidence in the analysis (0.0-1.0)
	Confidence float64
}

HuffmanAnalysisResult represents the result of Huffman table analysis.

type HuffmanBlockEncoder

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

HuffmanBlockEncoder encodes JPEG blocks using Huffman coding.

func NewHuffmanBlockEncoder

func NewHuffmanBlockEncoder(w io.Writer, dcTable, acTable *HuffmanEncoderTable) *HuffmanBlockEncoder

NewHuffmanBlockEncoder creates a new Huffman block encoder.

func (*HuffmanBlockEncoder) BytesWritten

func (e *HuffmanBlockEncoder) BytesWritten() int

BytesWritten returns the number of bytes written.

func (*HuffmanBlockEncoder) EncodeBlock

func (e *HuffmanBlockEncoder) EncodeBlock(block *[BlockSize2]int, prevDC int) (int, error)

EncodeBlock encodes a zigzag-ordered, quantized block. prevDC is the previous DC value for differential coding. Returns the new DC value.

func (*HuffmanBlockEncoder) Flush

func (e *HuffmanBlockEncoder) Flush() error

Flush flushes the bit stream writer.

type HuffmanDecode

type HuffmanDecode struct {

	// Public fields for backward compatibility
	X  int // Image width
	Y  int // Image height
	Nf int // Number of components
	// contains filtered or unexported fields
}

HuffmanDecode is a backward-compatible adapter for the refactored internal huffman decoder. This maintains the existing public API while using the improved internal implementation.

func NewHuffmanDecode

func NewHuffmanDecode(data []byte, reader ByteReader) *HuffmanDecode

NewHuffmanDecode creates a new Huffman decoder. The reader parameter provides abstracted byte reading for platform independence.

func NewHuffmanDecodeForCoefficients

func NewHuffmanDecodeForCoefficients(data []byte, reader ByteReader) *HuffmanDecode

NewHuffmanDecodeForCoefficients creates a decoder specifically for coefficient extraction. This is a convenience function that parses markers and prepares for full coefficient decoding. Use the Decode() method to extract all DCT coefficients from the JPEG.

func NewHuffmanDecodeForQTable

func NewHuffmanDecodeForQTable(data []byte, reader ByteReader) *HuffmanDecode

NewHuffmanDecodeForQTable creates a decoder specifically for Q-table extraction. This is a convenience function that only parses markers without decoding coefficients.

func (*HuffmanDecode) Decode

func (h *HuffmanDecode) Decode() ([]int, error)

Decode extracts DCT coefficients from the JPEG data. Returns array of quantized DCT coefficients or error.

func (*HuffmanDecode) GetComponentCount

func (h *HuffmanDecode) GetComponentCount() int

GetComponentCount returns the number of color components. Implements the ImageMetadata interface.

func (*HuffmanDecode) GetImageHeight

func (h *HuffmanDecode) GetImageHeight() int

GetImageHeight returns the image height in pixels. Implements the ImageMetadata interface.

func (*HuffmanDecode) GetImageWidth

func (h *HuffmanDecode) GetImageWidth() int

GetImageWidth returns the image width in pixels. Implements the ImageMetadata interface.

func (*HuffmanDecode) GetQuantTableIDs

func (h *HuffmanDecode) GetQuantTableIDs() []int

GetQuantTableIDs returns the quantization table ID for each component. Returns a slice where index 0=Y, 1=Cb, 2=Cr.

func (*HuffmanDecode) GetQuantizationTables

func (h *HuffmanDecode) GetQuantizationTables() map[int][64]int

GetQuantizationTables returns all quantization tables extracted from the JPEG. Returns a map of table ID (0-3) to 64-byte quantization table.

func (*HuffmanDecode) GetSamplingFactors

func (h *HuffmanDecode) GetSamplingFactors() (horizontal, vertical []int)

GetSamplingFactors returns the horizontal and vertical sampling factors for each component. Returns two slices: horizontal and vertical factors, indexed by component (0=Y, 1=Cb, 2=Cr). For 4:2:0: Y=(2,2), Cb=(1,1), Cr=(1,1) For 4:2:2: Y=(2,1), Cb=(1,1), Cr=(1,1) For 4:4:4: Y=(1,1), Cb=(1,1), Cr=(1,1)

type HuffmanDecoder

type HuffmanDecoder interface {
	// Decode extracts quantized DCT coefficients from JPEG entropy-coded data.
	// Returns array of coefficient values in zigzag order, or error if decoding fails.
	Decode() ([]int, error)

	// GetQuantizationTables returns the parsed quantization tables indexed by table ID.
	GetQuantizationTables() map[int][64]int
}

HuffmanDecoder defines the interface for Huffman decoding of JPEG entropy-coded data. This abstraction follows the Dependency Inversion Principle, allowing different. implementations of Huffman decoding while keeping the interface stable.

type HuffmanEncoderCode

type HuffmanEncoderCode struct {
	Code uint16 // The Huffman code bits
	Size byte   // Number of bits in the code
}

HuffmanEncoderCode represents a single Huffman code.

type HuffmanEncoderTable

type HuffmanEncoderTable struct {
	// Bits contains the count of codes for each length (1-16 bits).
	// Bits[i] = number of codes with length i+1.
	Bits [16]int

	// Values contains the symbol values in order of increasing code length.
	Values []byte

	// TableClass: 0 = DC, 1 = AC
	TableClass int

	// TableID: 0-3
	TableID int
	// contains filtered or unexported fields
}

HuffmanEncoderTable represents a Huffman coding table for JPEG encoding.

func GenerateEncoderHuffmanTable

func GenerateEncoderHuffmanTable(frequencies [256]int, class, id int) *HuffmanEncoderTable

GenerateEncoderHuffmanTable generates an optimal Huffman table from symbol frequencies using the procedure specified in T.81 Annex K.2 (figures K.1 and K.3), matching libjpeg-turbo's jpeg_gen_optimal_table. The procedure:

  1. Insert a sentinel symbol (index 256) with frequency 1 so the all-ones code never appears in the final table — T.81 §F.1.2.1.3 reserves the all-ones code for decoder synchronization, and decoders including libjpeg-turbo reject tables that would emit it.
  2. Build a Huffman tree in-place over freq[0..256] and sibling pointers (others[0..256]) per T.81 K.2 figure K.1. Each iteration merges the two least-frequent symbols into a tree, marking one root with -1 to remove it from future merges.
  3. Walk codesize[0..256] → bits[1..32] frequency-of-length histogram, tracking counts up to length 32 before limiting.
  4. Limit code lengths to 16 bits using T.81 K.2 figure K.3: for each overlong length i (from 32 down to 17), promote pairs from shorter lengths to absorb the overlong codes into length <= 16.
  5. Drop the sentinel symbol (bits[longest]--) so the final table carries only real symbols but keeps the all-ones prefix reserved.
  6. Sort symbols by (length, symbol) into values[], producing the canonical JPEG DHT wire form (bits array + values array).

The resulting table is decoder-compatible with libjpeg-turbo, Go's stdlib image/jpeg, and every other conformant T.81 JPEG decoder. It replaces a prior simpler implementation whose code-length limiter violated the Kraft inequality on common inputs, producing DHT markers djpeg rejected as "Bogus Huffman table definition".

func NewHuffmanEncoderTable

func NewHuffmanEncoderTable(bits [16]int, values []byte, class, id int) *HuffmanEncoderTable

NewHuffmanEncoderTable creates a new Huffman table from bits and values.

func NewStandardEncoderACChrominanceTable

func NewStandardEncoderACChrominanceTable() *HuffmanEncoderTable

NewStandardEncoderACChrominanceTable creates the standard AC chrominance table.

func NewStandardEncoderACLuminanceTable

func NewStandardEncoderACLuminanceTable() *HuffmanEncoderTable

NewStandardEncoderACLuminanceTable creates the standard AC luminance table.

func NewStandardEncoderDCChrominanceTable

func NewStandardEncoderDCChrominanceTable() *HuffmanEncoderTable

NewStandardEncoderDCChrominanceTable creates the standard DC chrominance table.

func NewStandardEncoderDCLuminanceTable

func NewStandardEncoderDCLuminanceTable() *HuffmanEncoderTable

NewStandardEncoderDCLuminanceTable creates the standard DC luminance table.

func (*HuffmanEncoderTable) Encode

func (h *HuffmanEncoderTable) Encode(symbol byte) HuffmanEncoderCode

Encode returns the Huffman code for a symbol.

func (*HuffmanEncoderTable) GetCode

func (h *HuffmanEncoderTable) GetCode(symbol byte) (code uint16, size byte)

GetCode returns the code and size for a symbol.

type HuffmanFrequencyCounter

type HuffmanFrequencyCounter struct {
	DCFreq [256]int
	ACFreq [256]int
}

HuffmanFrequencyCounter counts symbol frequencies for Huffman table generation.

func NewHuffmanFrequencyCounter

func NewHuffmanFrequencyCounter() *HuffmanFrequencyCounter

NewHuffmanFrequencyCounter creates a new frequency counter.

func (*HuffmanFrequencyCounter) CountBlock

func (fc *HuffmanFrequencyCounter) CountBlock(block *[BlockSize2]int, prevDC int) int

CountBlock counts frequencies for a zigzag-ordered block.

func (*HuffmanFrequencyCounter) GenerateACTable

func (fc *HuffmanFrequencyCounter) GenerateACTable(class, id int) *HuffmanEncoderTable

GenerateACTable generates an optimized AC Huffman table.

func (*HuffmanFrequencyCounter) GenerateDCTable

func (fc *HuffmanFrequencyCounter) GenerateDCTable(class, id int) *HuffmanEncoderTable

GenerateDCTable generates an optimized DC Huffman table.

type HuffmanSignatureAnalyzer

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

HuffmanSignatureAnalyzer analyzes Huffman tables for encoder identification. It stores standard IJG DC and AC Huffman table patterns and detects optimized or custom Huffman tables.

func NewHuffmanSignatureAnalyzer

func NewHuffmanSignatureAnalyzer() *HuffmanSignatureAnalyzer

NewHuffmanSignatureAnalyzer creates a new Huffman signature analyzer initialized with standard IJG Huffman table patterns.

func (*HuffmanSignatureAnalyzer) AnalyzeHuffmanTables

func (a *HuffmanSignatureAnalyzer) AnalyzeHuffmanTables(dhtSegments []*DHTSegment) *HuffmanAnalysisResult

AnalyzeHuffmanTables analyzes DHT segments for encoder patterns.

Parameters:

  • dhtSegments: Slice of DHTSegment structures from parsed DHT markers

Returns:

  • *HuffmanAnalysisResult: Analysis result with patterns and confidence

type HuffmanSpec

type HuffmanSpec struct {
	// Class indicates the table type: 0 = DC table, 1 = AC table.
	Class int

	// ID is the table identifier (0-3).
	// Tables are referenced by this ID in ScanComponent.DCTableID/ACTableID.
	ID int

	// Bits contains the count of codes for each length (1-16 bits).
	// Bits[i] = number of Huffman codes with length i+1.
	Bits [16]int

	// Values contains the symbol values in order of increasing code length.
	// The number of values should equal the sum of Bits[].
	Values []byte
}

HuffmanSpec defines a Huffman table for the DHT (Define Huffman Table) marker.

JPEG uses separate Huffman tables for DC and AC coefficients, and can have different tables for luminance and chrominance components.

func GetStandardHuffmanSpecs

func GetStandardHuffmanSpecs() []HuffmanSpec

GetStandardHuffmanSpecs returns the four standard Huffman table specifications from ITU-T T.81 Annex K.

Returns specs for: - DC Luminance (Class=0, ID=0) - DC Chrominance (Class=0, ID=1) - AC Luminance (Class=1, ID=0) - AC Chrominance (Class=1, ID=1)

type HuffmanTableInfo

type HuffmanTableInfo struct {
	// Class indicates the table class:
	// 0 = DC coefficient table
	// 1 = AC coefficient table
	Class int

	// ID is the table destination identifier (0-3).
	ID int

	// SymbolCounts contains the number of Huffman codes of each length (1-16 bits).
	// SymbolCounts[i] is the count of codes with length (i+1) bits.
	SymbolCounts [16]int

	// Symbols contains the symbol values in order of increasing code length.
	// The length matches the sum of all SymbolCounts values.
	Symbols []byte
}

HuffmanTableInfo contains Huffman table metadata for signature analysis.

type ImageData

type ImageData struct {
	Width         int        // Image width in pixels
	Height        int        // Image height in pixels
	Pixels        []byte     // Pixel data (interleaved by color space)
	Stride        int        // Bytes per row
	ColorSpace    ColorSpace // Color space of pixel data
	BitsPerSample int        // Bits per sample (8, 12, or 16)
}

ImageData represents raw pixel data for encoding.

func NewImageData

func NewImageData(width, height int, colorSpace ColorSpace) *ImageData

NewImageData creates a new ImageData from dimensions and color space. Note: For production use with untrusted input, use NewImageDataSafe instead which performs comprehensive validation and overflow checking.

func NewImageDataFromImage

func NewImageDataFromImage(img image.Image) *ImageData

NewImageDataFromImage creates ImageData from Go's image.Image. Returns nil if the image dimensions would cause buffer overflow.

func NewImageDataSafe

func NewImageDataSafe(width, height int, colorSpace ColorSpace) (*ImageData, error)

NewImageDataSafe creates a new ImageData with validation. Returns an error if dimensions are invalid or would exceed resource limits.

func (*ImageData) GetPixel

func (img *ImageData) GetPixel(x, y int) []byte

GetPixel returns the pixel values at (x, y). Returns nil if coordinates are out of bounds or would cause overflow.

func (*ImageData) SetPixel

func (img *ImageData) SetPixel(x, y int, values []byte)

SetPixel sets the pixel values at (x, y). Does nothing if coordinates are out of bounds or would cause overflow.

type ImageDecoder

type ImageDecoder interface {
	// Decode decodes JPEG image data to a reconstructed pixel image.
	// Returns *image.RGBA for color images (YCbCr, CMYK converted to RGB).
	// Returns *image.Gray for grayscale images.
	// Returns error if the JPEG data is invalid or cannot be decoded.
	Decode(data []byte) (image.Image, error)
}

ImageDecoder defines the interface for decoding JPEG images to pixel data. This interface complements CoefficientExtractor by providing full pixel reconstruction from JPEG data through IDCT transformation and color conversion.

The Decoder struct implements both CoefficientExtractor and ImageDecoder interfaces, allowing users to either extract raw DCT coefficients for analysis (Extract) or decode to a complete pixel image (Decode).

func NewImageDecoder

func NewImageDecoder() ImageDecoder

NewImageDecoder creates a new JPEG image decoder. Returns an implementation of ImageDecoder.

Use this when you need to decode JPEG data to a pixel image (image.Image). The decoder performs full IDCT reconstruction with configurable options for DCT implementation, color conversion, and chroma upsampling.

type ImageInfo

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

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

	// NumChannels is the number of color channels.
	// Common values: 1 (grayscale), 3 (RGB/YCbCr), 4 (RGBA/CMYK)
	NumChannels int

	// BitDepth is the number of bits per sample.
	// Common values: 8, 12, 16
	BitDepth int

	// Format is the detected JPEG format type.
	Format Format

	// HasHDR indicates if the image contains HDR extension data.
	// This is true for JPEG XT images with HDR extensions.
	HasHDR bool

	// IsLowLatency indicates if the format is designed for low-latency decoding.
	// This is true for JPEG XS format.
	IsLowLatency bool
}

ImageInfo contains metadata about a decoded image. This is the public type returned by the public API convenience functions.

ImageInfo provides essential information about the image format, dimensions, and capabilities without requiring a full decode operation. Use DecodeInfo to obtain this information efficiently.

func DecodeInfo

func DecodeInfo(r io.Reader) (info *ImageInfo, err error)

DecodeInfo reads JPEG metadata from r without fully decoding the image. This is useful for getting image dimensions and format information quickly.

The returned ImageInfo contains:

  • Image dimensions (Width, Height)
  • Color information (NumChannels, BitDepth)
  • Format type (Format)
  • HDR and low-latency capability flags

Returns an error if the reader is nil, empty, or contains invalid data.

Example:

info, err := jpeg.DecodeInfo(reader)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Format: %s, Size: %dx%d\n", info.Format, info.Width, info.Height)
Example

ExampleDecodeInfo demonstrates getting image information without full decoding. This is useful for checking image dimensions before processing.

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/0verkilll/jpeg"
)

// createExampleJPEG creates a minimal valid baseline JPEG for examples.
// This returns a 1x1 grayscale JPEG image.
func createExampleJPEG() []byte {
	return []byte{

		0xFF, 0xD8,

		0xFF, 0xE0, 0x00, 0x10,
		'J', 'F', 'I', 'F', 0x00,
		0x01, 0x01,
		0x00,
		0x00, 0x01,
		0x00, 0x01,
		0x00, 0x00,

		0xFF, 0xDB, 0x00, 0x43, 0x00,

		16, 11, 10, 16, 24, 40, 51, 61,
		12, 12, 14, 19, 26, 58, 60, 55,
		14, 13, 16, 24, 40, 57, 69, 56,
		14, 17, 22, 29, 51, 87, 80, 62,
		18, 22, 37, 56, 68, 109, 103, 77,
		24, 35, 55, 64, 81, 104, 113, 92,
		49, 64, 78, 87, 103, 121, 120, 101,
		72, 92, 95, 98, 112, 100, 103, 99,

		0xFF, 0xC0, 0x00, 0x0B,
		0x08,
		0x00, 0x01,
		0x00, 0x01,
		0x01,
		0x01,
		0x11,
		0x00,

		0xFF, 0xC4, 0x00, 0x1F, 0x00,
		0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
		0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
		0x08, 0x09, 0x0A, 0x0B,

		0xFF, 0xC4, 0x00, 0xB5, 0x10,
		0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
		0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D,
		0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
		0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
		0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
		0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
		0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16,
		0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
		0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
		0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
		0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
		0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
		0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
		0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
		0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
		0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
		0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
		0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
		0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
		0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
		0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,
		0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
		0xF9, 0xFA,

		0xFF, 0xDA, 0x00, 0x08,
		0x01,
		0x01, 0x00,
		0x00, 0x3F, 0x00,

		0xFB, 0xD3, 0x28, 0xA6,

		0xFF, 0xD9,
	}
}

func main() {
	jpegData := createExampleJPEG()

	// Get image info without full decode
	info, err := jpeg.DecodeInfo(bytes.NewReader(jpegData))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Size: %dx%d\n", info.Width, info.Height)
	fmt.Printf("Channels: %d\n", info.NumChannels)
	fmt.Printf("Bit depth: %d\n", info.BitDepth)
}
Output:
Size: 1x1
Channels: 1
Bit depth: 8

type ImageReconstructor

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

ImageReconstructor coordinates the reconstruction of a complete JPEG image from quantized DCT coefficients.

func NewImageReconstructor

func NewImageReconstructor(subsampling ChromaSubsampling, quantTables map[int][BlockSize2]int) *ImageReconstructor

NewImageReconstructor creates an ImageReconstructor for the given subsampling mode.

func (*ImageReconstructor) GetComponentReconstructor

func (ir *ImageReconstructor) GetComponentReconstructor(component int) *ComponentReconstructor

GetComponentReconstructor returns the reconstructor for a specific component. component: 0=Y, 1=Cb, 2=Cr

func (*ImageReconstructor) GetMCUProcessor

func (ir *ImageReconstructor) GetMCUProcessor() *MCUProcessor

GetMCUProcessor returns the MCU processor for accessing MCU organization details.

func (*ImageReconstructor) GetQuantTable

func (ir *ImageReconstructor) GetQuantTable(tableID int) *[BlockSize2]int

GetQuantTable returns the quantization table for the given table ID.

func (*ImageReconstructor) ResetAtRestartMarker

func (ir *ImageReconstructor) ResetAtRestartMarker()

ResetAtRestartMarker resets all DC predictors at a restart marker boundary.

type InferenceEngine

type InferenceEngine interface {
	// Infer runs inference on the provided latent tensor data.
	// Returns the reconstructed image tensor.
	Infer(latentData []float32) ([]float32, error)

	// GetModelInfo returns information about the loaded model.
	GetModelInfo() (*ModelInfo, error)
}

InferenceEngine executes neural network inference. Implements ISP for inference execution. Abstracts the neural network backend for JPEG AI.

type JP2Box

type JP2Box struct {
	Type     string // 4-character box type
	Length   int64  // Box length in bytes
	Position int64  // Box position in file
	Data     []byte // Box data (for small boxes)
}

JP2Box represents a JPEG 2000 box structure.

type JP2BoxReader

type JP2BoxReader interface {
	// ReadBox reads the next box header.
	ReadBox() (*JP2Box, error)

	// ReadBoxData reads the data for a box.
	ReadBoxData(box *JP2Box) ([]byte, error)

	// EnterSuperBox enters a superbox to read its children.
	EnterSuperBox(box *JP2Box) error

	// ExitSuperBox exits the current superbox.
	ExitSuperBox() error

	// Position returns the current read position.
	Position() int64

	// Remaining returns bytes remaining in current context.
	Remaining() int64
}

JP2BoxReader reads JPEG 2000 boxes from a container. Implements ISP for JPEG 2000 box parsing.

func NewJP2BoxReader

func NewJP2BoxReader(data []byte) JP2BoxReader

NewJP2BoxReader creates a new JP2BoxReader from byte data.

type JUMBFBox

type JUMBFBox struct {
	Type        [4]byte    // Box type identifier
	Label       string     // Optional label
	ID          uint32     // Optional ID
	ContentType string     // Content type (xml, json, cbor, codestream, uuid)
	Data        []byte     // Box content data
	Children    []JUMBFBox // Nested boxes (for superboxes)
}

JUMBFBox represents a JUMBF (JPEG Universal Metadata Box Format) box.

type JUMBFReader

type JUMBFReader interface {
	// ReadBox reads the next JUMBF box from the data.
	ReadBox(data []byte) (*JUMBFBox, error)

	// FindBoxByType finds all boxes of a specific type.
	FindBoxByType(data []byte, boxType [4]byte) ([]*JUMBFBox, error)
}

JUMBFReader reads JUMBF metadata boxes. Implements ISP for JUMBF parsing operations. Used by JPEG Systems Part 5 (ISO/IEC 19566-5).

type LightFieldDecodeMetadata

type LightFieldDecodeMetadata struct {
	UCount           int     // Number of horizontal views
	VCount           int     // Number of vertical views
	AngularPrecision float64 // Angular precision in degrees
	BaselineU        float64 // Horizontal baseline in mm
	BaselineV        float64 // Vertical baseline in mm
}

LightFieldDecodeMetadata contains light field metadata.

type LightFieldDecoder

type LightFieldDecoder interface {
	// DecodeView decodes a specific view from the light field.
	// u, v are angular coordinates identifying the view.
	DecodeView(u, v int) (*LightFieldView, error)

	// GetViewCount returns the dimensions of the light field (angular resolution).
	GetViewCount() (uCount, vCount int, err error)
}

LightFieldDecoder decodes 4D light field images. Implements ISP for light field data extraction. Used by JPEG Pleno Part 2 (ISO/IEC 21794-2).

type LightFieldView

type LightFieldView struct {
	U, V   int    // Angular coordinates in the light field
	Width  int    // View width in pixels
	Height int    // View height in pixels
	Pixels []byte // Pixel data for this view
}

LightFieldView represents a single view in a light field.

type LightFieldViewMode

type LightFieldViewMode int

LightFieldViewMode specifies how light field data should be extracted.

const (
	// LightFieldViewCenter extracts only the center view.
	// Default mode for simple display.
	LightFieldViewCenter LightFieldViewMode = iota

	// LightFieldViewAll extracts all views in the light field.
	// Returns multiple images for further processing.
	LightFieldViewAll

	// LightFieldViewSpecific extracts a specific view by coordinates.
	// Requires LightFieldViewU and LightFieldViewV to be set.
	LightFieldViewSpecific
)

func (LightFieldViewMode) String

func (l LightFieldViewMode) String() string

String returns the light field view mode name.

type LineBufferDecoder

type LineBufferDecoder interface {
	// BufferLine adds a coded line to the decoder buffer.
	BufferLine(lineData []byte) error

	// FlushLine retrieves and removes the oldest decoded line.
	FlushLine() ([]byte, error)

	// BufferedLines returns the number of lines currently buffered.
	BufferedLines() int
}

LineBufferDecoder provides line-based buffered decoding. Implements ISP for memory-bounded line processing. Ensures bounded memory usage as required by JPEG XS.

type LosslessEncoderImpl

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

LosslessEncoderImpl implements lossless JPEG encoding (SOF3).

func NewLosslessEncoder

func NewLosslessEncoder(opts *EncoderOptions) *LosslessEncoderImpl

NewLosslessEncoder creates a new lossless JPEG encoder with default options.

func NewLosslessEncoderWithOptions

func NewLosslessEncoderWithOptions(opts *EncoderOptions, losslessOpts *LosslessOptions) *LosslessEncoderImpl

NewLosslessEncoderWithOptions creates a lossless encoder with specific options.

func NewLosslessEncoderWithPredictor

func NewLosslessEncoderWithPredictor(opts *EncoderOptions, predictor int) *LosslessEncoderImpl

NewLosslessEncoderWithPredictor creates a lossless encoder with a specific predictor.

func (*LosslessEncoderImpl) Encode

func (e *LosslessEncoderImpl) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to lossless JPEG bytes.

func (*LosslessEncoderImpl) EncodeImage

func (e *LosslessEncoderImpl) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to lossless JPEG bytes.

func (*LosslessEncoderImpl) Format

func (e *LosslessEncoderImpl) Format() Format

Format returns the target encoding format.

func (*LosslessEncoderImpl) PointTransform

func (e *LosslessEncoderImpl) PointTransform() int

PointTransform returns the current point transform value.

func (*LosslessEncoderImpl) Precision

func (e *LosslessEncoderImpl) Precision() int

Precision returns the current sample precision.

func (*LosslessEncoderImpl) Predictor

func (e *LosslessEncoderImpl) Predictor() int

Predictor returns the current predictor mode.

func (*LosslessEncoderImpl) SetPointTransform

func (e *LosslessEncoderImpl) SetPointTransform(pt int) error

SetPointTransform sets the point transform value (0-15).

func (*LosslessEncoderImpl) SetPrecision

func (e *LosslessEncoderImpl) SetPrecision(precision int) error

SetPrecision sets the sample precision (2-16 bits).

func (*LosslessEncoderImpl) SetPredictor

func (e *LosslessEncoderImpl) SetPredictor(predictor int) error

SetPredictor sets the prediction mode (1-7).

func (*LosslessEncoderImpl) SetQuality

func (e *LosslessEncoderImpl) SetQuality(_ int) error

SetQuality is a no-op for lossless encoding.

type LosslessOptions

type LosslessOptions struct {
	// Predictor selects the prediction mode (1-7)
	Predictor int

	// PointTransform specifies the point transform value (0-15)
	// This effectively reduces precision by shifting sample values
	PointTransform int

	// Precision is the sample precision in bits (2-16)
	Precision int
}

LosslessOptions contains options specific to lossless JPEG encoding.

func DefaultLosslessOptions

func DefaultLosslessOptions() *LosslessOptions

DefaultLosslessOptions returns default options for lossless encoding.

type LowLatencyDecoder

type LowLatencyDecoder interface {
	// DecodeLine decodes a single line of the image.
	// Returns decoded pixel data for the specified line.
	// Enables sub-frame latency by processing line-by-line.
	DecodeLine(lineNumber int) ([]byte, error)
}

LowLatencyDecoder decodes images with minimal latency. Implements ISP for low-latency decoding operations. Used by JPEG XS (ISO/IEC 21122) for broadcast applications.

type LowLatencyEncoder

type LowLatencyEncoder interface {
	// EncodeLine encodes a single line of the image.
	// Returns the encoded data for the specified line.
	EncodeLine(lineNumber int, pixels []byte) ([]byte, error)
}

LowLatencyEncoder encodes images with minimal latency. Implements ISP for low-latency encoding operations. Used by JPEG XS (ISO/IEC 21122) for broadcast applications.

type MCUProcessor

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

MCUProcessor handles Minimum Coded Unit (MCU) organization for different chroma subsampling modes during JPEG decoding.

JPEG encodes images in MCUs, where each MCU contains one or more 8x8 blocks per color component. The number of blocks depends on the chroma subsampling:

  • 4:4:4: 1 Y + 1 Cb + 1 Cr (3 blocks total, 8x8 pixels)
  • 4:2:2: 2 Y + 1 Cb + 1 Cr (4 blocks total, 16x8 pixels)
  • 4:2:0: 4 Y + 1 Cb + 1 Cr (6 blocks total, 16x16 pixels)

func NewMCUProcessor

func NewMCUProcessor(subsampling ChromaSubsampling) *MCUProcessor

NewMCUProcessor creates an MCUProcessor for the given chroma subsampling mode.

func NewMCUProcessorFromSamplingFactors

func NewMCUProcessorFromSamplingFactors(hSampleY, vSampleY, hSampleC, vSampleC int) *MCUProcessor

NewMCUProcessorFromSamplingFactors creates an MCUProcessor from explicit sampling factors. This is useful when parsing SOF markers that provide per-component sampling factors.

func (*MCUProcessor) BlocksPerMCU

func (mcu *MCUProcessor) BlocksPerMCU() (yBlocks, cbBlocks, crBlocks int)

BlocksPerMCU returns the number of blocks per MCU for each component. For YCbCr images: returns (Y blocks, Cb blocks, Cr blocks). For grayscale: returns (Y blocks, 0, 0).

func (*MCUProcessor) CalculateMCUCount

func (mcu *MCUProcessor) CalculateMCUCount(imageWidth, imageHeight int) (mcuCols, mcuRows int)

CalculateMCUCount returns the number of MCUs needed to cover an image.

func (*MCUProcessor) GetSamplingFactors

func (mcu *MCUProcessor) GetSamplingFactors() (hY, vY, hC, vC int)

GetSamplingFactors returns the sampling factors for Y and chroma components.

func (*MCUProcessor) MCUPixelSize

func (mcu *MCUProcessor) MCUPixelSize() (width, height int)

MCUPixelSize returns the pixel dimensions covered by one MCU.

func (*MCUProcessor) Subsampling

func (mcu *MCUProcessor) Subsampling() ChromaSubsampling

Subsampling returns the chroma subsampling mode.

type Marker

type Marker = markers.Marker

Marker represents a JPEG marker with position and metadata.

type MarkerParser

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

MarkerParser extracts JPEG markers and their positions. This is a backward-compatibility adapter that delegates to the internal parser. Follows the Adapter pattern to maintain existing API while using new implementation.

func NewMarkerParser

func NewMarkerParser(_ ByteReader) *MarkerParser

NewMarkerParser creates a new marker parser. Uses dependency injection with default validator.

func (*MarkerParser) Parse

func (p *MarkerParser) Parse(data []byte) ([]Marker, error)

Parse extracts all JPEG markers from the data. Delegates to the internal parser implementation.

type MarkerParserInterface

type MarkerParserInterface interface {
	// Parse extracts all JPEG markers from the data.
	// Returns array of markers with positions and metadata, or error if parsing fails.
	Parse(data []byte) ([]Marker, error)
}

MarkerParserInterface defines the interface for parsing JPEG markers. This abstraction follows the Dependency Inversion Principle, allowing different. implementations of marker parsing while keeping the interface stable.

type MarkerReader

type MarkerReader interface {
	// ReadMarker reads the next marker byte (after 0xFF prefix).
	// Returns the marker code or error if reading fails.
	ReadMarker() (byte, error)

	// ReadSegmentLength reads a 16-bit big-endian segment length.
	// Returns the length value or error if reading fails.
	ReadSegmentLength() (int, error)

	// ReadSegment reads the specified number of bytes.
	// Returns the segment data or error if reading fails.
	ReadSegment(length int) ([]byte, error)

	// Position returns the current read position in the stream.
	Position() int

	// Remaining returns the number of bytes remaining to read.
	Remaining() int

	// Skip advances the position by the specified number of bytes.
	Skip(n int) error
}

MarkerReader reads JPEG markers from a byte stream. Implements ISP with focused marker reading methods.

func NewMarkerReader

func NewMarkerReader(data []byte) MarkerReader

NewMarkerReader creates a new MarkerReader from byte data. This is the factory function for creating MarkerReader instances.

type ModelInfo

type ModelInfo struct {
	Name       string // Model name/identifier
	Version    string // Model version
	InputSize  [4]int // Expected input tensor dimensions [N,C,H,W]
	OutputSize [4]int // Expected output tensor dimensions
	Precision  string // Model precision (float32, float16, int8)
}

ModelInfo contains information about a neural network model.

type ModelLoader

type ModelLoader interface {
	// LoadModel loads a neural network model from the given path.
	LoadModel(path string) (*ModelInfo, error)

	// UnloadModel releases the currently loaded model.
	UnloadModel() error

	// IsModelLoaded returns true if a model is currently loaded.
	IsModelLoaded() bool
}

ModelLoader loads neural network models for inference. Implements ISP for model loading operations. Allows external model loading for JPEG AI decoding.

type MultiAlgorithmEstimator

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

MultiAlgorithmEstimator implements QualityEstimator by combining multiple estimation algorithms for more accurate quality detection.

func NewMultiAlgorithmEstimator

func NewMultiAlgorithmEstimator(config *AlgorithmConfig) *MultiAlgorithmEstimator

NewMultiAlgorithmEstimator creates a new multi-algorithm estimator with the provided configuration. If config is nil, default settings are used.

Default configuration:

  • LeastSquares: enabled with weight 1.0 (highest priority)
  • ScaleFactor: enabled with weight 0.8
  • DCTHistogram: enabled with weight 0.6

func (*MultiAlgorithmEstimator) EstimateQuality

func (m *MultiAlgorithmEstimator) EstimateQuality(data []byte) (*QualityEstimate, error)

EstimateQuality analyzes raw JPEG file bytes to estimate compression quality using multiple algorithms for improved accuracy.

func (*MultiAlgorithmEstimator) EstimateQualityFromTables

func (m *MultiAlgorithmEstimator) EstimateQualityFromTables(tables map[int][64]int) (*QualityEstimate, error)

EstimateQualityFromTables estimates quality from pre-parsed quantization tables using multiple algorithms for improved accuracy.

type NeuralDecoder

type NeuralDecoder interface {
	// DecodeNeural decodes an image using neural network inference.
	// Requires a configured inference engine.
	DecodeNeural(r io.Reader) ([]byte, error)
}

NeuralDecoder decodes images using neural network inference. Implements ISP for neural codec operations. Used by JPEG AI (ISO/IEC) for learned image compression.

type NopLogger

type NopLogger struct{}

NopLogger is a no-operation logger.LeveledLogger implementation that discards all log messages. It is the default logger used when no custom logger is configured, ensuring that logging functionality has zero overhead when not needed.

NopLogger is designed for zero allocations - all methods are empty and immediately return without processing any arguments. This makes it suitable for high-performance code paths where logging is optional.

The zero value of NopLogger is ready to use:

var nop NopLogger
nop.Debug("message", "key", "value") // does nothing

Example - Using NopLogger explicitly:

// Explicitly set NopLogger to disable logging
jpeg.SetLogger(&jpeg.NopLogger{})

// Or simply set nil (equivalent behavior)
jpeg.SetLogger(nil)

Example - Using NopLogger in tests:

func TestMyFunction(t *testing.T) {
    // Ensure no logging output during tests
    jpeg.SetLogger(&jpeg.NopLogger{})
    defer jpeg.SetLogger(nil)

    // ... test code ...
}

Thread Safety: NopLogger is safe for concurrent use from multiple goroutines as it maintains no internal state.

func (*NopLogger) Debug

func (l *NopLogger) Debug(_ string, _ ...any)

Debug discards the message and arguments without any processing. This method has zero allocations and returns immediately.

func (*NopLogger) Error

func (l *NopLogger) Error(_ string, _ ...any)

Error discards the message and arguments without any processing. This method has zero allocations and returns immediately.

func (*NopLogger) Fatal

func (l *NopLogger) Fatal(_ string, _ ...any)

Fatal discards the message and arguments without any processing. This method has zero allocations and returns immediately. Note: Unlike typical Fatal implementations, NopLogger does NOT terminate the program.

func (*NopLogger) Info

func (l *NopLogger) Info(_ string, _ ...any)

Info discards the message and arguments without any processing. This method has zero allocations and returns immediately.

func (*NopLogger) Warn

func (l *NopLogger) Warn(_ string, _ ...any)

Warn discards the message and arguments without any processing. This method has zero allocations and returns immediately.

type OverflowError

type OverflowError struct {
	Operation string // The operation that overflowed (e.g., "multiply", "add")
	Operand1  int64  // First operand
	Operand2  int64  // Second operand (if applicable)
	Context   string // Additional context (e.g., "buffer size calculation")
	Cause     error  // Underlying cause
}

OverflowError represents an integer overflow during calculations. It provides details about the operation that caused the overflow.

func NewOverflowError

func NewOverflowError(operation string, op1, op2 int64, context string) *OverflowError

NewOverflowError creates a new OverflowError.

func (*OverflowError) Error

func (e *OverflowError) Error() string

Error implements the error interface.

func (*OverflowError) Is

func (e *OverflowError) Is(target error) bool

Is implements the errors.Is interface.

func (*OverflowError) Unwrap

func (e *OverflowError) Unwrap() error

Unwrap implements the errors.Unwrap interface.

type ParseError

type ParseError struct {
	Position int    // Byte position where error occurred
	Marker   byte   // Marker code if applicable
	Message  string // Error description
	Cause    error  // Underlying error
}

ParseError represents an error during JPEG parsing.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

type PatternDetectionResult

type PatternDetectionResult struct {
	// EncoderFamily is the detected encoder family.
	EncoderFamily string

	// EncoderName is the specific encoder name when identifiable.
	EncoderName string

	// DetectedQuality is the detected quality level (1-100) for standard tables.
	DetectedQuality int

	// Confidence is the detection confidence (0.0-1.0).
	Confidence float64

	// DetectedPatterns lists all patterns that matched.
	DetectedPatterns []string
}

PatternDetectionResult represents the result of a pattern detection operation.

type PatternMatcher

type PatternMatcher interface {
	// Name returns the name of this pattern matcher.
	Name() string

	// Priority returns the priority of this matcher (lower = higher priority).
	// More specific matchers should have lower priority values.
	Priority() int

	// Match attempts to match the given tables against known patterns.
	// Returns a result if a match is found, or nil if no match.
	Match(tables map[int][64]int, hints *APPMarkerHints) *PatternDetectionResult
}

PatternMatcher defines the interface for encoder pattern detection. Implementations should detect specific encoder patterns from quantization tables.

func GetRegisteredPatternMatchers

func GetRegisteredPatternMatchers() []PatternMatcher

GetRegisteredPatternMatchers returns all registered pattern matchers sorted by priority (most specific first).

type Point3D

type Point3D struct {
	X, Y, Z    float32 // Coordinates
	R, G, B    uint8   // Color (optional)
	NX, NY, NZ float32 // Normal vector (optional)
}

Point3D represents a point in 3D space.

type PointCloudData

type PointCloudData struct {
	Points      []Point3D // The decoded points
	HasColor    bool      // True if color information is present
	HasNormals  bool      // True if normal vectors are present
	BoundingBox struct {
		MinX, MinY, MinZ float32
		MaxX, MaxY, MaxZ float32
	}
}

PointCloudData represents decoded point cloud data.

type PointCloudDecoder

type PointCloudDecoder interface {
	// DecodePointCloud decodes point cloud data from a reader.
	DecodePointCloud(r io.Reader) (*PointCloudData, error)
}

PointCloudDecoder decodes 3D point cloud data. Implements ISP for point cloud extraction. Used by JPEG Pleno Part 6 (ISO/IEC 21794-6).

type PointCloudOutputFormat

type PointCloudOutputFormat int

PointCloudOutputFormat specifies the format for point cloud output.

const (
	// PointCloudRaw outputs raw point coordinates and attributes.
	// Default format suitable for most applications.
	PointCloudRaw PointCloudOutputFormat = iota

	// PointCloudPLY outputs in PLY (Polygon File Format).
	// Standard format for point cloud interchange.
	PointCloudPLY

	// PointCloudXYZ outputs in simple XYZ text format.
	// Simple format with one point per line.
	PointCloudXYZ
)

func (PointCloudOutputFormat) String

func (p PointCloudOutputFormat) String() string

String returns the point cloud output format name.

type PointCloudResult

type PointCloudResult struct {
	// Points contains the 3D coordinates
	Points [][3]float32

	// Colors contains RGB colors for each point (if available)
	Colors [][3]uint8

	// Normals contains surface normals for each point (if available)
	Normals [][3]float32

	// HasColors indicates if color data is present
	HasColors bool

	// HasNormals indicates if normal data is present
	HasNormals bool

	// BoundingBox defines the spatial extent of the point cloud
	BoundingBox struct {
		Min [3]float32
		Max [3]float32
	}
}

PointCloudResult contains decoded point cloud data.

type ProgressiveEncoderImpl

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

ProgressiveEncoderImpl implements progressive JPEG encoding (SOF2).

func NewProgressiveEncoder

func NewProgressiveEncoder(opts *EncoderOptions) *ProgressiveEncoderImpl

NewProgressiveEncoder creates a new progressive JPEG encoder.

func NewProgressiveEncoderWithScript

func NewProgressiveEncoderWithScript(opts *EncoderOptions, script *ScanScript) *ProgressiveEncoderImpl

NewProgressiveEncoderWithScript creates a progressive encoder with a custom scan script.

func (*ProgressiveEncoderImpl) Encode

func (e *ProgressiveEncoderImpl) Encode(img *ImageData) ([]byte, error)

Encode encodes raw pixel data to progressive JPEG bytes.

func (*ProgressiveEncoderImpl) EncodeCoefficients

func (e *ProgressiveEncoderImpl) EncodeCoefficients(coefficients []int, meta *CoeffEncoderMetadata) ([]byte, error)

EncodeCoefficients encodes pre-quantized DCT coefficients into a PROGRESSIVE (SOF2) JPEG, writing the coefficient values bit-exact. Because the values are preserved, an F5 steganography payload embedded in them survives, while the frame becomes progressive (e.g. mozjpeg-style) rather than baseline. The coefficient slice is the same MCU-interleaved, zigzag, DC-at-0 layout the decoder's ExtractCoefficients produces. It mirrors (*baselineEncoder). EncodeCoefficients but emits a progressive frame via a lossless (Al=0 per band) scan script, so decode(encode(coeffs)) == coeffs.

func (*ProgressiveEncoderImpl) EncodeImage

func (e *ProgressiveEncoderImpl) EncodeImage(img image.Image) ([]byte, error)

EncodeImage encodes Go's image.Image to progressive JPEG bytes.

func (*ProgressiveEncoderImpl) Format

func (e *ProgressiveEncoderImpl) Format() Format

Format returns the target encoding format.

func (*ProgressiveEncoderImpl) SetQuality

func (e *ProgressiveEncoderImpl) SetQuality(quality int) error

SetQuality sets encoding quality (0-100).

func (*ProgressiveEncoderImpl) SetScanScript

func (e *ProgressiveEncoderImpl) SetScanScript(script *ScanScript)

SetScanScript sets a custom scan script for progressive encoding.

type ProgressiveScanAnalyzer

type ProgressiveScanAnalyzer struct{}

ProgressiveScanAnalyzer analyzes SOS markers to extract scan progression patterns that can indicate specific encoder implementations.

func NewProgressiveScanAnalyzer

func NewProgressiveScanAnalyzer() *ProgressiveScanAnalyzer

NewProgressiveScanAnalyzer creates a new progressive scan analyzer.

func (*ProgressiveScanAnalyzer) AnalyzeScanPatterns

func (a *ProgressiveScanAnalyzer) AnalyzeScanPatterns(sosSegments []*SOSSegment) *ProgressiveScanResult

AnalyzeScanPatterns analyzes SOS segments to identify scan progression patterns.

Parameters:

  • sosSegments: Slice of SOSSegment structures from parsed SOS markers

Returns:

  • *ProgressiveScanResult: Analysis result with patterns and encoder hints

type ProgressiveScanResult

type ProgressiveScanResult struct {
	// ScanCount is the total number of scans
	ScanCount int

	// Patterns contains the detected scan patterns
	Patterns []ScanPattern

	// Strategy describes the overall progressive encoding strategy
	Strategy string

	// EncoderHints contains encoder-specific hints based on scan patterns
	EncoderHints []string

	// Confidence is the confidence in pattern identification
	Confidence float64
}

ProgressiveScanResult represents the result of progressive scan analysis.

type ProvenanceChecker

type ProvenanceChecker interface {
	// GetProvenance extracts the provenance chain from image data.
	GetProvenance(data []byte) ([]ProvenanceRecord, error)

	// HasProvenance checks if provenance data exists.
	HasProvenance(data []byte) bool
}

ProvenanceChecker extracts provenance information. Implements ISP for provenance chain extraction. Used by JPEG Trust for anti-deepfake verification.

type ProvenanceRecord

type ProvenanceRecord struct {
	Action      string // Action performed (created, edited, exported)
	Actor       string // Who performed the action
	Timestamp   int64  // Unix timestamp of the action
	Software    string // Software used
	Description string // Human-readable description
}

ProvenanceRecord represents a provenance entry.

type QCDMarker

type QCDMarker struct {
	QuantizationStyle byte      // Quantization style
	GuardBits         int       // Guard bits
	StepSizes         []float64 // Quantization step sizes
}

QCDMarker represents JPEG 2000 Quantization Default marker.

type QualityConfidenceBreakdown

type QualityConfidenceBreakdown struct {
	// TableMatch indicates confidence from quantization table matching (0.0-1.0).
	// Higher values indicate closer match to known encoder tables.
	TableMatch float64 `json:"table_match"`

	// AlgorithmAgreement indicates confidence from algorithm agreement (0.0-1.0).
	// Higher values indicate that multiple estimation algorithms agree.
	AlgorithmAgreement float64 `json:"algorithm_agreement"`

	// EncoderDetection indicates confidence in encoder identification (0.0-1.0).
	// Higher values indicate more certain encoder identification.
	EncoderDetection float64 `json:"encoder_detection"`
}

QualityConfidenceBreakdown provides detailed breakdown of confidence factors for quality estimation. This is separate from the ConfidenceBreakdown type used for encoder signature detection.

type QualityConfidenceCalculator

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

QualityConfidenceCalculator implements a multi-factor confidence model for JPEG quality estimation. It provides more nuanced reliability scores by considering multiple factors and handles edge cases gracefully.

This is distinct from ConfidenceCalculator which is used for encoder signature detection.

func NewQualityConfidenceCalculator

func NewQualityConfidenceCalculator() *QualityConfidenceCalculator

NewQualityConfidenceCalculator creates a new quality confidence calculator with default weights.

func (*QualityConfidenceCalculator) CalculateAlgorithmAgreementConfidence

func (c *QualityConfidenceCalculator) CalculateAlgorithmAgreementConfidence(results []AlgorithmResult) float64

CalculateAlgorithmAgreementConfidence calculates confidence based on agreement between different quality estimation algorithms.

Parameters:

  • results: Slice of algorithm results to compare

Returns:

  • float64: Agreement confidence (0.0-1.0)

func (*QualityConfidenceCalculator) CalculateEncoderConfidenceContribution

func (c *QualityConfidenceCalculator) CalculateEncoderConfidenceContribution(encoderConf float64, detected bool) float64

CalculateEncoderConfidenceContribution calculates how encoder detection affects overall quality estimation confidence.

Parameters:

  • encoderConf: Confidence in encoder detection (0.0-1.0)
  • detected: Whether any encoder was detected

Returns:

  • float64: Encoder contribution to confidence (0.0-1.0)

func (*QualityConfidenceCalculator) CalculateMultiFactorConfidence

func (c *QualityConfidenceCalculator) CalculateMultiFactorConfidence(
	tableMatchConf, algorithmAgree, encoderConf float64,
	encoderDetected bool,
) float64

CalculateMultiFactorConfidence computes overall confidence using multiple factors. Each factor is weighted by its reliability, providing a more nuanced confidence score than simple RMSE-based mapping.

Parameters:

  • tableMatchConf: Confidence from quantization table RMSE matching (0.0-1.0)
  • algorithmAgree: Confidence from algorithm agreement (0.0-1.0)
  • encoderConf: Confidence from encoder detection (0.0-1.0)
  • encoderDetected: Whether an encoder was successfully detected

Returns:

  • float64: Combined confidence score (0.0-1.0)

func (*QualityConfidenceCalculator) CalculateTableMatchConfidence

func (c *QualityConfidenceCalculator) CalculateTableMatchConfidence(rmse float64, isStandard bool) float64

CalculateTableMatchConfidence calculates confidence based on quantization table RMSE and whether the table matches a standard pattern.

Parameters:

  • rmse: Root mean square error between observed and reference tables
  • isStandard: Whether the table matches a known standard pattern

Returns:

  • float64: Confidence score (0.0-1.0)

func (*QualityConfidenceCalculator) Handle16BitPrecision

func (c *QualityConfidenceCalculator) Handle16BitPrecision(table [64]int, precision int) [64]int

Handle16BitPrecision normalizes 16-bit precision quantization tables to standard 8-bit range for analysis.

Parameters:

  • table: Quantization table (may have 16-bit values)
  • precision: Bit precision (8 or 16)

Returns:

  • [64]int: Normalized table with values in [1, 255] range

func (*QualityConfidenceCalculator) HandleAllMaxTable

func (c *QualityConfidenceCalculator) HandleAllMaxTable(table [64]int) (quality int, confidence float64)

HandleAllMaxTable detects and handles quality 1 tables where all coefficients are 255 (maximum quantization = minimum quality).

Parameters:

  • table: Quantization table to analyze

Returns:

  • quality: 1 if Q1 pattern detected, 0 otherwise
  • confidence: Confidence in detection (0.0-1.0)

func (*QualityConfidenceCalculator) HandleAllOnesTable

func (c *QualityConfidenceCalculator) HandleAllOnesTable(table [64]int) (quality int, confidence float64)

HandleAllOnesTable detects and handles quality 100 tables where all coefficients are 1 (minimum quantization = maximum quality).

Parameters:

  • table: Quantization table to analyze

Returns:

  • quality: 100 if Q100 pattern detected, 0 otherwise
  • confidence: Confidence in detection (0.0-1.0)

func (*QualityConfidenceCalculator) HandleProgressivePartialData

func (c *QualityConfidenceCalculator) HandleProgressivePartialData(data []byte) (*QualityEstimate, error)

HandleProgressivePartialData provides quality estimation for progressive JPEGs where not all scan data may be available.

Parameters:

  • data: Raw JPEG file bytes

Returns:

  • *QualityEstimate: Quality estimate with reduced confidence for partial data
  • error: If estimation fails completely

func (*QualityConfidenceCalculator) IsCustomTable

func (c *QualityConfidenceCalculator) IsCustomTable(table [64]int) bool

IsCustomTable determines if a quantization table is custom (not matching any standard encoder pattern).

Parameters:

  • table: Quantization table to analyze

Returns:

  • bool: True if the table doesn't match any known standard pattern

func (*QualityConfidenceCalculator) IsProgressiveJPEG

func (c *QualityConfidenceCalculator) IsProgressiveJPEG(data []byte) bool

IsProgressiveJPEG checks if the given data is a progressive JPEG (SOF2).

Parameters:

  • data: Raw JPEG file bytes

Returns:

  • bool: True if progressive JPEG

func (*QualityConfidenceCalculator) PopulateQualityConfidenceBreakdown

func (c *QualityConfidenceCalculator) PopulateQualityConfidenceBreakdown(
	estimate *QualityEstimate,
	rmse float64,
	isStandard bool,
	algorithmResults []AlgorithmResult,
	encoderConf float64,
	encoderDetected bool,
)

PopulateQualityConfidenceBreakdown fills in the ConfidenceBreakdown struct on a QualityEstimate with individual factor scores.

Parameters:

  • estimate: The QualityEstimate to update
  • rmse: RMSE from table matching
  • isStandard: Whether the table is standard
  • algorithmResults: Results from different estimation algorithms
  • encoderConf: Encoder detection confidence
  • encoderDetected: Whether encoder was detected

type QualityCurve

type QualityCurve func(quality int) [64]int

QualityCurve is a function type that generates a quantization table for a given quality level (1-100 for libjpeg-compatible encoders, or encoder-specific ranges like 1-12 for Photoshop).

type QualityEstimate

type QualityEstimate struct {
	// Quality is the estimated libjpeg-equivalent quality setting (1-100).
	// A value of 100 represents minimal compression (highest quality),
	// while 1 represents maximum compression (lowest quality).
	// Quality 50 corresponds to the unscaled ITU-T T.81 standard tables.
	Quality int `json:"quality"`

	// Confidence indicates the reliability of the quality estimate (0.0-1.0).
	// A value of 1.0 indicates an exact match with standard IJG tables,
	// while lower values indicate deviation from standard encoding patterns.
	// Confidence below 0.5 suggests non-standard or custom quantization tables.
	Confidence float64 `json:"confidence"`

	// Method describes the algorithm used for quality estimation.
	// Possible values include:
	//   - "least-squares": Primary method using sum of squared errors
	//   - "scale-matching": Secondary method using scale factor analysis
	//   - "combined": Both methods agree on the quality estimate
	Method string `json:"method"`

	// EncoderHint provides a hint about the encoder that produced the JPEG.
	// Possible values include:
	//   - "libjpeg": Standard Independent JPEG Group encoder
	//   - "photoshop": Adobe Photoshop (uses different quality scale)
	//   - "unknown": No recognizable encoder pattern detected
	// Note: This is a best-effort hint, not a definitive identification.
	EncoderHint string `json:"encoder_hint"`

	// LuminanceQuality is the estimated quality for the luminance (Y) table.
	// This may differ from the overall Quality if separate tables were used.
	LuminanceQuality int `json:"luminance_quality"`

	// ChrominanceQuality is the estimated quality for the chrominance (Cb/Cr) table.
	// This may differ from LuminanceQuality if the encoder applied different
	// compression to color channels (common optimization for human perception).
	ChrominanceQuality int `json:"chrominance_quality"`

	// IsStandardTable indicates whether the observed quantization table
	// exactly matches a standard IJG table at some quality level.
	// True means the table was generated using the standard IJG scaling formula.
	IsStandardTable bool `json:"is_standard_table"`

	// SSE is the Sum of Squared Errors between the observed table and
	// the best-matching reference table. A value of 0 indicates an exact match.
	// This metric is useful for assessing how closely the table matches standards.
	SSE float64 `json:"sse"`

	// RMSE is the Root Mean Square Error, calculated as sqrt(SSE/64).
	// This provides a per-coefficient error metric that is easier to interpret.
	// An RMSE of 0 indicates a perfect match with standard tables.
	RMSE float64 `json:"rmse"`

	// DCTAnalysisScore is the result of DCT coefficient distribution analysis (0.0-1.0).
	// Higher values indicate the DCT coefficients match expected patterns for the
	// estimated quality level. This provides independent validation of the quality estimate.
	DCTAnalysisScore float64 `json:"dct_analysis_score"`

	// ChromaSubsampling indicates the detected chroma subsampling mode.
	// 4:4:4 typically indicates higher quality intent, while 4:2:0 is standard/lower quality.
	ChromaSubsampling ChromaSubsamplingMode `json:"chroma_subsampling"`

	// EncoderConfidence indicates confidence in encoder identification (0.0-1.0).
	// This is separate from the overall Confidence which reflects quality estimate reliability.
	// Higher values indicate more certain encoder identification.
	EncoderConfidence float64 `json:"encoder_confidence"`

	// EstimationMethods lists which algorithms contributed to the quality estimate.
	// Multiple methods may be used for cross-validation.
	EstimationMethods []EstimationMethod `json:"estimation_methods,omitempty"`

	// ReEncodingLikelihood indicates the likelihood that the image has been re-encoded (0.0-1.0).
	// Values above 0.5 suggest the image may have been compressed multiple times.
	// This is detected through double quantization patterns and quality mismatches.
	ReEncodingLikelihood float64 `json:"re_encoding_likelihood"`

	// ConfidenceBreakdown provides detailed breakdown of confidence factors.
	// This shows how much each factor contributed to the overall confidence score.
	ConfidenceBreakdown QualityConfidenceBreakdown `json:"confidence_breakdown"`

	// DetectedEncoder indicates the encoder family that produced the JPEG.
	// This is more structured than EncoderHint and uses the EncoderFamily type.
	DetectedEncoder EncoderFamily `json:"detected_encoder"`
}

QualityEstimate represents the result of analyzing JPEG quantization tables to estimate the original compression quality setting.

func (*QualityEstimate) IsHighConfidence

func (q *QualityEstimate) IsHighConfidence() bool

IsHighConfidence returns true if the confidence score is above 0.8. This indicates a high-confidence quality estimate that can be trusted.

func (*QualityEstimate) IsReEncoded

func (q *QualityEstimate) IsReEncoded() bool

IsReEncoded returns true if the re-encoding likelihood exceeds the threshold (0.5). This provides a simple boolean answer to whether the image appears to have been re-encoded, based on the ReEncodingLikelihood score.

func (*QualityEstimate) PrimaryMethod

func (q *QualityEstimate) PrimaryMethod() EstimationMethod

PrimaryMethod returns the primary estimation method used. If multiple methods were used, returns the first one. If no methods are recorded, returns EstimationMethodLeastSquares as the default.

type QualityEstimator

type QualityEstimator interface {
	// EstimateQuality analyzes raw JPEG file bytes to estimate compression quality.
	// It parses DQT markers from the JPEG structure and delegates to the core
	// estimation algorithm.
	//
	// Returns:
	//   - *QualityEstimate: Comprehensive quality analysis including confidence
	//   - error: If data is not valid JPEG or lacks DQT markers
	//
	// Errors returned for:
	//   - Non-JPEG data (missing SOI marker 0xFFD8)
	//   - JPEG without DQT markers
	//   - Lossless JPEG (SOF3) where quality estimation is not applicable
	EstimateQuality(data []byte) (*QualityEstimate, error)

	// EstimateQualityFromTables estimates quality from pre-parsed quantization tables.
	// This is useful when JPEG data has already been partially parsed, such as
	// when integrating with HuffmanDecoder.GetQuantizationTables().
	//
	// Parameters:
	//   - tables: Map of quantization tables indexed by table ID (0-3)
	//     - ID 0: Typically luminance (Y) table
	//     - ID 1: Typically chrominance (Cb/Cr) table
	//
	// Returns:
	//   - *QualityEstimate: Comprehensive quality analysis
	//   - error: If tables map is empty or contains invalid data
	EstimateQualityFromTables(tables map[int][64]int) (*QualityEstimate, error)
}

QualityEstimator estimates JPEG compression quality from quantization tables. Implements ISP with focused methods for quality estimation.

This interface provides two entry points:

  • EstimateQuality: For raw JPEG file bytes (parses DQT markers)
  • EstimateQualityFromTables: For pre-parsed quantization tables

The estimation uses least-squares matching against standard IJG tables and scale factor reverse engineering for validation.

func NewQualityEstimator

func NewQualityEstimator(validator SecurityValidator) QualityEstimator

NewQualityEstimator creates a new QualityEstimator instance. The validator parameter is optional; if nil, no validation is performed.

Usage:

estimator := NewQualityEstimator(nil)
estimate, err := estimator.EstimateQuality(jpegData)

type QuantTableInfo

type QuantTableInfo struct {
	// NaturalOrder contains the quantization values in row-major order (8x8 matrix).
	// This is the format used for quality estimation and table matching.
	NaturalOrder [64]int

	// ZigzagOrder contains the quantization values in zigzag scan order.
	// This is the format stored in the JPEG file and used during encoding/decoding.
	ZigzagOrder [64]int

	// Precision indicates the quantization value precision:
	// 0 = 8-bit values (0-255)
	// 1 = 16-bit values (0-65535)
	Precision int
}

QuantTableInfo contains a quantization table with both natural and zigzag order representations for maximum flexibility in analysis.

type QuantizationSignature

type QuantizationSignature struct {
	// Family is the encoder family this signature represents.
	Family EncoderFamily

	// TableHash is a precomputed hash of the characteristic table.
	// Used for fast exact-match comparison.
	TableHash uint64

	// CharacteristicCoeffs are specific coefficient positions and their
	// expected ratio to the DC coefficient. This allows pattern matching
	// without requiring exact table matches.
	// Format: [position, expectedRatio]
	CharacteristicCoeffs []CoefficientRatio

	// DCRange specifies the expected range of DC coefficient values
	// for this encoder at various quality levels.
	DCRange [2]int // [min, max]

	// RatioTolerance is the acceptable deviation in coefficient ratios.
	RatioTolerance float64
}

QuantizationSignature represents a camera manufacturer's quantization table signature used for encoder detection.

type Quantizer

type Quantizer interface {
	// Quantize quantizes DCT coefficients using the quantization table.
	Quantize(block *[BlockSize2]float64) *[BlockSize2]int

	// Dequantize dequantizes coefficients back to DCT domain.
	Dequantize(block *[BlockSize2]int) *[BlockSize2]float64

	// Table returns the quantization table.
	Table() *[BlockSize2]int
}

Quantizer performs quantization and dequantization of DCT coefficients.

func NewChrominanceQuantizer

func NewChrominanceQuantizer(quality int) Quantizer

NewChrominanceQuantizer creates a quantizer with the standard chrominance table.

func NewLuminanceQuantizer

func NewLuminanceQuantizer(quality int) Quantizer

NewLuminanceQuantizer creates a quantizer with the standard luminance table.

func NewQuantizer

func NewQuantizer(table [BlockSize2]int) Quantizer

NewQuantizer creates a new quantizer with the given table.

type RawAPPMarker

type RawAPPMarker struct {
	// Type is the APP marker type (0-15 for APP0-APP15).
	Type int

	// Identifier is the null-terminated identifier string at the start.
	Identifier string

	// Data is the raw marker data after the identifier.
	Data []byte
}

RawAPPMarker represents a raw APP marker segment.

type SIZMarker

type SIZMarker struct {
	Capabilities   uint16 // Profile capabilities
	Width          int    // Image width
	Height         int    // Image height
	XOffset        int    // Horizontal offset from origin
	YOffset        int    // Vertical offset from origin
	TileWidth      int    // Tile width
	TileHeight     int    // Tile height
	TileXOffset    int    // Tile horizontal offset
	TileYOffset    int    // Tile vertical offset
	ComponentCount int    // Number of components
	ComponentSpecs []ComponentSpec
}

SIZMarker represents JPEG 2000 Image and Tile Size marker.

type SOFComponent

type SOFComponent struct {
	ID                 int // Component identifier
	HorizontalSampling int // Horizontal sampling factor
	VerticalSampling   int // Vertical sampling factor
	QuantTableID       int // Quantization table destination
}

SOFComponent represents a component in the SOF segment.

type SOFSegment

type SOFSegment struct {
	Precision      int            // Sample precision in bits
	Height         int            // Image height in pixels
	Width          int            // Image width in pixels
	ComponentCount int            // Number of image components
	Components     []SOFComponent // Component specifications
}

SOFSegment represents Start of Frame marker data.

type SOFType

type SOFType int

SOFType represents the JPEG Start of Frame marker type.

const (
	// SOFBaseline represents SOF0 - Baseline DCT (most common JPEG format)
	SOFBaseline SOFType = iota
	// SOFExtended represents SOF1 - Extended sequential DCT (12-bit support)
	SOFExtended
	// SOFProgressive represents SOF2 - Progressive DCT
	SOFProgressive
	// SOFLossless represents SOF3 - Lossless (sequential)
	SOFLossless
	// SOFDifferentialSequential represents SOF5 - Differential sequential DCT
	SOFDifferentialSequential
	// SOFDifferentialProgressive represents SOF6 - Differential progressive DCT
	SOFDifferentialProgressive
	// SOFDifferentialLossless represents SOF7 - Differential lossless
	SOFDifferentialLossless
	// SOFArithmeticSequential represents SOF9 - Extended sequential DCT with arithmetic coding
	SOFArithmeticSequential
	// SOFArithmeticProgressive represents SOF10 - Progressive DCT with arithmetic coding
	SOFArithmeticProgressive
	// SOFArithmeticLossless represents SOF11 - Lossless with arithmetic coding
	SOFArithmeticLossless
	// SOFArithmeticDiffSequential represents SOF13 - Differential sequential with arithmetic
	SOFArithmeticDiffSequential
	// SOFArithmeticDiffProgressive represents SOF14 - Differential progressive with arithmetic
	SOFArithmeticDiffProgressive
	// SOFArithmeticDiffLossless represents SOF15 - Differential lossless with arithmetic
	SOFArithmeticDiffLossless
	// SOFJPEGLS represents SOF55 - JPEG-LS (different algorithm)
	SOFJPEGLS
)

func (SOFType) String

func (s SOFType) String() string

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

type SOFVariantHandler

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

SOFVariantHandler handles different JPEG SOF variants for encoder detection.

func NewSOFVariantHandler

func NewSOFVariantHandler() *SOFVariantHandler

NewSOFVariantHandler creates a new SOF variant handler.

func (*SOFVariantHandler) AnalyzeVariant

func (h *SOFVariantHandler) AnalyzeVariant(
	sofType SOFType,
	precision int,
	dhtSegments []*DHTSegment,
	sosSegments []*SOSSegment,
) *VariantInfo

AnalyzeVariant analyzes a JPEG variant and returns variant-specific information.

Parameters:

  • sofType: The SOF marker type
  • precision: Sample precision in bits
  • dhtSegments: DHT segments for Huffman analysis (optional)
  • sosSegments: SOS segments for progressive analysis (optional)

Returns:

  • *VariantInfo: Comprehensive variant information

type SOSComponent

type SOSComponent struct {
	ComponentSelector int // Component selector (Cs)
	DCTableSelector   int // DC entropy table selector
	ACTableSelector   int // AC entropy table selector
}

SOSComponent represents a component in the SOS segment.

type SOSSegment

type SOSSegment struct {
	ComponentCount int            // Number of components in scan
	Components     []SOSComponent // Component specifications
	SpectralStart  int            // Start of spectral selection
	SpectralEnd    int            // End of spectral selection
	SuccessiveHigh int            // Successive approximation bit position high
	SuccessiveLow  int            // Successive approximation bit position low
}

SOSSegment represents Start of Scan marker data.

type SOTMarker

type SOTMarker struct {
	TileIndex      int   // Tile index
	TilePartLength int64 // Tile-part length
	TilePartIndex  int   // Tile-part index
	TilePartCount  int   // Number of tile-parts
}

SOTMarker represents JPEG 2000 Start of Tile-part marker.

type SafeMath

type SafeMath interface {
	// SafeMultiply performs overflow-safe multiplication.
	// Returns the result and true if overflow occurred.
	SafeMultiply(a, b int) (int, bool)

	// SafeAdd performs overflow-safe addition.
	// Returns the result and true if overflow occurred.
	SafeAdd(a, b int) (int, bool)

	// SafeSubtract performs overflow-safe subtraction.
	// Returns the result and true if overflow occurred.
	SafeSubtract(a, b int) (int, bool)
}

SafeMath provides overflow-safe arithmetic operations.

type ScanComponent

type ScanComponent struct {
	// ComponentID references a component defined in the SOF marker.
	// Must match an EncoderComponentSpec.ID from the frame header.
	ComponentID int

	// DCTableID is the DC Huffman table selector (0-3).
	// Points to a table defined by a DHT marker with Class=0.
	DCTableID int

	// ACTableID is the AC Huffman table selector (0-3).
	// Points to a table defined by a DHT marker with Class=1.
	ACTableID int
}

ScanComponent defines a component's parameters for the SOS (Start of Scan) marker.

The SOS marker specifies which components are included in a scan and which Huffman tables to use for each component's DC and AC coefficients.

func Get420ScanComponents

func Get420ScanComponents() []ScanComponent

Get420ScanComponents returns SOS scan components matching Get420ComponentSpecs.

func Get422ScanComponents

func Get422ScanComponents() []ScanComponent

Get422ScanComponents returns SOS scan components matching Get422ComponentSpecs.

func Get444ScanComponents

func Get444ScanComponents() []ScanComponent

Get444ScanComponents returns SOS scan components matching Get444ComponentSpecs.

func GetGrayscaleScanComponents

func GetGrayscaleScanComponents() []ScanComponent

GetGrayscaleScanComponents returns SOS scan components matching GetGrayscaleComponentSpecs (single luminance component).

type ScanPattern

type ScanPattern struct {
	// ComponentCount is the number of components in this scan
	ComponentCount int

	// SpectralStart is the start of spectral selection (Ss)
	SpectralStart int

	// SpectralEnd is the end of spectral selection (Se)
	SpectralEnd int

	// SuccessiveHigh is the successive approximation bit high (Ah)
	SuccessiveHigh int

	// SuccessiveLow is the successive approximation bit low (Al)
	SuccessiveLow int
}

ScanPattern represents a progressive JPEG scan pattern.

type ScanScript

type ScanScript struct {
	Scans []ScanSpec
}

ScanScript defines the sequence of scans for progressive encoding.

func DefaultScanScript

func DefaultScanScript(numComponents int) *ScanScript

DefaultScanScript returns a standard progressive scan script. This provides a good balance between file size and progressive display.

func SimpleScanScript

func SimpleScanScript(numComponents int) *ScanScript

SimpleScanScript returns a minimal progressive scan script. This produces fewer scans but less gradual progression.

type ScanSpec

type ScanSpec struct {
	// Components to include in this scan (component IDs)
	Components []int

	// SpectralStart is the first DCT coefficient index (Ss, 0-63)
	SpectralStart int

	// SpectralEnd is the last DCT coefficient index (Se, 0-63)
	SpectralEnd int

	// SuccApproxHigh is the successive approximation bit position high (Ah)
	// 0 for first scan of these coefficients, >0 for refinement
	SuccApproxHigh int

	// SuccApproxLow is the successive approximation bit position low (Al)
	SuccApproxLow int
}

ScanSpec defines the parameters for a single progressive scan.

type SecurityError

type SecurityError struct {
	ViolationType SecurityViolationType
	Details       string
	Cause         error
}

SecurityError represents a security violation during parsing.

func NewSecurityError

func NewSecurityError(violationType SecurityViolationType, cause error) *SecurityError

NewSecurityError creates a new security error.

func (*SecurityError) Error

func (e *SecurityError) Error() string

func (*SecurityError) Unwrap

func (e *SecurityError) Unwrap() error

type SecurityValidator

type SecurityValidator interface {
	// ValidateImageSize validates image dimensions against limits.
	ValidateImageSize(width, height int) error

	// ValidateComponentCount validates the number of image components.
	ValidateComponentCount(count int) error

	// ValidateSegmentLength validates marker segment length.
	ValidateSegmentLength(length int) error

	// ValidateAllocation checks if a memory allocation is safe.
	ValidateAllocation(size uint64) error

	// CheckIteration guards against infinite loops.
	CheckIteration() error

	// Reset resets all validator state.
	Reset()
}

SecurityValidator validates parsing parameters to prevent attacks. Implements ISP with focused validation methods.

func NewSecurityValidator

func NewSecurityValidator() SecurityValidator

NewSecurityValidator returns a new SecurityValidator with default limits.

func NewThreadSafeValidator

func NewThreadSafeValidator(v SecurityValidator) SecurityValidator

NewThreadSafeValidator wraps a validator for thread-safe access.

type SecurityViolationType

type SecurityViolationType int

SecurityViolationType categorizes security violations.

const (
	// ViolationIntegerOverflow indicates integer overflow detected.
	ViolationIntegerOverflow SecurityViolationType = iota
	// ViolationBufferOverflow indicates buffer overflow attempt.
	ViolationBufferOverflow
	// ViolationResourceExhaustion indicates resource exhaustion attack.
	ViolationResourceExhaustion
	// ViolationInvalidMarker indicates malformed marker.
	ViolationInvalidMarker
	// ViolationMalformedData indicates malformed data structure.
	ViolationMalformedData
	// ViolationInfiniteLoop indicates potential infinite loop.
	ViolationInfiniteLoop
	// MemoryExhaustion indicates memory limit exceeded.
	MemoryExhaustion
	// InfiniteLoop indicates iteration limit exceeded.
	InfiniteLoop
)

func (SecurityViolationType) String

func (t SecurityViolationType) String() string

String returns a human-readable description of the violation type.

type SegmentParser

type SegmentParser interface {
	// ParseSOF parses Start of Frame segment data.
	ParseSOF(data []byte) (*SOFSegment, error)

	// ParseDHT parses Define Huffman Table segment data.
	ParseDHT(data []byte) (*DHTSegment, error)

	// ParseDQT parses Define Quantization Table segment data.
	ParseDQT(data []byte) (*DQTSegment, error)

	// ParseSOS parses Start of Scan segment data.
	ParseSOS(data []byte) (*SOSSegment, error)

	// ParseAPP parses Application marker segment data.
	ParseAPP(appType int, data []byte) (*APPSegment, error)
}

SegmentParser parses JPEG segment data. Implements ISP with methods for each segment type.

func DefaultSegmentParser

func DefaultSegmentParser() SegmentParser

DefaultSegmentParser returns the default SegmentParser implementation.

func NewSegmentParser

func NewSegmentParser(validator SecurityValidator) SegmentParser

NewSegmentParser creates a new SegmentParser with optional security validator. If validator is nil, uses the default security validator.

type Signature

type Signature struct {
	// Comments contains all COM marker text strings found in the JPEG.
	// Multiple COM markers result in multiple entries in this slice.
	Comments []string

	// APPMarkers contains raw APP0-APP15 marker data indexed by marker type (0-15).
	// The map key corresponds to the APP marker number (0 for APP0, 15 for APP15).
	// The value is the raw marker data after the length field.
	APPMarkers map[int][]byte

	// QuantTables contains quantization tables indexed by table ID (0-3).
	// Each table includes both natural order and zigzag order representations.
	QuantTables map[int]QuantTableInfo

	// HuffmanTables contains all Huffman table definitions with metadata.
	// DC tables have Class=0, AC tables have Class=1.
	HuffmanTables []HuffmanTableInfo

	// SOFInfo contains Start of Frame information including dimensions,
	// precision, and component specifications. May be nil if no SOF found.
	SOFInfo *SignatureSOFInfo

	// EncoderHints contains encoder identification hints derived from APP markers.
	// This reuses the existing APPMarkerHints struct for compatibility.
	// May be nil if APP marker analysis was not performed.
	EncoderHints *APPMarkerHints
}

Signature contains all extractable metadata from a JPEG file. This comprehensive structure enables forensic analysis and encoder identification without requiring multiple parsing passes.

func ExtractSignature

func ExtractSignature(data []byte) (*Signature, error)

ExtractSignature extracts comprehensive metadata from raw JPEG data. This is the primary entry point for JPEG signature extraction.

The function performs a single pass through the JPEG data, extracting: - DQT markers (quantization tables) - DHT markers (Huffman tables) - SOF markers (frame information) - APP0-APP15 markers (application data) - COM markers (comments)

Parameters:

  • data: Raw JPEG file bytes starting with SOI marker (0xFFD8)

Returns:

  • *Signature: Comprehensive metadata structure
  • error: If data is not a valid JPEG

Example:

data, _ := os.ReadFile("image.jpg")
sig, err := jpeg.ExtractSignature(data)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Image: %dx%d, %d comments\n",
    sig.SOFInfo.Width, sig.SOFInfo.Height, len(sig.Comments))

type SignatureComponentInfo

type SignatureComponentInfo struct {
	// ID is the component identifier.
	ID int

	// HSampling is the horizontal sampling factor.
	HSampling int

	// VSampling is the vertical sampling factor.
	VSampling int

	// QuantTableID is the quantization table destination for this component.
	QuantTableID int
}

SignatureComponentInfo contains component information for signature analysis.

type SignatureDatabase

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

SignatureDatabase stores quantization table signatures for encoder detection. It pre-computes and caches reference tables for all qualities 1-100 and supports signature lookup by exact table match or computed hash.

func NewSignatureDatabase

func NewSignatureDatabase() *SignatureDatabase

NewSignatureDatabase creates a new SignatureDatabase instance with pre-computed reference tables for all quality levels 1-100.

The database stores ITU-T T.81 Annex K standard luminance and chrominance tables (quality 50 baseline) and scales them using the IJG formula for all other quality levels.

Usage:

db := NewSignatureDatabase()
result := db.LookupByTable(quantTable)

func (*SignatureDatabase) FindClosestMatch

func (db *SignatureDatabase) FindClosestMatch(table [64]int) (quality int, tableType TableType, sse int64, isExact bool)

FindClosestMatch finds the quality level with the smallest SSE for a given table. This is useful for approximate matching of non-standard tables.

Parameters:

  • table: A 64-element quantization table in row-major order

Returns:

  • quality: The quality level with minimum SSE
  • tableType: Whether the closest match is luminance or chrominance
  • sse: The minimum SSE found
  • isExact: Whether the match is exact (SSE = 0)

func (*SignatureDatabase) GetChrominanceTable

func (db *SignatureDatabase) GetChrominanceTable(quality int) *[64]int

GetChrominanceTable returns the reference chrominance table for the specified quality. Quality must be in range 1-100. Returns nil for invalid quality values.

func (*SignatureDatabase) GetLuminanceTable

func (db *SignatureDatabase) GetLuminanceTable(quality int) *[64]int

GetLuminanceTable returns the reference luminance table for the specified quality. Quality must be in range 1-100. Returns nil for invalid quality values.

func (*SignatureDatabase) GetStandardChrominanceTable

func (db *SignatureDatabase) GetStandardChrominanceTable() [64]int

GetStandardChrominanceTable returns the ITU-T T.81 Annex K standard chrominance quantization table (quality 50 baseline).

func (*SignatureDatabase) GetStandardLuminanceTable

func (db *SignatureDatabase) GetStandardLuminanceTable() [64]int

GetStandardLuminanceTable returns the ITU-T T.81 Annex K standard luminance quantization table (quality 50 baseline).

func (*SignatureDatabase) LookupByHash

func (db *SignatureDatabase) LookupByHash(hash string) *HashLookupResult

LookupByHash looks up a table signature by its pre-computed SHA-256 hash. The hash must have been previously registered using RegisterTableHash.

Parameters:

  • hash: A hex-encoded SHA-256 hash string (64 characters)

Returns:

  • *HashLookupResult: Registered signature if found, or nil if unknown

func (*SignatureDatabase) LookupByTable

func (db *SignatureDatabase) LookupByTable(table [64]int) *TableLookupResult

LookupByTable looks up a quantization table by exact coefficient matching. It compares the table against all pre-computed reference tables for both luminance and chrominance at all quality levels 1-100.

Parameters:

  • table: A 64-element quantization table in row-major order

Returns:

  • *TableLookupResult: Match result if found, or nil if no match

The function first checks for exact matches with luminance tables, then chrominance tables. If no exact match is found, it returns nil.

func (*SignatureDatabase) RegisterTableHash

func (db *SignatureDatabase) RegisterTableHash(hash string, encoderFamily string, quality int, tableType TableType)

RegisterTableHash registers a table hash with associated encoder information. This allows fast lookup of known encoder signatures by hash.

Parameters:

  • hash: A hex-encoded SHA-256 hash string (64 characters)
  • encoderFamily: The encoder family for this signature
  • quality: The quality level associated with this table
  • tableType: The type of table (luminance or chrominance)

type SignatureSOFInfo

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

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

	// Precision is the sample precision in bits (typically 8 or 12).
	Precision int

	// Components contains the component specifications (Y, Cb, Cr for color images).
	Components []SignatureComponentInfo
}

SignatureSOFInfo contains Start of Frame information for signature analysis. This is separate from SOFSegment to provide a cleaner API for external consumers.

type SimpleDecoder

type SimpleDecoder interface {
	// DecodeImage decodes the image and returns the pixel data as an image.Image.
	// The returned image type depends on the source format and channel count:
	//   - Grayscale: *image.Gray or *image.Gray16
	//   - Color: *image.RGBA
	//
	// Returns an error if the image data is corrupted or the format is unsupported.
	DecodeImage() (image.Image, error)

	// GetImageInfo returns metadata about the image without fully decoding it.
	// This is a fast operation that only parses the image header.
	// Returns an ImageInfo with Format set to FormatUnknown if parsing fails.
	GetImageInfo() *ImageInfo
}

SimpleDecoder is the interface for the simple JPEG decoder. It can decode any supported JPEG format using a streaming reader interface.

SimpleDecoder provides a two-phase decode approach: first get image info using GetImageInfo to check dimensions and format, then decode the full image using DecodeImage. This is useful when you need to make decisions based on image properties before committing to the full decode.

func NewSimpleDecoder

func NewSimpleDecoder(r io.Reader) (dec SimpleDecoder, err error)

NewSimpleDecoder creates a new simple decoder for the given JPEG data. The decoder automatically detects the format and uses the appropriate decoding strategy.

Use SimpleDecoder when you want to:

  • Check image properties before decoding (via GetImageInfo)
  • Reuse the decoder for multiple operations
  • Have more control over the decode process

For simple one-shot decoding, use Decode instead.

Example:

dec, err := jpeg.NewSimpleDecoder(reader)
if err != nil {
    log.Fatal(err)
}
info := dec.GetImageInfo()
fmt.Printf("Image is %dx%d\n", info.Width, info.Height)
img, err := dec.DecodeImage()
Example

ExampleNewSimpleDecoder demonstrates using the SimpleDecoder interface. This provides more control over the decode process with a two-phase approach.

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/0verkilll/jpeg"
)

// createExampleJPEG creates a minimal valid baseline JPEG for examples.
// This returns a 1x1 grayscale JPEG image.
func createExampleJPEG() []byte {
	return []byte{

		0xFF, 0xD8,

		0xFF, 0xE0, 0x00, 0x10,
		'J', 'F', 'I', 'F', 0x00,
		0x01, 0x01,
		0x00,
		0x00, 0x01,
		0x00, 0x01,
		0x00, 0x00,

		0xFF, 0xDB, 0x00, 0x43, 0x00,

		16, 11, 10, 16, 24, 40, 51, 61,
		12, 12, 14, 19, 26, 58, 60, 55,
		14, 13, 16, 24, 40, 57, 69, 56,
		14, 17, 22, 29, 51, 87, 80, 62,
		18, 22, 37, 56, 68, 109, 103, 77,
		24, 35, 55, 64, 81, 104, 113, 92,
		49, 64, 78, 87, 103, 121, 120, 101,
		72, 92, 95, 98, 112, 100, 103, 99,

		0xFF, 0xC0, 0x00, 0x0B,
		0x08,
		0x00, 0x01,
		0x00, 0x01,
		0x01,
		0x01,
		0x11,
		0x00,

		0xFF, 0xC4, 0x00, 0x1F, 0x00,
		0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
		0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
		0x08, 0x09, 0x0A, 0x0B,

		0xFF, 0xC4, 0x00, 0xB5, 0x10,
		0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
		0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D,
		0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
		0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
		0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
		0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
		0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16,
		0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
		0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
		0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
		0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
		0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
		0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
		0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
		0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
		0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
		0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
		0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
		0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
		0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
		0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,
		0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
		0xF9, 0xFA,

		0xFF, 0xDA, 0x00, 0x08,
		0x01,
		0x01, 0x00,
		0x00, 0x3F, 0x00,

		0xFB, 0xD3, 0x28, 0xA6,

		0xFF, 0xD9,
	}
}

func main() {
	jpegData := createExampleJPEG()

	// Create a decoder
	dec, err := jpeg.NewSimpleDecoder(bytes.NewReader(jpegData))
	if err != nil {
		log.Fatal(err)
	}

	// Get info first (fast operation, only parses header)
	info := dec.GetImageInfo()
	fmt.Printf("Image dimensions: %dx%d\n", info.Width, info.Height)

	// Then decode the full image
	img, err := dec.DecodeImage()
	if err != nil {
		log.Fatal(err)
	}

	bounds := img.Bounds()
	fmt.Printf("Decoded: %dx%d\n", bounds.Dx(), bounds.Dy())
}
Output:
Image dimensions: 1x1
Decoded: 1x1

func NewSimpleDecoderForFormat

func NewSimpleDecoderForFormat(r io.Reader, format Format) (dec SimpleDecoder, err error)

NewSimpleDecoderForFormat creates a decoder for a specific format. Use this when you already know the format to skip auto-detection.

This can be slightly faster than NewSimpleDecoder since it skips format detection. It's also useful when you want to force a specific decoder for testing or special handling.

Example:

// When you know the format in advance
dec, err := jpeg.NewSimpleDecoderForFormat(reader, jpeg.FormatJPEG2000)
if err != nil {
    log.Fatal(err)
}
img, err := dec.DecodeImage()
Example

ExampleNewSimpleDecoderForFormat demonstrates creating a format-specific decoder. Use this when you already know the format to skip auto-detection.

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/0verkilll/jpeg"
)

// createExampleJPEG creates a minimal valid baseline JPEG for examples.
// This returns a 1x1 grayscale JPEG image.
func createExampleJPEG() []byte {
	return []byte{

		0xFF, 0xD8,

		0xFF, 0xE0, 0x00, 0x10,
		'J', 'F', 'I', 'F', 0x00,
		0x01, 0x01,
		0x00,
		0x00, 0x01,
		0x00, 0x01,
		0x00, 0x00,

		0xFF, 0xDB, 0x00, 0x43, 0x00,

		16, 11, 10, 16, 24, 40, 51, 61,
		12, 12, 14, 19, 26, 58, 60, 55,
		14, 13, 16, 24, 40, 57, 69, 56,
		14, 17, 22, 29, 51, 87, 80, 62,
		18, 22, 37, 56, 68, 109, 103, 77,
		24, 35, 55, 64, 81, 104, 113, 92,
		49, 64, 78, 87, 103, 121, 120, 101,
		72, 92, 95, 98, 112, 100, 103, 99,

		0xFF, 0xC0, 0x00, 0x0B,
		0x08,
		0x00, 0x01,
		0x00, 0x01,
		0x01,
		0x01,
		0x11,
		0x00,

		0xFF, 0xC4, 0x00, 0x1F, 0x00,
		0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
		0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
		0x08, 0x09, 0x0A, 0x0B,

		0xFF, 0xC4, 0x00, 0xB5, 0x10,
		0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
		0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D,
		0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
		0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
		0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
		0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
		0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16,
		0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
		0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
		0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
		0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
		0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
		0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
		0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
		0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
		0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
		0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
		0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
		0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
		0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
		0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,
		0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
		0xF9, 0xFA,

		0xFF, 0xDA, 0x00, 0x08,
		0x01,
		0x01, 0x00,
		0x00, 0x3F, 0x00,

		0xFB, 0xD3, 0x28, 0xA6,

		0xFF, 0xD9,
	}
}

func main() {
	jpegData := createExampleJPEG()

	// Create a decoder for a specific format
	dec, err := jpeg.NewSimpleDecoderForFormat(
		bytes.NewReader(jpegData),
		jpeg.FormatBaselineJPEG,
	)
	if err != nil {
		log.Fatal(err)
	}

	img, err := dec.DecodeImage()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Decoded with forced format: %dx%d\n", img.Bounds().Dx(), img.Bounds().Dy())
}
Output:
Decoded with forced format: 1x1

type StandardDecoder

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

StandardDecoder is a backward-compatible adapter for the refactored internal standard decoder. This maintains the existing public API while using the improved internal implementation.

func NewStandardDecoder

func NewStandardDecoder() *StandardDecoder

NewStandardDecoder creates a new JPEG decoder. Returns a decoder that uses the internal/standard implementation.

func (*StandardDecoder) EncodeCoefficients

func (s *StandardDecoder) EncodeCoefficients(coefficients []int) ([]byte, error)

EncodeCoefficients creates a JPEG from DCT coefficients using metadata from this decoder. This is the primary method for F5 steganography workflows where coefficients are modified.

Typical usage:

decoder := NewStandardDecoder()
coeffs, _ := decoder.ExtractCoefficients(jpegData)
// ... modify coefficients (e.g., F5 embedding) ...
stegoJPEG, _ := decoder.EncodeCoefficients(modifiedCoeffs)

func (*StandardDecoder) EncodeCoefficientsWithOptions

func (s *StandardDecoder) EncodeCoefficientsWithOptions(coefficients []int, opts *EncoderOptions) ([]byte, error)

EncodeCoefficientsWithOptions creates a JPEG from DCT coefficients with custom encoder options. This allows control over encoding behavior such as disabling the comment marker. Options are merged with defaults - you only need to specify the fields you want to change.

Example disabling comment:

stegoJPEG, _ := decoder.EncodeCoefficientsWithOptions(coeffs, &jpeg.EncoderOptions{
	DisableComment: true,
})

func (*StandardDecoder) ExtractCoefficients

func (s *StandardDecoder) ExtractCoefficients(data []byte) ([]int, error)

ExtractCoefficients extracts quantized DCT coefficients from JPEG data. This method creates a new Huffman decoder for each call and delegates to internal decoder.

func (*StandardDecoder) GetComponentCount

func (s *StandardDecoder) GetComponentCount() int

GetComponentCount returns the number of color components.

func (*StandardDecoder) GetImageDimensions

func (s *StandardDecoder) GetImageDimensions() (width, height int)

GetImageDimensions returns the width and height of the decoded image.

func (*StandardDecoder) GetMetadata

func (s *StandardDecoder) GetMetadata() *CoeffEncoderMetadata

GetMetadata returns all metadata needed for coefficient re-encoding. This is a convenience method that gathers all relevant metadata for use with EncodeCoefficients.

func (*StandardDecoder) GetQuantizationTables

func (s *StandardDecoder) GetQuantizationTables() map[int][64]int

GetQuantizationTables returns the quantization tables extracted from the JPEG. Returns a map from table ID to the 64-element quantization table.

func (*StandardDecoder) GetSamplingFactors

func (s *StandardDecoder) GetSamplingFactors() (horizontal, vertical []int)

GetSamplingFactors returns the per-component horizontal and vertical sampling factors detected from the JPEG.

func (*StandardDecoder) GetSubsampling

func (s *StandardDecoder) GetSubsampling() ChromaSubsampling

GetSubsampling returns the chroma subsampling mode detected from the JPEG.

type StreamingDecoder

type StreamingDecoder interface {
	// StartStream initializes streaming decode with format parameters.
	StartStream(width, height, bitDepth int) error

	// FeedData provides encoded data to the streaming decoder.
	FeedData(data []byte) error

	// ReadFrame reads the next complete decoded frame.
	// Returns io.EOF when no more frames are available.
	ReadFrame() ([]byte, error)

	// StopStream terminates the streaming decode session.
	StopStream() error
}

StreamingDecoder supports continuous streaming decode. Implements ISP for streaming codec operations. Used for real-time video streaming applications (SMPTE ST 2110-22).

type StreamingEncoder

type StreamingEncoder interface {
	// StartStream initializes streaming encode with format parameters.
	StartStream(w io.Writer, width, height, bitDepth int) error

	// WriteFrame encodes and writes a complete frame.
	WriteFrame(pixels []byte) error

	// StopStream terminates the streaming encode session.
	StopStream() error
}

StreamingEncoder supports continuous streaming encode. Implements ISP for streaming encoding operations. Used for real-time video encoding applications.

type TableLookupResult

type TableLookupResult struct {
	// Quality is the matched quality level (1-100) for standard tables.
	Quality int

	// TableType indicates whether this is a luminance or chrominance table.
	TableType TableType

	// IsExactMatch indicates whether the table exactly matches a reference.
	IsExactMatch bool

	// EncoderFamily is the detected encoder family for non-standard tables.
	EncoderFamily string

	// Confidence is the match confidence (0.0-1.0).
	Confidence float64
}

TableLookupResult represents the result of looking up a quantization table in the signature database.

type TableType

type TableType int

TableType identifies the type of quantization table.

const (
	// TableTypeLuminance indicates a luminance (Y) quantization table.
	TableTypeLuminance TableType = iota
	// TableTypeChrominance indicates a chrominance (Cb/Cr) quantization table.
	TableTypeChrominance
)

func (TableType) String

func (t TableType) String() string

String returns a string representation of the TableType.

type ToneMapper

type ToneMapper interface {
	// ToneMap applies tone mapping to convert HDR to SDR.
	// Input is linear HDR values, output is gamma-corrected SDR values [0,255].
	ToneMap(hdrPixels []float32, metadata *HDRMetadata) ([]uint8, error)
}

ToneMapper applies tone mapping to HDR image data. Implements ISP with a focused tone mapping method. Converts HDR pixel values to SDR for display on standard monitors.

type TransformError

type TransformError struct {
	Transform string // Transform type (e.g., "DCT", "wavelet 5/3", "wavelet 9/7")
	BlockX    int    // Block X coordinate
	BlockY    int    // Block Y coordinate
	Message   string // Error message
	Cause     error  // Underlying cause
}

TransformError represents an error during data transformation (DCT, wavelet).

func NewTransformError

func NewTransformError(transform string, blockX, blockY int, message string, cause error) *TransformError

NewTransformError creates a new TransformError.

func (*TransformError) Error

func (e *TransformError) Error() string

Error implements the error interface.

func (*TransformError) Unwrap

func (e *TransformError) Unwrap() error

Unwrap implements the errors.Unwrap interface.

type TranslatorProvider

type TranslatorProvider interface {
	// Translate looks up a translation key in the current locale.
	// If the key is not found, it tries the fallback chain.
	// Returns the key itself if not found in any locale.
	Translate(key string) string

	// TranslateWithArgs looks up a translation key and formats it with arguments.
	// Uses fmt.Sprintf formatting. If the key is not found, returns the key itself.
	TranslateWithArgs(key string, args ...interface{}) string

	// HasKey checks if a translation key exists in the current locale or fallback chain.
	HasKey(key string) bool

	// SetLocale changes the current locale for translation lookups.
	SetLocale(locale string)

	// GetLocale returns the current locale being used for translations.
	GetLocale() string
}

TranslatorProvider allows optional translation support. This interface matches github.com/0verkilll/i18n.TranslatorProvider but is defined here to avoid a hard dependency on the i18n package.

Packages using this pattern allow application developers to optionally provide translations without forcing the i18n package on all users.

Example usage:

import "github.com/0verkilll/i18n"

translator, _ := i18n.New(
    i18n.WithFileSystemLoader("locales"),
    i18n.WithDefaultLocale("en-US"),
)
jpeg.SetTranslator(translator)

Now all jpeg error messages will be translated according to the current locale setting in the translator.

func GetTranslator

func GetTranslator() TranslatorProvider

GetTranslator returns the currently configured translator, or nil if none is set.

This function is thread-safe and can be called from multiple goroutines.

type TrustDecodeMetadata

type TrustDecodeMetadata struct {
	IsAIGenerated   bool     // True if marked as AI-generated
	ProvenanceChain []string // List of provenance records
	Assertions      []string // List of assertions
	IsSigned        bool     // True if digitally signed
}

TrustDecodeMetadata contains trust/provenance metadata.

type TrustManifest

type TrustManifest struct {
	Version     string   // Manifest version
	Issuer      string   // Issuer identifier
	Assertions  []string // List of assertions made
	HashMethod  string   // Hash algorithm used
	Signature   []byte   // Digital signature (if present)
	IsAIContent bool     // True if marked as AI-generated
}

TrustManifest represents a JPEG Trust manifest.

type TrustValidator

type TrustValidator interface {
	// ValidateTrust validates the trust metadata in image data.
	// Returns the manifest and any validation errors.
	ValidateTrust(data []byte) (*TrustManifest, error)
}

TrustValidator validates JPEG Trust metadata. Implements ISP for trust validation operations. Used by JPEG Trust (ISO/IEC 21617) for content authenticity.

type UnifiedDecoder

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

UnifiedDecoder provides a single interface for decoding all JPEG family formats. It automatically detects the input format and routes to the appropriate internal decoder.

func NewUnifiedDecoder

func NewUnifiedDecoder() *UnifiedDecoder

NewUnifiedDecoder creates a new unified decoder with default options.

func NewUnifiedDecoderWithOptions

func NewUnifiedDecoderWithOptions(opts *DecoderOptions) *UnifiedDecoder

NewUnifiedDecoderWithOptions creates a new unified decoder with custom options.

func (*UnifiedDecoder) Decode

func (d *UnifiedDecoder) Decode(data []byte) (*DecodeResult, error)

Decode decodes JPEG family data and returns a unified result. The input data is automatically analyzed to determine the format, then routed to the appropriate internal decoder.

func (*UnifiedDecoder) DecodeHDR

func (d *UnifiedDecoder) DecodeHDR(data []byte) ([]float32, *HDRDecodeMetadata, error)

DecodeHDR is a convenience method for decoding HDR images. Returns HDR data as float32 values.

func (*UnifiedDecoder) DecodeLightField

func (d *UnifiedDecoder) DecodeLightField(data []byte) (map[[2]int]image.Image, *LightFieldDecodeMetadata, error)

DecodeLightField is a convenience method for decoding light field images. Returns all views as a map indexed by (u, v) coordinates.

func (*UnifiedDecoder) DecodePointCloud

func (d *UnifiedDecoder) DecodePointCloud(data []byte) (*PointCloudResult, error)

DecodePointCloud is a convenience method for decoding point cloud data.

func (*UnifiedDecoder) DecodeToImage

func (d *UnifiedDecoder) DecodeToImage(data []byte) (image.Image, error)

DecodeToImage is a convenience method that decodes to a standard image.Image. This is equivalent to calling Decode() and extracting the Image field. Returns an error if the format does not produce an image output.

func (*UnifiedDecoder) GetFormat

func (d *UnifiedDecoder) GetFormat(data []byte) (Format, error)

GetFormat returns the detected format without full decoding.

func (*UnifiedDecoder) GetOptions

func (d *UnifiedDecoder) GetOptions() *DecoderOptions

GetOptions returns the current decoder options.

func (*UnifiedDecoder) SetOptions

func (d *UnifiedDecoder) SetOptions(opts *DecoderOptions)

SetOptions updates the decoder options.

type UpsamplingMode

type UpsamplingMode int

UpsamplingMode specifies the interpolation method for chroma upsampling.

const (
	// UpsamplingNearestNeighbor uses simple duplication (faster).
	UpsamplingNearestNeighbor UpsamplingMode = iota
	// UpsamplingBilinear uses bilinear interpolation (higher quality).
	UpsamplingBilinear
)

func (UpsamplingMode) String

func (m UpsamplingMode) String() string

String returns the upsampling mode name.

type Validatable

type Validatable interface {
	// Validate checks if the receiver is in a valid state.
	// Returns nil if valid, or an error describing the validation failure.
	Validate() error
}

Validatable represents types that can validate their state. Implements ISP with a single focused validation method.

type ValidationError

type ValidationError struct {
	Field   string      // Field that failed validation
	Value   interface{} // Invalid value
	Limit   interface{} // Limit that was exceeded
	Message string      // Error description
	Cause   error       // Underlying error
}

ValidationError represents a validation failure.

func NewValidationError

func NewValidationError(field, message string, cause error) *ValidationError

NewValidationError creates a new validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

type Validator

type Validator interface {
	// ValidateMarkerLength validates that a marker length is valid and within remaining data.
	ValidateMarkerLength(length int, remaining int) error

	// ValidateCoefficient validates that a DCT coefficient value fits in int16 range.
	ValidateCoefficient(value int) error

	// ValidateTableIndex validates that an index is within valid table bounds.
	ValidateTableIndex(index int, maxIndex int) error

	// ValidatePosition validates that a position is within valid bounds.
	ValidatePosition(pos int, maxPos int) error

	// ValidateSliceAccess validates that a slice index is within bounds.
	ValidateSliceAccess(index int, sliceLen int) error

	// SafeMultiply performs overflow-safe multiplication.
	SafeMultiply(a, b int) (int, error)

	// SafeAdd performs overflow-safe addition.
	SafeAdd(a, b int) (int, error)
}

Validator defines the interface for input validation functions. All validation methods return an error if validation fails, or nil if successful.

func NewValidator

func NewValidator() Validator

NewValidator creates a new Validator instance.

type VariantInfo

type VariantInfo struct {
	// SOFType indicates the JPEG variant type (SOF0, SOF1, SOF2, etc.)
	SOFType SOFType

	// SupportLevel indicates the level of encoder detection support:
	// - "full": Complete signature detection support
	// - "partial": Limited support (focus on APP markers)
	// - "not-applicable": Encoder detection not meaningful for this variant
	SupportLevel string

	// VariantSpecificHints contains encoder clues specific to this variant.
	// For progressive: scan patterns
	// For arithmetic: coding characteristics
	// For lossless: not populated
	VariantSpecificHints []string

	// Precision is the sample precision in bits (8 or 12)
	Precision int

	// IsProgressive indicates if this is a progressive JPEG
	IsProgressive bool

	// IsArithmetic indicates if arithmetic coding is used (vs Huffman)
	IsArithmetic bool

	// IsLossless indicates if this is a lossless JPEG variant
	IsLossless bool

	// ScanCount is the number of scans detected (for progressive JPEGs)
	ScanCount int

	// ScanPatterns contains analyzed scan progression patterns
	ScanPatterns []ScanPattern
}

VariantInfo contains information about the JPEG variant and its encoder detection support level.

type VisualEvent

type VisualEvent struct {
	X         uint16 // X coordinate
	Y         uint16 // Y coordinate
	Timestamp uint64 // Timestamp in microseconds
	Polarity  int8   // Polarity: +1 for ON, -1 for OFF
}

VisualEvent represents a single event from an event-based sensor.

type VisualEventData

type VisualEventData struct {
	X         uint16 // X coordinate
	Y         uint16 // Y coordinate
	Timestamp uint64 // Timestamp in microseconds
	Polarity  int8   // +1 for ON, -1 for OFF
}

VisualEventData represents a single visual event.

type WorkerPool

type WorkerPool interface {
	// Submit submits a job for processing.
	Submit(job func())

	// Wait waits for all submitted jobs to complete.
	Wait()

	// Shutdown gracefully shuts down the worker pool.
	Shutdown()

	// WorkerCount returns the number of workers.
	WorkerCount() int
}

WorkerPool manages concurrent processing workers.

func NewWorkerPool

func NewWorkerPool(workers int) WorkerPool

NewWorkerPool creates a new worker pool with the specified number of workers. If workers is 0, it defaults to the number of CPUs.

Directories

Path Synopsis
Package decoder provides a unified interface for decoding JPEG family formats.
Package decoder provides a unified interface for decoding JPEG family formats.
internal
jpeg2000
Package jpeg2000 provides JPEG 2000 encoding and decoding support.
Package jpeg2000 provides JPEG 2000 encoding and decoding support.
jpeg2000/htj2k
Package htj2k implements HTJ2K block decoding.
Package htj2k implements HTJ2K block decoding.
jpeg2000/jp3d
Package jp3d implements JPEG 2000 Part 10 (JP3D) volumetric image support as specified in ISO/IEC 15444-10.
Package jp3d implements JPEG 2000 Part 10 (JP3D) volumetric image support as specified in ISO/IEC 15444-10.
jpeg2000/jpip
Package jpip implements JPEG 2000 Part 9 (JPIP) client response parsing as specified in ISO/IEC 15444-9.
Package jpip implements JPEG 2000 Part 9 (JPIP) client response parsing as specified in ISO/IEC 15444-9.
jpeg2000/jpm
Package jpm provides JPEG 2000 Part 6 (JPM) compound image support per ISO/IEC 15444-6.
Package jpm provides JPEG 2000 Part 6 (JPM) compound image support per ISO/IEC 15444-6.
jpeg2000/jpsec
Package jpsec implements JPEG 2000 Part 8 (JPSEC) security features as specified in ISO/IEC 15444-8.
Package jpsec implements JPEG 2000 Part 8 (JPSEC) security features as specified in ISO/IEC 15444-8.
jpeg2000/jpwl
Package jpwl implements JPEG 2000 Part 11 (JPWL) wireless transmission support as specified in ISO/IEC 15444-11.
Package jpwl implements JPEG 2000 Part 11 (JPWL) wireless transmission support as specified in ISO/IEC 15444-11.
jpeg2000/jpx
Package jpx provides JPEG 2000 Part 2 (JPX) extended file format support.
Package jpx provides JPEG 2000 Part 2 (JPX) extended file format support.
jpeg2000/mct
Package mct implements the Multi-Component Transform (MCT) defined by ISO/IEC 15444-1 §F.4.9 for JPEG 2000.
Package mct implements the Multi-Component Transform (MCT) defined by ISO/IEC 15444-1 §F.4.9 for JPEG 2000.
jpeg2000/mj2
Package mj2 implements Motion JPEG 2000 (MJ2/MJP2) per ISO/IEC 15444-3.
Package mj2 implements Motion JPEG 2000 (MJ2/MJP2) per ISO/IEC 15444-3.
jpeg2000/security
Package security provides security validation for JPEG 2000 parsing
Package security provides security validation for JPEG 2000 parsing
jpeg2000/trellis
Package trellis implements trellis quantization for JPEG 2000 Part 2 (JPX).
Package trellis implements trellis quantization for JPEG 2000 Part 2 (JPX).
jpegai
Package jpegai provides parsing and decoding support for JPEG AI (ISO/IEC 6046) neural network-based image compression.
Package jpegai provides parsing and decoding support for JPEG AI (ISO/IEC 6046) neural network-based image compression.
jpegls
Package jpegls implements JPEG-LS encoding and decoding per ITU-T T.87/ISO 14495-1 with T.870 extensions for higher bit depths.
Package jpegls implements JPEG-LS encoding and decoding per ITU-T T.87/ISO 14495-1 with T.870 extensions for higher bit depths.
jpegpleno
Package jpegpleno provides decoding support for JPEG Pleno.
Package jpegpleno provides decoding support for JPEG Pleno.
jpegpleno/holography
Package holography provides decoding support for JPEG Pleno Holography.
Package holography provides decoding support for JPEG Pleno Holography.
jpegpleno/lightfield
Package lightfield provides types and decoding for JPEG Pleno Light Field.
Package lightfield provides types and decoding for JPEG Pleno Light Field.
jpegpleno/pointcloud
Package pointcloud provides types and decoding for JPEG Pleno Point Cloud.
Package pointcloud provides types and decoding for JPEG Pleno Point Cloud.
jpegsystems/jlink
Package jlink implements parsing for JPEG Linked Media Format (JLINK) as defined in ISO/IEC 19566-7 (JPEG Systems Part 7).
Package jlink implements parsing for JPEG Linked Media Format (JLINK) as defined in ISO/IEC 19566-7 (JPEG Systems Part 7).
jpegsystems/jpeg360
Package jpeg360 implements parsing for JPEG 360 panoramic image metadata as defined in ISO/IEC 19566-6 (JPEG Systems Part 6).
Package jpeg360 implements parsing for JPEG 360 panoramic image metadata as defined in ISO/IEC 19566-6 (JPEG Systems Part 6).
jpegsystems/jumbf
Package jumbf implements parsing for JPEG Universal Metadata Box Format (JUMBF) as defined in ISO/IEC 19566-5 (JPEG Systems Part 5).
Package jumbf implements parsing for JPEG Universal Metadata Box Format (JUMBF) as defined in ISO/IEC 19566-5 (JPEG Systems Part 5).
jpegtrust
Package jpegtrust implements parsing and validation for JPEG Trust metadata as defined in ISO/IEC 21617 (JPEG Trust).
Package jpegtrust implements parsing and validation for JPEG Trust metadata as defined in ISO/IEC 21617 (JPEG Trust).
jpegxe
Package jpegxe provides JPEG XE (ISO/IEC 21122-5) decoding support for event camera data.
Package jpegxe provides JPEG XE (ISO/IEC 21122-5) decoding support for event camera data.
jpegxs
Package jpegxs provides JPEG XS (ISO/IEC 21122) codestream decoding.
Package jpegxs provides JPEG XS (ISO/IEC 21122) codestream decoding.
jpegxs/container
Package container provides JPEG XS (ISO/IEC 21122-3) transport format parsing.
Package container provides JPEG XS (ISO/IEC 21122-3) transport format parsing.
jpegxt
Package jpegxt provides JPEG XT (ISO/IEC 18477) HDR extension support.
Package jpegxt provides JPEG XT (ISO/IEC 18477) HDR extension support.
logging
Package logging provides logging helper functions for internal packages.
Package logging provides logging helper functions for internal packages.
safeconv
Package safeconv provides safe integer type conversions with overflow detection.
Package safeconv provides safe integer type conversions with overflow detection.
Package security provides common security limits and validation utilities for all JPEG family decoders.
Package security provides common security limits and validation utilities for all JPEG family decoders.

Jump to

Keyboard shortcuts

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