moonjls

    Portable JPEG-LS lossless and near-lossless image coding

    jpeg-ls
    charls
    image
    compression
    wasm
    Download zip
    Author
    Version
    0.1.1
    License
    BSD-3-Clause
    Last updated
    1 hour ago
    Downloads
    6

    No dependencies

    #MoonJLS

    MoonJLS 是 纯 MoonBit JPEG-LS 无损与近无损图像编解码库。它直接处理 2–16 位无符号样本,按 JPEG-LS 的预测、上下文统计和 Golomb 熵编码压缩图像;常见使用对象是科研灰度图、多通道原始图像和需要保留整数样本的 Wasm 工具。

    项目由 SUNhuixin-2007 维护,源码仓库为 MoonJLS。本地工程保存在 D:\CodexProjects\MoonJLS;Mooncakes 命名空间为 SHX-ai-nb/moonjls。GitHub 已从 SHX-ai-nb 改名为 SUNhuixin-2007,Mooncakes 保留原用户名,二者归属于同一个 GitHub 账号。项目范围见 兼容性清单,选题与迁移价值见 申报书 和 生态差异。

    #实现方式

    项目是 CharLS 2.4.2 的受限范围 MoonBit 移植与工程适配,不是原生库绑定。移植保留成熟实现中 regular/run 模式的上下文演化和样本重建规则,采用 MoonBit 的位流、类型、错误和资源约束接口;编译后的核心不调用 CharLS、Python 或 C FFI。具体文件与来源见 THIRD_PARTY.md。

    JPEG-LS 与普通 JPEG 的核心方法不同:它按邻域中值预测样本、量化梯度选择上下文、适应性更新预测偏差,并使用 regular/run 两种编码路径。JPEG-LS 不使用普通 JPEG 的 DCT/量化质量参数,NEAR 明确限制每个样本允许的绝对误差。

    #本地运行

    已验证工具链为 moonc 0.10.17+093cb8f9c,CI 固定同版编译器和标准库。文件工具另需 Node.js 22+,开发用独立互操作脚本另需 Python;核心只依赖 MoonBit 标准库。

    moon check --target all --deny-warn moon test --target wasm --deny-warn moon test --target wasm-gc --deny-warn moon test --target js --deny-warn moon run cmd/demo --target js moon fmt --check

    原生运行需要平台 C 编译器与链接环境。各目标的最终实测结果以验证记录为准,不把静态检查等同于运行通过。

    #转换本地文件

    以下命令会自动构建 MoonBit JS 宿主适配器。核心压缩与解压都在 MoonBit 中完成,Python/CharLS 不参与日常转换。

    node scripts/moonjls.mjs encode input.pgm output.jls node scripts/moonjls.mjs encode input.ppm output.jls --near 3 --interleave line node scripts/moonjls.mjs inspect output.jls node scripts/moonjls.mjs decode output.jls restored.pnm node scripts/moonjls.mjs decode output.jls restored.pam --pam

    输出必须是尚不存在的文件;失败会清理本次创建的部分输出。灰度/RGB 可用 PNM,Alpha 可用 PAM。二进制 P5/P6 编码按行读入;多分量 none 会回访输入并保留压缩输出。PAM/ASCII 编码及文件解码物化整图,报告如实标记。inspect 只检查结构,返回 entropy_validated=false;完整 decode 才验证熵数据与零填充。

    首版 JPEG-LS 的 MAXVAL 必须为 2^bits−1,非满范围 MAXVAL 显式拒绝。两通道文件默认用 none,其他限制见兼容性表。

    #库接口

    Image.samples 始终为逐行、像素交织的无符号整数数组,bits_per_sample 保留 2–16 位精度;输入码流采用何种交织方式,不改变库的样本布局。

    let original : @jls.Image = {
    frame: { width: 2, height: 2, bits_per_sample: 12, components: 1 },
    samples: [0, 4095, 73, 2048],
    }
    let packed = @jls.encode(original)
    let restored = @jls.decode(packed[:])

    近无损编码使用 EncodeOptions.near。例如 near=3 的承诺是解码样本与原样本的绝对误差不超过 3,不是“质量 3”或平均误差。

    let options = { ..@jls.EncodeOptions::default(), near: 3 }
    let packed = @jls.encode(original, options~)

    在自己的 moon.pkg 中导入 "SHX-ai-nb/moonjls" @jls;安装命令为 moon add SHX-ai-nb/moonjls@0.1.1。

    #独立验证

    imagecodecs==2026.11.11 所附 CharLS 用于独立验证:先由 CharLS 写码流,再由 MoonJLS 解码;反方向由 MoonJLS 写码流,再由 CharLS 解码。比较的是样本数组和误差边界,压缩字节不要求与另一个合法编码器完全相同。

    python -m pip install --target work/pydeps -r scripts/requirements-dev.txt python scripts/interop.py

    独立向量只使用公开合成图像;不含车辆日志、患者资料或商业图像。测试范围与限制见 docs/VALIDATION.md。一键复现完整本地检查:

    python scripts/validate.py

    记录包含三个运行目标各 46 项测试、独立编解码验证与真实文件测试;Windows native 未执行,远程 CI 与发布进度见 发布状态。

    #源码规模

    python scripts/count_loc.py python scripts/count_loc.py --minimum 4000

    统计将核心、测试、示例工具分开,排除依赖、构建、生成接口、注释和空行;严格口径进一步排除纯结构符号。当前严格有效核心为 4,118 行,非空非注释核心为 5,178 行。精确口径与逐文件统计保存在 本地验证记录,不承诺主办方采用相同计数方式。

    #资料与授权

    本地实现和测试不代表获得 ITU、ISO、AUTOSAR 或医学用途认证。比赛报名表仍需按官方要求提交;仓库公开和模块发布不等于已经报名或通过审核。

    本轮本地代码检查与修复明细见 LOCAL_REVIEW.md。大尺寸 PNM 文件交换、预算边界和异常输入均有回归测试。

    JlsError

    pub(all) suberror JlsError {
    Invalid(Int, String)
    Truncated(Int, String)
    Unsupported(Int, String)
    Limit(Int, String)
    }

    JlsError::describe

    fn JlsError::describe(self : JlsError) -> String

    ByteSource

    pub struct ByteSource {
    size : UInt64
    read_at : (UInt64, Int) -> Bytes raise JlsError
    }

    Immutable host byte source. Reads must return exactly length bytes, with offsets expressed as UInt64 so callers need not narrow large file positions.

    ByteSource::from_bytes

    fn ByteSource::from_bytes(bytes : Bytes) -> ByteSource

    ByteSource::new

    fn ByteSource::new(size : UInt64, read_at : (UInt64, Int) -> Bytes raise JlsError) -> ByteSource

    ByteSource::read

    fn ByteSource::read(self : ByteSource, offset : UInt64, length : Int) -> Bytes raise JlsError

    ByteSource::size

    fn ByteSource::size(self : ByteSource) -> UInt64

    ByteSource::slice

    fn ByteSource::slice(self : ByteSource, offset : UInt64, length : UInt64) -> ByteSource raise JlsError

    ChannelMetrics

    pub(all) struct ChannelMetrics {
    component : Int
    samples : Int
    maximum_error : Int
    mean_error : Double
    mean_absolute_error : Double
    mean_squared_error : Double
    } derive(Eq,
    Debug
    )

    CodestreamFramer

    pub struct CodestreamFramer {
    limits : Limits
    batch_images : Int
    buffer :
    Buffer

    state : FramingState
    marker : Int
    length : Int
    remaining : Int
    images : UInt64
    received : UInt64
    closed : Bool
    failed : Bool
    }

    Incremental framing of concatenated JPEG-LS codestreams. This stores one compressed image, not decoded pixels, and does not pretend to decode a scan before all its compressed bytes have arrived. Chunks may split any marker.

    CodestreamFramer::buffered_bytes

    fn CodestreamFramer::buffered_bytes(self : CodestreamFramer) -> Int

    CodestreamFramer::feed

    fn CodestreamFramer::feed(self : CodestreamFramer, chunk : BytesView) -> Array[Bytes] raise JlsError

    Returns complete compressed images after structural inspection. A failed feed poisons the object; reset is explicit and discards its incomplete tail.

    CodestreamFramer::finish

    fn CodestreamFramer::finish(self : CodestreamFramer) -> Unit raise JlsError

    CodestreamFramer::image_count

    fn CodestreamFramer::image_count(self : CodestreamFramer) -> UInt64

    CodestreamFramer::input_bytes

    fn CodestreamFramer::input_bytes(self : CodestreamFramer) -> UInt64

    CodestreamFramer::new

    fn CodestreamFramer::new(limits? : Limits, batch_images? : Int) -> CodestreamFramer raise JlsError

    CodestreamFramer::reset

    fn CodestreamFramer::reset(self : CodestreamFramer) -> Unit

    ColorTransform

    pub(all) enum ColorTransform {
    Identity
    Hp1
    Hp2
    Hp3
    } derive(Eq,
    Debug
    )

    Reversible HP transforms are a common CharLS extension, not part of T.87. They are restricted here to lossless, full-range 8/16-bit three-channel RGB.

    ColorTransform::code

    fn ColorTransform::code(self : ColorTransform) -> Int

    ColorTransform::from_code

    fn ColorTransform::from_code(value : Int) -> ColorTransform raise JlsError

    EncodeOptions

    pub(all) struct EncodeOptions {
    near : Int
    interleave : Interleave
    preset : Preset
    } derive(Eq,
    Debug
    )

    EncodeOptions::default

    fn EncodeOptions::default() -> EncodeOptions

    EncodeOptions::from_json

    EncodeOptions::to_json

    EncodingChoice

    pub(all) struct EncodingChoice {
    point : RatePoint
    codestream : Bytes
    attempts : Int
    } derive(Eq,
    Debug
    )

    ErrorMetrics

    pub(all) struct ErrorMetrics {
    samples : Int
    maximum_error : Int
    mean_error : Double
    mean_absolute_error : Double
    mean_squared_error : Double
    channels : Array[ChannelMetrics]
    } derive(Eq,
    Debug
    )

    ErrorMetrics::psnr

    fn ErrorMetrics::psnr(self : ErrorMetrics, maximum : Int) -> Double? raise JlsError

    ErrorMetrics::to_json

    ErrorMetrics::within_near

    fn ErrorMetrics::within_near(self : ErrorMetrics, near : Int) -> Bool raise JlsError

    Frame

    pub(all) struct Frame {
    width : Int
    height : Int
    bits_per_sample : Int
    components : Int
    } derive(Eq,
    Debug
    )

    Frame::from_json

    fn Frame::from_json(json :
    Json
    , limits? : Limits) -> Frame raise JlsError

    Frame::packed_size

    fn Frame::packed_size(self : Frame, layout : PixelLayout, limits? : Limits) -> Int raise JlsError

    Minimum buffer span containing every active sample. A final padding row is not required; internal row and plane padding still contributes to this span.

    Frame::sample_count

    fn Frame::sample_count(self : Frame, limits? : Limits) -> Int raise JlsError

    Frame::to_json

    FramingState

    type FramingState

    Image

    pub(all) struct Image {
    frame : Frame
    samples : Array[Int]
    } derive(Eq,
    Debug
    )

    Canonical row-major, pixel-interleaved unsigned samples, regardless of the codestream's interleave mode. Values stay exact up to unsigned 16 bits.

    Image::color_transform

    fn Image::color_transform(self : Image, transform : ColorTransform, inverse? : Bool, limits? : Limits) -> Image raise JlsError

    Image::copy_row_into

    fn Image::copy_row_into(self : Image, y : Int, destination : Array[Int], components? : Array[Int], limits? : Limits) -> Unit raise JlsError

    Copies selected channels into a caller-owned reusable row buffer. Validation completes before the destination is touched, so failed calls are atomic.

    Image::crop

    fn Image::crop(self : Image, x : Int, y : Int, width : Int, height : Int, limits? : Limits) -> Image raise JlsError

    Image::from_json

    fn Image::from_json(json :
    Json
    , limits? : Limits) -> Image raise JlsError

    Image::from_packed

    fn Image::from_packed(frame : Frame, data : BytesView, layout? : PixelLayout, limits? : Limits) -> Image raise JlsError

    Image::plane

    fn Image::plane(self : Image, component : Int, limits? : Limits) -> Image raise JlsError

    Image::row

    fn Image::row(self : Image, y : Int, limits? : Limits) -> Array[Int] raise JlsError

    Image::sample

    fn Image::sample(self : Image, x : Int, y : Int, component? : Int, limits? : Limits) -> Int raise JlsError

    Image::to_json

    Tagged image interchange keeps sample precision and component order explicit. Every unsigned 16-bit sample is exactly representable by a JSON number.

    Image::to_packed

    fn Image::to_packed(self : Image, layout? : PixelLayout, limits? : Limits) -> Bytes raise JlsError

    Produces the minimum containing span and initializes all internal padding to zero. Neither byte order nor planar packing changes numeric sample values.

    Image::validate

    fn Image::validate(self : Image, maximum? : Int, limits? : Limits) -> Unit raise JlsError

    Image::with_plane

    fn Image::with_plane(self : Image, component : Int, plane : Image, limits? : Limits) -> Image raise JlsError

    Info

    pub(all) struct Info {
    frame : Frame
    scans : Array[ScanInfo]
    metadata : Array[Segment]
    consumed : Int
    } derive(Eq,
    Debug
    )

    Info::color_transform

    fn Info::color_transform(self : Info) -> ColorTransform raise JlsError

    Info::spiff_header

    fn Info::spiff_header(self : Info, limits? : Limits) -> SpiffHeader? raise JlsError

    Finds and validates a SPIFF v2 header and end-of-directory wrapper. Directory entry payloads are preserved as opaque APP8 data, not interpreted as images.

    Info::to_json

    fn Info::to_json(self : Info, include_metadata? : Bool, limits? : Limits) ->
    Json
    raise JlsError

    Interleave

    pub(all) enum Interleave {
    None
    Line
    Sample
    } derive(Eq,
    Debug
    )

    Interleave::code

    fn Interleave::code(self : Interleave) -> Int

    Limits

    pub(all) struct Limits {
    pixels : Int
    samples : Int
    compressed_bytes : Int
    metadata_bytes : Int
    segments : Int
    } derive(Eq,
    Debug
    )

    Limits::default

    fn Limits::default() -> Limits

    PamImage

    pub(all) struct PamImage {
    image : Image
    maximum : Int
    tuple_type : String
    } derive(Eq,
    Debug
    )

    PAM supplies a raw file interchange for two- and four-component images, including alpha. Tuple labels describe samples; the codec never color-converts.

    PamImage::encode

    fn PamImage::encode(self : PamImage, limits? : Limits) -> Bytes raise JlsError

    PamImage::validate

    fn PamImage::validate(self : PamImage, limits? : Limits) -> Unit raise JlsError

    PixelLayout

    pub(all) struct PixelLayout {
    order : PixelOrder
    storage : SampleStorage
    row_stride : Int
    plane_stride : Int
    } derive(Eq,
    Debug
    )

    A zero stride selects tight packing. For planar buffers plane_stride selects the distance between channel starts; all byte offsets are nonnegative.

    PixelLayout::from_json

    Structural decoding only; packed_size(frame) verifies nonoverlap and budgets.

    PixelLayout::tight

    fn PixelLayout::tight(storage? : SampleStorage, order? : PixelOrder) -> PixelLayout

    PixelLayout::to_json

    PixelOrder

    pub(all) enum PixelOrder {
    Interleaved
    Planar
    } derive(Eq,
    Debug
    )

    PnmImage

    pub(all) struct PnmImage {
    image : Image
    maximum : Int
    } derive(Eq,
    Debug
    )

    Netpbm image plus the exact PNM MAXVAL. The Image precision is the smallest JPEG-LS-supported precision that represents MAXVAL; values are never scaled.

    PnmImage::encode

    fn PnmImage::encode(self : PnmImage, ascii? : Bool, limits? : Limits) -> Bytes raise JlsError

    PnmSource

    pub struct PnmSource {
    source : ByteSource
    frame : Frame
    maximum : Int
    raster_offset : UInt64
    row_bytes : Int
    sample_bytes : Int
    limits : Limits
    }

    Binary P5/P6 raster descriptor. Only the bounded header and requested rows are read. The caller keeps the source stable; no filesystem handles are owned.

    PnmSource::encode

    fn PnmSource::encode(self : PnmSource, options? : EncodeOptions) -> Bytes raise JlsError

    PnmSource::frame

    fn PnmSource::frame(self : PnmSource) -> Frame

    PnmSource::maximum

    fn PnmSource::maximum(self : PnmSource) -> Int

    PnmSource::open

    fn PnmSource::open(source : ByteSource, start? : UInt64, limits? : Limits) -> PnmSource raise JlsError

    PnmSource::raster_offset

    fn PnmSource::raster_offset(self : PnmSource) -> UInt64

    PnmSource::row

    fn PnmSource::row(self : PnmSource, y : Int, components? : Array[Int]) -> Array[Int] raise JlsError

    Selected components preserve caller order, with each pixel's values adjacent. An omitted selection reads all channels; repeated component indices fail.

    Preset

    pub(all) struct Preset {
    maximum : Int
    threshold1 : Int
    threshold2 : Int
    threshold3 : Int
    reset : Int
    } derive(Eq,
    Debug
    )

    A zero field selects its standard default; resolved presets contain no zeros.

    Preset::automatic

    fn Preset::automatic() -> Preset

    Preset::defaults

    fn Preset::defaults(maximum : Int, near : Int) -> Preset raise JlsError

    Preset::from_json

    fn Preset::from_json(json :
    Json
    ) -> Preset raise JlsError

    Reads the raw zero-means-default preset. Resolution against precision and NEAR remains mandatory before using it for a scan.

    Preset::resolve

    fn Preset::resolve(self : Preset, bits_per_sample : Int, near : Int) -> Preset raise JlsError

    Preset::to_json

    RatePoint

    pub(all) struct RatePoint {
    near : Int
    interleave : Interleave
    compressed_bytes : Int
    maximum_error : Int
    mean_squared_error : Double
    } derive(Eq,
    Debug
    )

    RatePoint::to_json

    Region

    pub(all) struct Region {
    x : Int
    y : Int
    width : Int
    height : Int
    } derive(Eq,
    Debug
    )

    Region::from_json

    fn Region::from_json(json :
    Json
    , frame : Frame) -> Region raise JlsError

    Region::full

    fn Region::full(frame : Frame) -> Region

    Region::intersection

    fn Region::intersection(self : Region, other : Region) -> Region? raise JlsError

    Region::to_json

    Region::validate

    fn Region::validate(self : Region, frame : Frame) -> Unit raise JlsError

    RowEncoder

    pub struct RowEncoder {
    push_row : (Array[Int]) -> Unit raise JlsError
    finish_stream : () -> Unit raise JlsError
    position : () -> Int
    written : () -> Int
    }

    Push-based encoder holding two reconstructed rows per component and partial entropy bytes. The host controls row arrival and output backpressure.

    RowEncoder::bytes_written

    fn RowEncoder::bytes_written(self : RowEncoder) -> Int

    RowEncoder::finish

    fn RowEncoder::finish(self : RowEncoder) -> Unit raise JlsError

    RowEncoder::new

    fn RowEncoder::new(frame : Frame, emit : (Bytes) -> Unit raise JlsError, options? : EncodeOptions, limits? : Limits) -> RowEncoder raise JlsError

    For canonical row order, grayscale uses NONE and multiple components use LINE/SAMPLE. Planar multi-scan encoding requires encode_rows with row revisits. The sink receives a header immediately; commit the sink only after finish. A sink may inspect counters but must not reenter push or finish on this encoder. Reentry is rejected before mutation; an uncaught sink error poisons the stream.

    RowEncoder::push

    fn RowEncoder::push(self : RowEncoder, row : Array[Int]) -> Unit raise JlsError

    RowEncoder::rows_written

    fn RowEncoder::rows_written(self : RowEncoder) -> Int

    SampleHistogram

    pub struct SampleHistogram {
    bits : Int
    components : Int
    maximum_samples : Int
    bins : Array[Array[Int]]
    total : Int
    }

    Incremental exact integer histograms. Marginal entropy is descriptive; it is not a promise about JPEG-LS's contextual compressed size or a quality score.

    SampleHistogram::count

    fn SampleHistogram::count(self : SampleHistogram, component : Int, value : Int) -> Int raise JlsError

    SampleHistogram::merge

    fn SampleHistogram::merge(self : SampleHistogram, other : SampleHistogram) -> Unit raise JlsError

    Combines disjoint batches, checking compatibility and capacity before mutation. Self-merge intentionally doubles the observations if the budget permits it.

    SampleHistogram::new

    fn SampleHistogram::new(bits : Int, components : Int, maximum_samples? : Int) -> SampleHistogram raise JlsError

    SampleHistogram::nonzero_bins

    fn SampleHistogram::nonzero_bins(self : SampleHistogram, component : Int, maximum_bins? : Int) -> Array[(Int, Int)] raise JlsError

    SampleHistogram::push

    fn SampleHistogram::push(self : SampleHistogram, samples : ArrayView[Int]) -> Unit raise JlsError

    A rejected row changes no bins; callers may correct it and retry.

    SampleHistogram::push_image

    fn SampleHistogram::push_image(self : SampleHistogram, image : Image, limits? : Limits) -> Unit raise JlsError

    SampleHistogram::quantile

    fn SampleHistogram::quantile(self : SampleHistogram, component : Int, probability : Double) -> Int raise JlsError

    Nearest-rank quantile with floor(p*(n-1)); endpoints select actual extrema.

    SampleHistogram::reset

    fn SampleHistogram::reset(self : SampleHistogram) -> Unit

    SampleHistogram::sample_count

    fn SampleHistogram::sample_count(self : SampleHistogram) -> Int

    SampleHistogram::subtract

    fn SampleHistogram::subtract(self : SampleHistogram, other : SampleHistogram) -> Unit raise JlsError

    Removes a known sub-batch atomically; mismatching bin counts are rejected.

    SampleHistogram::summary

    fn SampleHistogram::summary(self : SampleHistogram, component : Int) -> SampleSummary raise JlsError

    SampleStorage

    pub(all) enum SampleStorage {
    U8
    U16Big
    U16Little
    } derive(Eq,
    Debug
    )

    SampleStorage::bytes

    fn SampleStorage::bytes(self : SampleStorage) -> Int

    SampleSummary

    pub(all) struct SampleSummary {
    samples : Int
    minimum : Int
    maximum : Int
    distinct : Int
    most_frequent : Int
    mean : Double
    variance : Double
    entropy_bits : Double
    } derive(Eq,
    Debug
    )

    SampleSummary::to_json

    ScanInfo

    pub(all) struct ScanInfo {
    components : Array[Int]
    near : Int
    interleave : Interleave
    preset : Preset
    entropy_offset : Int
    entropy_end : Int
    restart_interval : Int
    } derive(Eq,
    Debug
    )

    ScanInfo::to_json

    Segment

    pub(all) struct Segment {
    marker : Int
    offset : Int
    data : Bytes
    } derive(Eq,
    Debug
    )

    SpiffHeader

    pub(all) struct SpiffHeader {
    frame : Frame
    color_space : Int
    resolution_units : Int
    vertical_resolution : UInt
    horizontal_resolution : UInt
    } derive(Eq,
    Debug
    )

    SpiffHeader::default

    fn SpiffHeader::default(frame : Frame) -> SpiffHeader

    SpiffHeader::to_json

    SpiffHeader::validate

    fn SpiffHeader::validate(self : SpiffHeader, limits? : Limits) -> Unit raise JlsError

    compare_images

    fn compare_images(expected : Image, actual : Image, limits? : Limits) -> ErrorMetrics raise JlsError

    Exact integer differences are accumulated as binary64 sums; the maximum absolute error is exact. No implicit precision or color conversion occurs.

    decode

    fn decode(data : BytesView, limits? : Limits) -> Image raise JlsError

    Strict single-image decode. Marker inspection alone never substitutes for entropy decoding, reconstructed sample range checks and exact end padding.

    decode_region

    fn decode_region(data : BytesView, region : Region, components? : Array[Int], limits? : Limits) -> Image raise JlsError

    JPEG-LS prediction prevents arbitrary entropy seeking. This decodes the entire image's scans but retains only the requested pixel rectangle and channels. Memory is proportional to scan row width plus the selected output rectangle.

    decode_rows

    fn decode_rows(data : BytesView, emit : (Int, Array[Int], Array[Int]) -> Unit raise JlsError, limits? : Limits) -> Info raise JlsError

    Reconstructs samples with two rows per scan component, without allocating a full destination image. The compressed source remains resident. Each callback owns a fresh row and component list; later decoder activity cannot modify it. Callbacks are incremental: discard partial output if this function raises.

    encode

    fn encode(image : Image, options? : EncodeOptions, limits? : Limits) -> Bytes raise JlsError

    Encodes baseline JPEG-LS using reconstructed neighbors; NEAR is a per-sample maximum absolute error bound, never an image quality percentage.

    encode_pam

    fn encode_pam(image : Image, maximum? : Int, tuple_type? : String, limits? : Limits) -> Bytes raise JlsError

    encode_pnm

    fn encode_pnm(image : Image, maximum? : Int, ascii? : Bool, limits? : Limits) -> Bytes raise JlsError

    Emits a deterministic PGM or PPM without scaling or color-space conversion. MAXVAL defaults to the image's full precision and may be preserved separately from parse_pnm when a producer used a non-power-of-two range.

    encode_restarted

    fn encode_restarted(image : Image, interval : Int, options? : EncodeOptions, limits? : Limits) -> Bytes raise JlsError

    Writes standard restart intervals measured in JPEG-LS scan lines. Every interval resets predictive/context state and terminates its own stuffed bits. This makes restart decoding testable with independent CharLS decoders even though CharLS's encoder does not itself expose restart-marker generation.

    encode_rows

    fn encode_rows(frame : Frame, row_at : (Int, Array[Int]) -> Array[Int] raise JlsError, options? : EncodeOptions, limits? : Limits) -> Bytes raise JlsError

    Low-memory input contract: for each requested row return only the selected component indices, in pixel-interleaved order. Planar scans may revisit rows. The host must provide stable pixels for the duration of an encoding operation.

    encode_to_budget

    fn encode_to_budget(image : Image, maximum_bytes : Int, near_levels : Array[Int], modes : Array[Interleave], maximum_attempts? : Int, work_sample_budget? : UInt64, limits? : Limits) -> EncodingChoice? raise JlsError

    Finds the best measured candidate fitting a byte budget, prioritizing maximum error, then MSE, then bytes. None means no tested candidate fit; it does not assert that the image cannot be encoded under that budget by any algorithm.

    encode_transformed

    fn encode_transformed(image : Image, transform : ColorTransform, options? : EncodeOptions, limits? : Limits) -> Bytes raise JlsError

    hex_decode

    fn hex_decode(text : String) -> Bytes raise JlsError

    hex_encode

    fn hex_encode(data : BytesView) -> String

    inspect

    fn inspect(data : BytesView, limits? : Limits) -> Info raise JlsError

    Parses marker boundaries and metadata without reconstructing pixels. Successful inspection establishes structure, not semantic validity of the entropy codes.

    merge_planes

    fn merge_planes(planes : ArrayView[Image], limits? : Limits) -> Image raise JlsError

    parse_pam

    fn parse_pam(data : BytesView, limits? : Limits) -> PamImage raise JlsError

    Parses one PAM P7 image. Numeric fields are unique; repeated TUPLTYPE lines concatenate in order. Unknown keys fail explicitly, and raster bytes are never tokenized as whitespace or comments after the ENDHDR line.

    parse_pnm

    fn parse_pnm(data : BytesView, limits? : Limits) -> PnmImage raise JlsError

    Parses one complete P2/P3/P5/P6 image. Concatenated images are intentionally rejected. Binary samples start after exactly one separator (or CRLF), so a first pixel containing whitespace or '#' is never treated as header text.

    rate_curve

    fn rate_curve(image : Image, near_levels : Array[Int], modes : Array[Interleave], maximum_attempts? : Int, work_sample_budget? : UInt64, limits? : Limits) -> Array[RatePoint] raise JlsError

    Measures real encodings rather than estimating an unspecified JPEG quality scale. Candidate count and total processed samples have separate budgets.

    strip_metadata

    fn strip_metadata(data : BytesView, limits? : Limits) -> Bytes raise JlsError

    Removes annotations without decoding pixels. Essential HP transform markers remain, because dropping them would change the reconstructed color values.

    tile_regions

    fn tile_regions(frame : Frame, tile_width : Int, tile_height : Int, maximum_tiles? : Int) -> Array[Region] raise JlsError

    Plans a bounded nonoverlapping partition without decoding or copying pixels.

    verify_near

    fn verify_near(expected : Image, actual : Image, near : Int, limits? : Limits) -> ErrorMetrics raise JlsError

    with_metadata

    fn with_metadata(data : BytesView, metadata : Array[Segment], limits? : Limits) -> Bytes raise JlsError

    Replaces application annotations and comments. SPIFF/HP markers must be created through their typed APIs, so arbitrary payloads cannot mislabel pixels.

    with_spiff

    fn with_spiff(data : BytesView, header : SpiffHeader, limits? : Limits) -> Bytes raise JlsError

    write_pam_rows

    fn write_pam_rows(frame : Frame, row_at : (Int) -> Array[Int] raise JlsError, emit : (Bytes) -> Unit raise JlsError, maximum? : Int, tuple_type? : String, limits? : Limits) -> UInt64 raise JlsError

    Emits one PAM row at a time, including two/four-channel alpha rasters. The host must discard partial output if any later callback fails.

    write_pnm_rows

    fn write_pnm_rows(frame : Frame, row_at : (Int) -> Array[Int] raise JlsError, emit : (Bytes) -> Unit raise JlsError, maximum? : Int, limits? : Limits) -> UInt64 raise JlsError

    Emits binary P5/P6 incrementally. Every row is checked before it is written; earlier callback effects remain if a later row fails, so hosts commit on success.